Skip to content

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

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

njzjz wants to merge 14 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

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
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@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 Resolved
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 87.02128% with 61 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.78%. Comparing base (e5a3340) to head (e2b31ef).

Files with missing lines Patch % Lines
source/lmp/pair_deepmd.cpp 86.62% 26 Missing and 35 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #5943      +/-   ##
==========================================
- Coverage   78.98%   78.78%   -0.20%     
==========================================
  Files        1258     1258              
  Lines      152609   153050     +441     
  Branches     5238     5332      +94     
==========================================
+ Hits       120532   120577      +45     
- Misses      30141    30504     +363     
- Partials     1936     1969      +33     

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

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 Resolved

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");
  }

@njzjz-bot njzjz-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.

Three independent full reviews were completed against this exact head. The findings below are blocking because one currently fails CI and the other two can produce inconsistent compact-evaluation behavior.

The Codex quota is close to resetting, so I am concentrating the remaining token budget on these reviews.

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

Comment thread source/lmp/pair_deepmd.cpp Resolved
Comment thread source/lmp/pair_deepmd.cpp Resolved
Comment thread source/lmp/tests/test_lammps_compact.py Resolved
njzjz-bot and others added 2 commits August 11, 2026 02:53
Coding-Agent: Codex
Codex-Version: codex-cli 0.144.6
Model: gpt-5.6-sol
Reasoning-Effort: xhigh

@njzjz-bot njzjz-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.

The previous cache-representation and DPLR compatibility fixes are present. I found one additional neighbor-list configuration that still violates the compact path's assumptions: neigh_modify include is not rejected and can leave a selected local atom without a populated neighbor row. Please address the new inline finding.

Validation: reproduced the neighbor-list contract with LAMMPS 22 Jul 2025 using two local atoms, group active id 1, group center id 2, atom_modify first active, neigh_modify include active, and a full neighbor list requested by pair_style zero 4.0 full. After run 0, nlocal=2 but the list contains only local row 0. Independently checked LAMMPS's NPairBin implementation (it uses atom->nfirst when includegroup is set) and this PR's direct row access. This validates the missing-row condition; I did not run the DeepMD backend itself on this configuration.

Agent: ChatGPT
Model: GPT-6 Astra Pro
Reviewed head: 835a42f

Comment thread source/lmp/pair_deepmd.cpp Resolved
Coding-Agent: Codex
Codex-Version: codex-cli 0.164.0
Model: gpt-6-astra
Reasoning-Effort: xhigh
Coding-Agent: Codex
Codex-Version: codex-cli 0.164.0
Model: gpt-6-astra
Reasoning-Effort: xhigh

@wanghan-iapcm wanghan-iapcm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The PR addresses #5942: LAMMPS may evaluate a DeePMD model on a dynamically selected subsystem instead of every atom. Three new pair_style deepmd options - center_group, environment_cutoff and include_molecule - select the center atoms, the periodic minimum-image environment around them, and optionally promote partially selected molecules to whole molecules; atoms outside the selection are marked with type -1 and removed by the existing DeepPot compaction, neighbour remap and output scatter path, with a single-rank packed fast path that drops them before the API boundary. The selection is synchronised across MPI ranks, cached neighbour mappings are invalidated when it changes, ranks with no selected atoms are handled, deviation summaries are normalised by the selected atoms, and the mode is rejected for deepmd/kk, fix dplr and neigh_modify exclude/include. The PR also changes extract("cut_coul") so the model cutoff is only advertised as a Coulomb cutoff for pppm/dplr.

Five non-blocking findings are inline. None is blocking, and the highest severity is a coverage gap on the new environment-cutoff semantics.

Comment thread source/lmp/pair_deepmd.cpp Resolved
Comment thread source/lmp/pair_base.cpp Resolved
Comment thread source/lmp/pair_deepmd.cpp Resolved
Comment thread source/lmp/tests/test_lammps_compact.py Resolved
Comment thread source/lmp/pair_deepmd.cpp Resolved
Coding-Agent: Codex
Codex-Version: codex-cli 0.167.0
Model: gpt-6.1-sol
Reasoning-Effort: xhigh
@njzjz
njzjz requested a review from wanghan-iapcm November 15, 2026 14:11

