Skip to content

feat(lammps): add compact DeePMD evaluation - #5943

Open
njzjz wants to merge 7 commits into
deepmodeling:masterfrom
njzjz:feat/lammps-compact-evaluation
Open

feat(lammps): add compact DeePMD evaluation#5943
njzjz wants to merge 7 commits into
deepmodeling:masterfrom
njzjz:feat/lammps-compact-evaluation

Conversation

@njzjz

@njzjz njzjz commented Jul 31, 2026

Copy link
Copy Markdown
Member

Summary

  • Add center_group, environment_cutoff, and include_molecule options to pair_style deepmd.
  • Dynamically select the center group and its periodic cutoff environment, with optional whole-molecule promotion.
  • Mark excluded model atoms with type -1, reusing the existing DeepPot compaction, neighbor remapping, communication, and output-scattering path.
  • Synchronize selection across MPI ranks and invalidate cached neighbor mappings whenever the selected subsystem changes.
  • Compute model-deviation summaries over selected atoms while keeping excluded atomic outputs zero.
  • Diagnose compact evaluation as unsupported by pair_style deepmd/kk until accelerator parity is implemented.

Validation

  • cmake --build source/build --target deepmd_lmp -j2
  • pytest source/lmp/tests/test_lammps_compact.py -v — 7 passed
  • pytest source/lmp/tests/test_lammps_option_parsers.py -v — 25 passed
  • ruff check .
  • ruff format .
  • clang-format --dry-run --Werror source/lmp/pair_deepmd.cpp source/lmp/pair_deepmd.h source/lmp/pair_deepmd_kokkos.cpp
  • Repository pre-commit hooks

The compact tests cover orthogonal and restricted triclinic boxes, periodic boundary selection, complete-molecule promotion, zero outputs for excluded atoms, selected-only model deviation, cache invalidation when selection changes, cross-domain MPI selection, and ranks with no selected owned atoms.

Addresses #5942.

Coding agent: Codex
Codex version: codex-cli 0.144.6
Model: gpt-5.6-sol
Reasoning effort: xhigh

Summary by CodeRabbit

  • New Features

    • Added compact subsystem evaluation for pair_style deepmd.
    • Added options for selecting center atoms, defining environment cutoffs, and including complete molecules.
    • Added support for compact evaluation in serial and MPI simulations.
    • Added model-deviation statistics for selected atoms.
  • Bug Fixes

    • Added validation and diagnostics for invalid compact-evaluation options.
    • Clarified that compact evaluation is unavailable with pair_style deepmd/kk.
    • Corrected Coulomb cutoff handling for long-range hybrid simulations.
  • Documentation

    • Added option descriptions and usage examples for compact evaluation.

Select a periodic cutoff environment around a center group, optionally promote cutoff hits to complete molecules, and mark excluded model atoms with type -1 so existing DeepPot compaction handles inference and output scattering.

Synchronize selection across MPI ranks, invalidate cached neighbor mappings when it changes, normalize model deviation over selected atoms, document the interface, and add serial, triclinic, cache-transition, and MPI coverage.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.6
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
Copilot AI review requested due to automatic review settings July 31, 2026 11:23
@dosubot dosubot Bot added the new feature label Jul 31, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Added cutoff-based compact atom selection to pair_style deepmd. The feature selects atoms around a center group, optionally includes whole molecules, supports MPI execution, updates model inputs, and normalizes selected-atom statistics. Option parsing, validation, documentation, Kokkos handling, and regression tests were added.

Changes

Compact DeepMD evaluation

