Skip to content

fix(lammps): free model deviation buffers#5803

Merged
njzjz merged 3 commits into
deepmodeling:masterfrom
njzjz:codex/code-scan-5644
Jul 20, 2026
Merged

fix(lammps): free model deviation buffers#5803
njzjz merged 3 commits into
deepmodeling:masterfrom
njzjz:codex/code-scan-5644

Conversation

@njzjz

@njzjz njzjz commented Jul 14, 2026

Copy link
Copy Markdown
Member

Closes #5644.

Summary

  • initialize all six model-deviation gather buffer pointers to nullptr;
  • centralize allocation and growth in a shared ensure_model_deviation_buffers() helper;
  • reuse process-count buffers across repeated init_style() calls instead of overwriting live allocations;
  • grow the four atom-sized buffers through LAMMPS Memory::grow() when the global atom count increases;
  • release all six buffers from the shared base-class destructor;
  • use the same lifecycle path for both DeepMD and DeepSpin pair styles;
  • add a repeated run(0) / clear() smoke test for reinitialization and pair destruction.

Root cause

init_style() created the communication arrays whenever atomic model-deviation output was enabled, but repeated LAMMPS runs can call init_style() again on the same pair object. Those creates overwrote the stored pointers. The compute paths separately destroyed and recreated four arrays on atom-count growth, while the pair destructor released none of the six arrays.

The pair object is the sole owner of these buffers. Allocation, reuse, growth, and destruction are now handled in one base-class implementation, with nullptr initialization making every cleanup path safe.

Why existing tests missed this

The existing model-deviation tests validate numerical output. Leaking a LAMMPS-managed buffer does not change those values or necessarily crash, so the old implementation passes ordinary functional tests.

The new repeated-init/clear test is intentionally only a lifecycle smoke: it exercises repeated init_style() and pair destruction and can catch obvious double-free or use-after-free regressions. It is not presented as a leak detector, and the old implementation also passes it while leaking.

A direct stable old-fail/new-pass demonstration requires a dedicated LeakSanitizer build with appropriate handling of unrelated TensorFlow/Python/LAMMPS allocations. No RSS or process-memory threshold was added because it would be allocator- and timing-dependent.

Validation

  • built the DeePMD LAMMPS plugin, TensorFlow backend, and TensorFlow op against stable_22Jul2025_update2;
  • built a matching Update2 LAMMPS shared library and Python wrapper;
  • existing test_pair_deepmd_model_devi: passed;
  • new test_pair_deepmd_model_devi_atomic_reinit_clear_smoke: passed;
  • combined targeted result: 2 passed;
  • clang-format 22.1.5 check;
  • ruff format .;
  • ruff check .;
  • git diff --check;
  • independent final review: no findings.

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

Summary by CodeRabbit

  • Bug Fixes

    • Improved allocation, cleanup, and reuse of model-deviation output buffers during repeated pair initialization and simulation teardown.
    • Prevented stale pointers and potential memory leaks by centralizing model-deviation buffer management.
    • Ensures model-deviation gather buffers correctly grow with system size changes.
  • Tests

    • Added a smoke test that runs the DeepMD model-deviation workflow twice and then clears the simulation to verify cleanup.
    • Extended CI with a LeakSanitizer step for model-deviation teardown coverage.

Centralize allocation, growth, reuse, and destruction of atomic model-deviation communication buffers for DeepMD and DeepSpin pair styles.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.1
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
Copilot AI review requested due to automatic review settings July 14, 2026 21:07

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.

@dosubot dosubot Bot added the bug label Jul 14, 2026
@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change centralizes model-deviation communication buffer allocation, resizing, and destruction, initializes buffer pointers safely, updates DeepMD and DeepSpin call paths, and adds repeated-run cleanup and LSan coverage.

Changes

Model-deviation buffer lifecycle