@njzjz-bot njzjz-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.

Agent: dot

[P1] Resolve the duplicate init_style declaration in the merged tree before integration.

The source branch has one declaration, but GitHub's tested merge a6657fd contains void init_style() override; twice in source/lmp/pair_deepmd.h, at lines 49 and 51. This is a compile error, not a numerical-test failure: the Linux C++ build and C++ tests fail with “cannot be overloaded”, and the macOS wheel build reports “class member cannot be redeclared”. The branch's serial test results therefore do not establish that its merge with master builds. Reconcile the overlapping declaration when updating the branch and verify the merged-tree build.

Evidence:

void init_style() override;
void compute(int, int) override;
void init_style() override;

Linux build: https://github.com/deepmodeling/deepmd-kit/actions/runs/43722518866/job/132837359311
macOS wheel: https://github.com/deepmodeling/deepmd-kit/actions/runs/43722518861/job/132837359324

Coding-Agent: Codex
Codex-Version: codex-cli 0.167.0
Model: gpt-6.1-sol
Reasoning-Effort: xhigh
@njzjz

njzjz commented Nov 15, 2026

Copy link
Copy Markdown
Member Author

CI exposed a semantic merge issue with the newer master: both branches independently added PairDeepMD::init_style, so Git's conflict-free test merge contained duplicate declarations/definitions. Fixed in eb1aa6654 by merging master and retaining its common/long-range initialization exactly once, then calling a separate compact-selection initialization helper.

Rebuilt the native CPU libraries and LAMMPS plugin together after the merge. All 19 serial compact-selection tests pass, including the five review regressions addressed in 1b66b7063. The two MPI cases were not run locally because the available LAMMPS library is serial; hosted qualification remains responsible for those. Review requests remain with @OutisLi and @wanghan-iapcm.

Coding agent: Codex
Codex version: codex-cli 0.167.0
Model: gpt-6.1-sol
Reasoning effort: xhigh

@wanghan-iapcm wanghan-iapcm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This PR adds an opt-in compact evaluation mode to pair_style deepmd: with center_group and
environment_cutoff, the model is evaluated on a dynamically selected subsystem (excluded atoms are
passed to the backend as virtual atoms, or removed outright by a single-rank LAMMPS-side packed
path), with whole-molecule promotion, MPI tag gathering, deviation normalization over the selected
atoms, a cut_coul extraction fix for hybrid styles, a Kokkos rejection, documentation and a large
LAMMPS test suite. The compact-evaluation idea and the test coverage are solid; the comments below
concern one wrong-result case in the multi-model path, a documented output that no test pins down,
and two configurations that are accepted but evaluate a silently truncated subsystem.

The multi-model generic path reuses the persistent all_force buffer without clearing the entries
of atoms excluded from the selection, so a deviation step can add a previous step's force to atoms
that have left the selection. The documented global virial is never asserted under compact
selection. Compact selection is not rejected for models with a long-range module, and a hybrid
sub-style skip list can remove model atoms from the compact subsystem that the full path still
evaluates.

Comment thread source/lmp/pair_deepmd.cpp Outdated
}
}
dener = all_energy[0];
dforce = all_force[0];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

dforce = all_force[0] reuses a buffer that the backend does not clear, so atoms that left the compact selection keep a previous deviation step's force.

Trigger. Compact selection on the generic (non-packed) path — multi-rank, DP_LAMMPS_DISABLE_COMPACT_PACKING, or any case excluded from packed mode (aparam_from_compute, ttm, ...) — with numb_models > 1 and an out_freq model-deviation step, where an atom is selected at one deviation step and outside the selection at a later one.