Layer / File(s) Summary
Compact selection contract and state
source/lmp/pair_deepmd.h, source/lmp/pair_deepmd.cpp
Added compact-selection state, initialization overrides, status reporting, and selection helpers.
Option parsing and validation
source/lmp/pair_deepmd.cpp, source/lmp/tests/test_lammps_option_parsers.py
Added compact-selection option parsing, validation, dependency checks, startup output, and parser regression tests.
Compact selection initialization
source/lmp/pair_deepmd.cpp
Validates atom and molecule data, resolves the center group, refreshes center tags, and applies the environment cutoff.
MPI-aware compact selection
source/lmp/pair_deepmd.cpp
Gathers tags across MPI ranks, selects cutoff environments, promotes molecules when enabled, handles special-bond exclusions, and detects selection changes.
Compute path integration
source/lmp/pair_deepmd.cpp
Applies selection before energy and force evaluation, refreshes neighbor lists, filters model-deviation statistics, and normalizes selected-atom results.
Compact evaluation validation and support
source/lmp/tests/test_lammps_compact.py, source/lmp/pair_deepmd_kokkos.cpp, doc/third-party/lammps-command.md
Tests compact evaluation across geometries, molecules, cache changes, validation cases, and MPI execution. Documents the options and rejects compact selection in Kokkos mode.
DPLR cutoff compatibility
source/lmp/pair_base.cpp, source/lmp/tests/test_dplr.py
Limits cut_coul exposure to pppm/dplr and tests long-range Coulomb integration.

Estimated code review effort: 4 (Complex) | ~50 minutes

Possibly related issues

  • deepmodeling/deepmd-kit issue 5942: Covers the cutoff-based compact pair_style deepmd evaluation implemented in this PR.

Suggested labels: C++

Suggested reviewers: copilot

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding compact DeePMD evaluation to LAMMPS.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
source/lmp/pair_deepmd.cpp (1)

303-328: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Document the neutral-element contract for the no-selection case.

If no owned atom is selected, this function leaves max, min, and sum at the caller's initial values. The single caller sets min = numeric_limits<double>::max(), max = 0, and avg = 0 before the call, so the following MPI_Reduce operations stay correct. That contract is implicit. Add a short comment so a future caller does not initialize the outputs differently and produce a wrong global minimum.