Layer / File(s) Summary
Centralize buffer lifecycle
source/lmp/pair_base.h, source/lmp/pair_base.cpp
Adds shared buffer management helpers, initializes buffer pointers to nullptr, uses the helper during init_style(), and destroys buffers in the destructor.
Pair-style integration and lifecycle validation
source/lmp/pair_deepmd.cpp, source/lmp/pair_deepspin.cpp, source/lmp/tests/test_lammps.py, .github/workflows/test_cc.yml
Routes DeepMD and DeepSpin atomic model-deviation paths through shared buffer sizing and adds repeated-run smoke-test and LSan workflow coverage for teardown.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested labels: Python, C++

Suggested reviewers: njzjz-bot, wanghan-iapcm

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately describes the main change: freeing model-deviation buffers in LAMMPS.
Linked Issues check ✅ Passed The changes address #5644 by null-initializing, centralizing cleanup, handling reinitialization, and adding lifecycle regression coverage.
Out of Scope Changes check ✅ Passed The added test and CI step directly support the buffer leak fix and lifecycle coverage, with no clear unrelated changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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.

@njzjz
njzjz requested a review from wanghan-iapcm July 14, 2026 22:49

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

Reviewed via the code-review skill. Correct and complete: all six model-devi buffers are nullptr-initialized, ensure_model_deviation_buffers() reuses counts/displacements (nprocs is fixed for the run) and memory->grow()s the four atom buffers (grow-on-nullptr == create in LAMMPS), and destroy_model_deviation_buffers() frees all six from the base destructor (destroy-on-nullptr is a safe no-op, so no double-free), covering both PairDeepMD and PairDeepSpin. The sweep found no other unfreed model-devi buffers, and the destructor-never-freed gap has existed since #628. Both the atomic and non-atomic branches are exercised (the latter via existing teardown).

One non-blocking note: the new reinit/clear smoke test genuinely exercises the fixed paths, but it cannot fail pre-fix in CI -- the leak is silent (not a crash/UAF), and the LAMMPS pytest step is gated with 'if: not matrix.check_memleak', so the -fsanitize=leak leg never runs it while every leg that runs it has no sanitizer. As written it is a crash-safety/coverage guard, not a leak-regression guard (which the PR body candidly acknowledges). Wiring source/lmp/tests into the check_memleak leg (or a dedicated LSan job) would turn it into a real regression guard for this leak class. LGTM.

Execute the focused model-deviation reinitialization and clear test in the TensorFlow/PyTorch leak-sanitizer leg so the fixed buffer leak becomes CI-observable.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.4
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
@njzjz-bot

Copy link
Copy Markdown
Contributor

I addressed the non-blocking CI coverage note in f3fba652b.

The focused test_pair_deepmd_model_devi_atomic_reinit_clear_smoke case now runs in the TensorFlow/PyTorch -fsanitize=leak matrix leg with the repository's LSan suppressions and installed LAMMPS plugin. This turns the test from crash-safety-only coverage into a leak-observable regression while avoiding the full LAMMPS suite and the sanitizer-incompatible Paddle leg.

The workflow YAML, formatting, Ruff, and repository commit hooks passed locally; the actual LSan execution is delegated to CI.

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

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

🧹 Nitpick comments (1)
.github/workflows/test_cc.yml (1)

100-103: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use matrix variables for environment configuration.

For consistency with other test steps in this workflow and to prevent potential mismatches if the build matrix configuration changes in the future, consider dynamically setting the framework flags based on the matrix variables instead of hardcoding them.

♻️ Proposed refactor
-          ENABLE_TENSORFLOW: "1"
-          ENABLE_PYTORCH: "1"
-          ENABLE_JAX: "1"
-          ENABLE_PADDLE: "0"
+          ENABLE_TENSORFLOW: ${{ matrix.enable_tensorflow && '1' || '0' }}
+          ENABLE_PYTORCH: ${{ matrix.enable_pytorch && '1' || '0' }}
+          ENABLE_JAX: ${{ matrix.enable_tensorflow && '1' || '0' }}
+          ENABLE_PADDLE: ${{ matrix.enable_paddle && '1' || '0' }}
🤖 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 @.github/workflows/test_cc.yml around lines 100 - 103, Update the framework
environment flags in the workflow test step to derive their enabled values from
the corresponding build matrix variables rather than hardcoded strings. Apply
this consistently to ENABLE_TENSORFLOW, ENABLE_PYTORCH, ENABLE_JAX, and
ENABLE_PADDLE while preserving the matrix’s current enable/disable behavior.
🤖 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.

Nitpick comments:
In @.github/workflows/test_cc.yml:
- Around line 100-103: Update the framework environment flags in the workflow
test step to derive their enabled values from the corresponding build matrix
variables rather than hardcoded strings. Apply this consistently to
ENABLE_TENSORFLOW, ENABLE_PYTORCH, ENABLE_JAX, and ENABLE_PADDLE while
preserving the matrix’s current enable/disable behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: d2d247a8-76a9-4f05-b7a9-e963b23af725

📥 Commits

Reviewing files that changed from the base of the PR and between 43d6a41 and f3fba65.

📒 Files selected for processing (1)
  • .github/workflows/test_cc.yml

@njzjz
njzjz enabled auto-merge July 16, 2026 15:51
@codecov

codecov Bot commented Jul 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.30769% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.58%. Comparing base (3122138) to head (2790ad6).
⚠️ Report is 21 commits behind head on master.

Files with missing lines Patch % Lines
source/lmp/pair_base.cpp 91.66% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #5803      +/-   ##
==========================================
- Coverage   79.83%   78.58%   -1.25%     
==========================================
  Files        1029     1054      +25     
  Lines      117576   121758    +4182     
  Branches     4311     4411     +100     
==========================================
+ Hits        93869    95689    +1820     
- Misses      22156    24502    +2346     
- Partials     1551     1567      +16     

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

@njzjz

njzjz commented Jul 18, 2026

Copy link
Copy Markdown
Member Author

Possible reviewers based on changed lines, exact file history, and exact-file review history:

  • @OutisLi — 49 reviews on exact changed files (.github/workflows/test_cc.yml, source/lmp/pair_base.cpp, source/lmp/pair_base.h, source/lmp/pair_deepmd.cpp, source/lmp/pair_deepspin.cpp).
  • @iProzd — 7 commits on changed files (source/lmp/pair_base.cpp, source/lmp/pair_base.h, source/lmp/pair_deepmd.cpp, source/lmp/pair_deepspin.cpp, source/lmp/tests/test_lammps.py).

No review request was made automatically.

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

@njzjz
njzjz requested review from OutisLi and iProzd July 18, 2026 07:25
@njzjz
njzjz marked this pull request as draft July 19, 2026 05:25
auto-merge was automatically disabled July 19, 2026 05:25

Pull request was converted to draft

@njzjz
njzjz removed request for OutisLi and iProzd July 19, 2026 18:00
Remove the workflow-only LSan regression step while retaining the underlying LAMMPS buffer fix and its test.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.4
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
Signed-off-by: njzjz-bot <njzjz.bot@gmail.com>
@njzjz
njzjz marked this pull request as ready for review July 19, 2026 20:08
@njzjz
njzjz enabled auto-merge July 19, 2026 20:08
@njzjz
njzjz added this pull request to the merge queue Jul 19, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to no response for status checks Jul 20, 2026
@njzjz
njzjz added this pull request to the merge queue Jul 20, 2026
Merged via the queue into deepmodeling:master with commit c8a2d85 Jul 20, 2026
57 checks passed
@njzjz
njzjz deleted the codex/code-scan-5644 branch July 20, 2026 20:43
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.

[Code scan] Free LAMMPS model-deviation atomic communication buffers

4 participants