Call chain. apply_compact_selection (source/lmp/pair_deepmd.cpp:368-370) sets model_types[ii] = -1 for excluded atoms; can_use_compact_packing() is false, so the code reaches deep_pot_model_devi.compute(all_energy, all_force, ...) and then this line. all_force is the persistent member std::vector<std::vector<double> > all_force (source/lmp/pair_base.h:74), and each backend's select_map writes only the entries whose forward map is non-negative — if (idx_map[ii] >= 0) in source/api_cc/src/common.cc:1042 (the TF/PT/JAX/PD wrappers share the same contract), so the slots of type -1 atoms are never written and keep their value from the previous deviation step. DeepPotModelDevi::compute only resizes.

Consequence. The loop below (:1189-1194) adds dforce to f for all nall atoms, so an excluded atom receives the stale force of the earlier step and its trajectory is perturbed on that step. std_f is computed from the same buffer, so the per-atom atomic deviation of those atoms is reported non-zero. Energy, global deviation statistics and atomic energy/virial are unaffected (they are filtered or zero-filled).

Expected behaviour. Atoms marked -1 must contribute zero force on every step; e.g. zero all_force/all_energy (or at least the entries of type -1 atoms) before the deviation evaluation. Note that the packed path is safe (scatter_compact_output builds a zero-filled array) and the single-model path is safe (dforce is a fresh local), so a targeted fix on this branch is enough.


If `center_group` and `environment_cutoff` are set, `pair_style deepmd` evaluates the model on a dynamically selected compact subsystem. Every atom in `center_group` is included. Every other model atom within `environment_cutoff` of a center atom is included using periodic minimum-image distances; orthogonal and restricted triclinic cells are supported. With the default `include_molecule yes`, a cutoff hit promotes every DeePMD-mapped atom with the same positive LAMMPS molecule ID, so a solvent molecule represented by the model is not truncated. With `include_molecule no`, only the individual atom is selected.

Atoms outside the compact subsystem are removed before the model backend is called. Their DeePMD force, atomic energy, atomic virial, and atomic model-deviation output are zero. Energy and global virial are accumulated from the compact subsystem normally. When multiple models are supplied, every model receives the same selection, and the force and virial deviation summaries are normalized by the number of selected model atoms rather than the full LAMMPS atom count.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The sentence "Energy and global virial are accumulated from the compact subsystem normally" states a guarantee that no test in this PR checks.

Trigger. Any compact run with vflag set — a barostat, compute pressure, or the default thermo output that includes press.

Call chain. PairDeepMD::compute → the dvirial accumulation block (source/lmp/pair_deepmd.cpp:1201-1208 for the full-system path, and the packed equivalent), which is unchanged by this PR and therefore relies on the selection/scatter code being correct.

Consequence. A regression in the compact scatter (for example a virial normalized by the full LAMMPS atom count, or a missing stride-9 scatter) would not fail any test: the compact suite asserts total energy, forces and pe/atom only, and grepping the compact tests finds no press, virial or centroid assertion. Users of NPT or of per-atom pressure decomposition would silently get wrong values.

Expected behaviour. Compact evaluation must produce the same global virial as full-system evaluation for the same configuration. A test comparing lammps.eval("press") against the full-system run, at least for one deviation step and one multi-rank case, would pin the documented guarantee.

"every model carries one; use models with long-range modules "
"throughout, or a periodic system.");
}
init_compact_selection();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

init_compact_selection() is called without rejecting models that carry a long-range module, so compact evaluation silently truncates the long-range sum.

Trigger. A periodic system (periodic in all three dimensions) evaluated with a model that has_long_range(), plus center_group and environment_cutoff, with at least one model atom outside the environment.

Call chain. init_style computes long_range a few lines above (:1645-1646) and already fails fast for the other long-range incompatibilities — mixed periodic dimensions (:1649) and an ensemble with a long-range model on a fully non-periodic system (:1659). init_compact_selection() then checks exclusions, tags, molecule IDs and fix dplr, but not long_range. At evaluation, atoms outside the subsystem are passed as type -1 (or removed by the packed path), so the long-range module sums over the compact nodes only.

Consequence. The long-range part of the energy and forces is wrong, with no warning or error, for a configuration the code otherwise accepts. The long-range documentation states that the module sums over every pair of atoms of a non-periodic system, or over the images of the cell of a fully periodic one; restricting the subsystem to the environment_cutoff neighbourhood violates that contract, and unlike the documented environment_cutoff caveats this one cannot be satisfied by any cutoff choice.

Expected behaviour. Compact selection should be rejected when the evaluated model (or any model of a deviation ensemble) has a long-range module, in the same style as the adjacent checks: if (long_range && compact_selection_enabled_) error->all(...).

const int jnum = list->numneigh[ii];
int* const jlist = list->firstneigh[ii];
for (int jj = 0; jj < jnum; ++jj) {
select_environment_atom(ii, jlist[jj] & NEIGHMASK, false);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The environment search walks only the DeepMD sub-style's neighbor list, so under pair_style hybrid a type pair assigned to another sub-style removes model atoms from the compact subsystem.

Trigger. pair_style hybrid with deepmd as one sub-style and pair_coeff I J <other> ... for a type pair whose atoms are both mapped to the model, where an atom is within environment_cutoff of a center and reachable through that pair only.

Call chain. LAMMPS gives each hybrid sub-style a neighbor list with the pair skipped (iskip/ijskip, npair_skip.cpp). This loop only sees list->numneigh[ii] / list->firstneigh[ii], so the skipped partner is never passed to select_environment_atom. init_compact_selection rejects neigh_modify exclude for exactly this reason (:586): user exclusions remove otherwise eligible pairs before the list reaches the style, and there is no bounded topology list from which to recover them. The hybrid type-pair skip is the same situation without the nex_type flag, so it is not caught.

Consequence. A model atom reachable only through such a pair is never promoted into the environment; it is marked -1 and gets no per-atom energy, whereas the non-compact path evaluates that atom as a center. Compact evaluation therefore diverges from full-system evaluation without any warning, contrary to the stated equivalence in the documentation.

Expected behaviour. Compact selection should reject the hybrid-with-skip configuration (e.g. when the style is a hybrid sub-style and its iskip/ijskip entries skip a pair between model-mapped types), or otherwise recover the skipped partners, the way the special_bonds recovery below does.

@OutisLi OutisLi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The compact path and MPI coverage are useful, but there are still three existing wrong-result cases on this head. Please clear inactive force slots at each generic ensemble deviation step, reject long-range models with compact selection unless the full long-range environment is preserved, and reject or correctly recover neighbors excluded by hybrid type-pair filtering. Please add regressions for a selected atom leaving before a later deviation step and the unsupported configurations.

@OutisLi
OutisLi requested review from OutisLi and removed request for OutisLi November 26, 2026 01:27
- Merge origin/master into feat/lammps-compact-evaluation, integrating
  compact selection with BrickNeighborList and ModelDeviation while
  retaining per-selection normalization and atom filtering in model
  deviation output.
- Zero-initialize per-step and per-ensemble force buffers and invalidate
  ensemble neighbor caches on compact selection transitions so excluded
  atoms never retain stale forces or deviations.
- Reject compact selection when any evaluated model carries a long-range
  module (has_long_range()), and document the restriction.
- Reject pair_style hybrid neighbor skip lists (iskip/ijskip) that omit
  model-mapped atom types or pairs while keeping NULL/non-model type
  skips working.
- Keep LAMMPS 23Jun2022 header compatibility via SFINAE dispatch for
  Domain::minimum_image, clear compact_is_center_ on settings() reset,
  initialize dim in PairDeepBaseModel::extract("cut_coul"), and check
  compact_selection_enabled() before PairDeepMD::init_style() in
  deepmd/kk.
- Add regression tests for global pressure/virial and centroid stress,
  atoms leaving compact selection before a later deviation step (packed
  and generic paths, out_freq 1 and 2), hybrid skip-list rejection and
  safe non-model skips, and long-range model/ensemble rejection.

Coding-Agent: Antigravity
Antigravity-Version: 1.5.23
Model: Gemini 4 Neon (High)
Reasoning-Effort: high
@njzjz-bot

Copy link
Copy Markdown
Contributor

Merged origin/master and addressed all review findings in e2b31efa8:

Merge & Upstream Integration

  • Resolved conflicts in source/lmp/pair_deepmd.{h,cpp} and source/lmp/pair_deepmd_kokkos.cpp against master's BrickNeighborList and ModelDeviation refactor, extending ModelDeviation::write with optional compact-selection filtering and selected-atom normalization.
  • Added SFINAE dispatch for Domain::minimum_image so both legacy LAMMPS 23Jun2022 and current headers compile cleanly, cleared compact_is_center_ and cache-representation state in settings(), initialized dim in PairDeepBaseModel::extract("cut_coul"), and moved the deepmd/kk compact-evaluation rejection ahead of PairDeepMD::init_style().

Review Findings Addressed

  1. Stale force / deviation slots for atoms leaving selection (@OutisLi, @wanghan-iapcm): Replaced the persistent all_force path with fresh zero-initialized per-model force buffers (dforce, model_force) via ModelDeviation, and invalidated the ensemble neighbor cache (model_deviation.start_run()) whenever compact selection or packing representation changes. Added test_compact_model_deviation_clears_atom_leaving_selection covering both packed and generic non-packed paths with out_freq 1 and 2.
  2. Global virial / pressure and centroid stress coverage (@wanghan-iapcm): Added global pressure/virial tensor assertions (press, pxx..pyz) across serial, triclinic, packed vs. generic, model-deviation, and 2-rank MPI tests, plus test_compact_centroid_stress_matches_explicit_subsystem.
  3. Long-range model rejection (@OutisLi, @wanghan-iapcm): Rejected compact selection in PairDeepMD::init_style() when long_range is true (single model or any ensemble member), updated doc/third-party/lammps-command.md, and added test_compact_selection_rejects_long_range_model and test_compact_selection_rejects_ensemble_with_long_range_model in source/lmp/tests/test_lammps_dpa4c_long_range_pt2.py.
  4. Hybrid neighbor skip lists (iskip/ijskip) (@OutisLi, @wanghan-iapcm): Added validate_compact_neighbor_list() before reading neighbor rows in apply_compact_selection() (after NeighList::post_constructor populates iskip/ijskip) to reject hybrid skip lists that omit any model-mapped type or pair while allowing skips of non-model/NULL types. Added test_compact_rejects_hybrid_skipped_model_pairs and test_compact_allows_hybrid_skipping_non_model_type.

Local Validation

  • Built native C++ libraries and libdeepmd_lmp.so (TF + PT + JAX, LAMMPS 22 Jul 2025) and syntax-checked host pair styles against LAMMPS stable_23Jun2022 (-DLAMMPS_VERSION_NUMBER=20220623).
  • pytest source/lmp/tests/test_lammps_compact.py source/lmp/tests/test_lammps_option_parsers.py -v — 55 passed (including 2-rank MPICH tests with pressure assertions).
  • pytest source/lmp/tests/test_dplr.py source/lmp/tests/test_lammps.py -v — 29 passed (3 skipped).
  • pytest source/lmp/tests/test_lammps_dpa4c_long_range_pt2.py -k "compact or periodic_boundary or model_deviation" -v (with freshly generated .pt2 fixtures) — 12 passed.
  • clang-format --dry-run --Werror, ruff check, ruff format --check, and pre-commit hooks all passed.
Coding agent: Antigravity
Antigravity version: 1.5.23
Model: Gemini 4 Neon (High)
Reasoning effort: high

This branch has not been deployed

No deployments
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.

6 participants