♻️ Proposed comment
+  // No owned atom is selected on this rank. Leave the caller's initial values
+  // untouched; the caller must seed them with the reduction-neutral elements
+  // (min = DBL_MAX, max = 0, sum = 0) so the MPI reductions stay correct.
   bool found = false;
   for (int ii = 0; ii < nlocal; ++ii) {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@source/lmp/pair_deepmd.cpp` around lines 303 - 328, Add a concise comment in
PairDeepMD::analyze_model_deviation documenting that when no owned atoms are
selected, max, min, and sum must remain unchanged so the caller-provided neutral
values remain valid for subsequent MPI_Reduce operations. Do not alter the
selection or accumulation logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@source/lmp/tests/test_lammps_compact.py`:
- Around line 195-201: Update the sp.run invocation in the MPI test to include
an explicit timeout=60, matching the sibling test’s subprocess behavior. Keep
the existing command, working directory, output capture, and return-code
assertion unchanged.

---

Nitpick comments:
In `@source/lmp/pair_deepmd.cpp`:
- Around line 303-328: Add a concise comment in
PairDeepMD::analyze_model_deviation documenting that when no owned atoms are
selected, max, min, and sum must remain unchanged so the caller-provided neutral
values remain valid for subsequent MPI_Reduce operations. Do not alter the
selection or accumulation logic.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a1d13ff2-7727-4980-a727-6b4d17a96c57

📥 Commits

Reviewing files that changed from the base of the PR and between 9b2582f and 8834300.

📒 Files selected for processing (6)
  • doc/third-party/lammps-command.md
  • source/lmp/pair_deepmd.cpp
  • source/lmp/pair_deepmd.h
  • source/lmp/pair_deepmd_kokkos.cpp
  • source/lmp/tests/test_lammps_compact.py
  • source/lmp/tests/test_lammps_option_parsers.py

Comment thread source/lmp/tests/test_lammps_compact.py
Keep collective send scalars mutable because the LAMMPS serial MPI stubs expose pre-const-correct void pointer parameters. Also document the model-deviation reduction seeds and bound MPI compact tests with an explicit timeout.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.6
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
Copilot AI review requested due to automatic review settings July 31, 2026 12:29

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@codecov

codecov Bot commented Jul 31, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 17.96690% with 347 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.56%. Comparing base (9b2582f) to head (e8b513f).
⚠️ Report is 5 commits behind head on master.

Files with missing lines Patch % Lines
source/lmp/pair_deepmd.cpp 18.09% 332 Missing and 12 partials ⚠️
source/lmp/pair_base.cpp 0.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #5943      +/-   ##
==========================================
- Coverage   79.41%   77.56%   -1.86%     
==========================================
  Files        1072     1072              
  Lines      124893   125410     +517     
  Branches     4531     4617      +86     
==========================================
- Hits        99187    97268    -1919     
- Misses      24085    26746    +2661     
+ Partials     1621     1396     -225     

☔ View full report in Codecov by Harness.
📢 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.

Only expose the DeepMD cutoff through cut_coul for pppm/dplr. This allows ordinary long-range Coulomb sub-styles to use a different cutoff under hybrid/overlay without breaking the existing DPLR split.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.6
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
Copilot AI review requested due to automatic review settings July 31, 2026 16:06

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Walk the DeepMD full-neighbor rows for center atoms instead of scanning every center against the full local-plus-ghost atom set on each step. Cache static center membership between neighbor rebuilds while retaining cutoff-crossing behavior.

Recover zero-valued special_bonds exclusions through a deferred tag lookup so compact selection remains independent of force-field exclusions. Add regression coverage for the excluded bonded-pair case.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.6
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
Copilot AI review requested due to automatic review settings August 1, 2026 14:32

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

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

Suppressed comments (3)

source/lmp/pair_deepmd.cpp:1032

  • PairDeepMD::settings resets compact-selection state but leaves compact_is_center_ intact. If pair_style deepmd is redefined (or settings re-run) without forcing a neighbor rebuild, apply_compact_selection() can reuse a same-sized compact_is_center_ cache computed for a previous center_group, producing an incorrect center/environment selection. Clear compact_is_center_ alongside the other compact-selection caches during settings().
  compact_natoms_ = 0;
  compact_center_group_id_.clear();
  compact_center_tags_.clear();
  compact_selected_.clear();

source/lmp/pair_base.cpp:588

  • PairDeepBaseModel::extract returns nullptr for "cut_coul" when not using pppm/dplr, but in that branch it does not set the out-parameter dim. Leaving output parameters uninitialized can cause undefined behavior if a caller reads dim regardless of the returned pointer. Set dim before returning nullptr for consistency with other branches.
    if (force->kspace_style == nullptr ||
        strcmp(force->kspace_style, "pppm/dplr") != 0) {
      return nullptr;
    }

source/lmp/pair_deepmd_kokkos.cpp:183

  • In pair_style deepmd/kk, the unsupported-compact-evaluation diagnostic is checked only after calling PairDeepMD::init_style(). If compact options are set but another compact-related precondition fails first (e.g., missing group, molecule IDs, or atom IDs), users may never see the intended "not supported" message. Check compact_selection_enabled() before calling PairDeepMD::init_style() so deepmd/kk always diagnoses this mode as unsupported.
  // Base setup and the full neighbor-list request.
  PairDeepMD::init_style();

  if (compact_selection_enabled()) {
    error->all(FLERR,

Comment thread source/lmp/tests/test_lammps_compact.py Fixed
Express the create_box command as one string so CodeQL does not flag implicit list-item concatenation.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.6
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
Copilot AI review requested due to automatic review settings August 1, 2026 16:23

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
source/lmp/pair_deepmd.cpp (1)

296-306: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Duplicate tags in tag_to_index can map to a far periodic image.

tag[jj] repeats for each ghost image of the same atom. emplace keeps the first insertion, so find_atom_by_tag can return a distant image index. The following select_environment_atom call passes apply_minimum_image = true, so the distance test recovers the correct value. The selected index is still an arbitrary image.

The current use is limited to the distance test and to tag[environment] or molecule[environment], and both are image-invariant. Add a short comment that states this requirement, so a later change does not read image-dependent data from the returned index.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@source/lmp/pair_deepmd.cpp` around lines 296 - 306, The tag lookup may return
an arbitrary periodic image when duplicate ghost tags exist. Add a short comment
adjacent to find_atom_by_tag or its use documenting that the returned index is
valid only for image-invariant data such as distance checks, tag, and molecule,
and must not be used to read image-dependent properties.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@source/lmp/pair_deepmd.cpp`:
- Around line 290-332: Update init_style() to reject active neigh_modify exclude
type/group/molecule settings before compact selection is used, covering all
neighbor-exclusion modes that can remove environment pairs. Keep the existing
special_bonds recovery in apply_compact_selection() unchanged.

---

Nitpick comments:
In `@source/lmp/pair_deepmd.cpp`:
- Around line 296-306: The tag lookup may return an arbitrary periodic image
when duplicate ghost tags exist. Add a short comment adjacent to
find_atom_by_tag or its use documenting that the returned index is valid only
for image-invariant data such as distance checks, tag, and molecule, and must
not be used to read image-dependent properties.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0c0df027-0ad6-4d68-ab48-9eba3bce18be

📥 Commits

Reviewing files that changed from the base of the PR and between 8421ba3 and a3aadb9.

📒 Files selected for processing (3)
  • source/lmp/pair_deepmd.cpp
  • source/lmp/pair_deepmd.h
  • source/lmp/tests/test_lammps_compact.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • source/lmp/pair_deepmd.h

Comment thread source/lmp/pair_deepmd.cpp

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

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

Suppressed comments (1)

source/lmp/tests/test_lammps_compact.py:129

  • The MPI test helper only looks for an executable named lmp. In many build/install setups (including locally built LAMMPS) the binary may have a different name/path, which would silently skip all MPI coverage for compact selection. Consider allowing an env override and/or trying common candidate names before skipping.
    mpirun = shutil.which("mpirun")
    lmp = shutil.which("lmp")
    if mpirun is None or lmp is None:
        pytest.skip("MPI compact tests require mpirun and the lmp executable")

Coding-Agent: Codex\nCodex-Version: codex-cli 0.144.6\nModel: gpt-5.6-sol\nReasoning-Effort: xhigh
Copilot AI review requested due to automatic review settings August 1, 2026 16:58

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

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

Suppressed comments (1)

source/lmp/pair_deepmd.cpp:1041

  • The compact-selection settings reset clears compact_center_tags_ and compact_selected_, but leaves compact_is_center_ intact. If the pair style is reconfigured in the same LAMMPS session (or if neighbor->ago is nonzero on the first compute), apply_compact_selection() can reuse stale center-membership flags because the recompute condition doesn’t consider compact_center_tags_ being refreshed. Clearing compact_is_center_ alongside the other compact caches avoids incorrect center detection.
  compact_center_group_id_.clear();
  compact_center_tags_.clear();
  compact_selected_.clear();

Cache a single-rank compact atom map and filtered neighbor list between LAMMPS rebuilds, update only selected coordinates on ordinary steps, and scatter forces directly unless model-deviation communication requires full arrays. Unsupported MPI and atomic-parameter configurations continue to use the generic backend selection path.

Add regression coverage comparing the packed path with the generic type-minus-one fallback.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.6
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
Copilot AI review requested due to automatic review settings August 2, 2026 02:08

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

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

Suppressed comments (2)

source/lmp/pair_deepmd.cpp:1253

  • compact_is_center_ is not reset in settings(). If pair_style deepmd is reconfigured within the same LAMMPS session, apply_compact_selection() may reuse stale cached center membership (since it only rebuilds compact_is_center_ on size mismatch/neighbor rebuild), leading to incorrect compact selection.
  compact_center_group_id_.clear();
  compact_center_tags_.clear();
  compact_selected_.clear();

source/lmp/pair_deepmd_kokkos.cpp:183

  • deepmd/kk checks compact_selection_enabled() after calling PairDeepMD::init_style(), which can trigger compact-selection initialization/error paths and may prevent the intended "unsupported" diagnostic from being shown. Check and error out before calling PairDeepMD::init_style() so users reliably get the deepmd/kk-specific message.
  // Base setup and the full neighbor-list request.
  PairDeepMD::init_style();

  if (compact_selection_enabled()) {
    error->all(FLERR,
               "pair style deepmd/kk does not yet support center_group compact "
               "evaluation; use pair style deepmd");
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants