Skip to content

feat(lammps): support Cartesian native-spin magnetic forces - #6084

Merged
OutisLi merged 7 commits into
deepmodeling:masterfrom
OutisLi:feat/lammps-cartesian-magnetic-force
Oct 18, 2026
Merged

OutisLi merged 7 commits into
deepmodeling:masterfrom
OutisLi:feat/lammps-cartesian-magnetic-force

Conversation

@OutisLi

@OutisLi OutisLi commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Implements #6077, fixes #6075, and supersedes #6078. This revision builds on the original implementation by @OutisLi-Bot (credited in the commit), rebases it onto current master, and replaces the weak/optional regression checks with tests of the actual LAMMPS adapter.

  • magnetic_force precession remains the default and preserves the existing moment/hbar conversion.
  • magnetic_force cartesian stores -dE/dS with the energy-per-model-spin conversion, including zero moments; currently requires units metal.
  • Pair::extract("fm_cartesian_force", dim) exposes a scalar integer (dim == 0, precession = 0, Cartesian = 1).
  • The host and Kokkos scatter paths use the selected convention without changing communication or introducing allocations/transfers. Register the host style in the runtime plugin as well.

Regression coverage and CI repair

The model-independent test_lammps_plugin.py checks unsuffixed dpa4spin availability without loading a model or gating on an inference backend. It supports the CI LAMMPS_PLUGIN_PATH autoload path and explicit DEEPMD_TEST_PLUGIN loading. The host factory and registration are outside LMP_KOKKOS; this closes #6075 without changing magnetic-force conventions or Kokkos aliases.

The new adapter tests check all three Cartesian components against energy finite differences at zero, tiny (1e-8), and finite moments; default/explicit precession equivalence; nonmagnetic atoms; unchanged mechanical force/energy; pair scaling and repeated compute; extraction; invalid/missing/duplicate options; and non-metal rejection. PyTorch-enabled LAMMPS CI explicitly requires the model fixture, bindings, and plugin registration instead of silently skipping them.

The previous C++ CI failure was reproduced with PyTorch 2.11 and OMP_NUM_THREADS=1: CPU SIMD gather codegen references an undeclared tmp42. Disabling loop-tail vectorization still fails. A scoped cpp.simdlen=1 context around this small test-fixture export only avoids the defect. Production export settings and CUDA device selection are unchanged, and the setting is restored afterward.

CUDA Kokkos regression

The CUDA C++ job uses the same Python-prefix MPICH distribution for mpi4py, DeePMD, LAMMPS, plugins, and launcher. Ubuntu 24.04's MPICH package can start independent singleton worlds (upstream report); avoiding it also removes its leaked host-LTO compiler flags, so the earlier job-local NVCC workaround is no longer needed. An early two-rank probe checks communicator size, rank gathering, and actual MPI library paths before the long model/build stages. The integration runner also checks the requested rank count against both mpi4py and native LAMMPS.

The CUDA job now separately builds matching Kokkos-enabled LAMMPS and plugin libraries, exports a compressed float32 canonical native-spin archive, and runs explicit atom_style spin/kk, pair_style dpa4spin/kk, and run_style verlet/kk with Kokkos enabled. The required test mode fails on missing CUDA, MPI, fixture, or plugin prerequisites. The ordinary host test suite does not silently substitute for this test.

The new regression compares the same canonical archive through the host adapter and one-/two-rank GPU adapters: all atom-ID-ordered magnetic forces, mechanical forces, and total energy; convention extraction; default/explicit precession; zero, tiny, and finite moments; repeated compute, pair scaling, and two-style hybrid/overlay accumulation. The two-rank system has interacting atoms on both sides of its domain boundary. Tiny-moment precession is normalized before comparison, and a live zero-moment Cartesian gradient makes a forced-precession kernel fail. Communication is host-staged, so this does not require or claim CUDA-aware MPI coverage.

Validation

  • Fresh DeePMD C++ libraries and runtime plugin built against PyTorch 2.11 CPU.
  • LAMMPS stable_22Jul2025_update2 built with SPIN/KSPACE/EXTRA-FIX/MOLECULE/PLUGIN.
  • Actual fixture generator succeeded with one thread and a fresh Inductor cache.
  • pytest -q source/lmp/tests/test_dpa4spin_magnetic_force_convention.py: 10 passed, using the default generated artifact and mandatory-test mode; independently rerun.
  • Additional artifact finite differences checked all nine Ni magnetic-force components. A separate runtime check confirmed two host hybrid/overlay contributions add correctly in both conventions.
  • Kokkos Serial LAMMPS and plugin builds succeeded, including the modified scatter kernel and the dedicated script's exact library/plugin loading check.
  • The new compressed fixture's deterministic weights/tables and live zero/tiny/finite spin derivatives were checked with CPU reference kernels; nonmagnetic rows are exactly zero. CUDA archive export subsequently succeeded in CI on c985896e.
  • On 21053699, the actual C++ CUDA job passed: the unified MPICH 5.0.2 two-rank/library-path preflight; CUDA Kokkos LAMMPS/plugin build and canonical fixture export; all 6 /kk integration tests, covering zero/tiny/finite moments, genuine one-/two-rank convention comparisons, and overlay accumulation; all C++ ctests; the ordinary LAMMPS suite (295 passed, 24 skipped); and i-PI (8 passed). The runner explicitly verifies verlet/kk and both mpi4py/native-LAMMPS rank counts.
  • The new runner's full host path was executed for all three moment cases. Assertion-sensitivity checks reject substituted precession output; these are not a GPU mutation run.
  • The optional GPU module skips in the ordinary suite; mandatory mode errors on this CPU-only environment instead of skipping.
  • The full GPU Python suite passed on 21053699: 14,070 passed, 8,709 skipped (5:01:19).
  • Check results on 21053699: 54 successful, 2 skipped (the PyPI publishing jobs), with no failed or pending checks. One unchanged CPU LMDB training test initially failed with an already-open-environment error; rerunning only that failed job succeeded, without code changes or restarting CUDA jobs.
  • Repository-wide Ruff check/format, focused isort/clang-format, shell syntax, workflow YAML parsing, and git diff --check passed.

Model-independent registration validation (aa3bb292)

  • Fresh backend-neutral DeePMD plugins (ALLOW_NO_BACKEND=ON, all inference backends disabled) and matching LAMMPS stable_22Jul2025_update2 builds passed the new test both without Kokkos and with Kokkos Serial. Explicit plugin loading and CI-style autoloading each passed in fresh Python processes, with no model fixture.
  • A separate runtime probe verified that the host style was absent before loading and registered afterward. With Kokkos enabled, the unsuffixed style and all three existing /kk aliases were available.
  • Removing only the host registration made the new test fail; restoring it made the test pass. The mutation was not committed.
  • Repository-wide Ruff check/format, focused isort, and git diff --check passed. This follow-up adds only the standalone regression test; production code and CI workflows are unchanged. No new CUDA run or full-CI result is claimed for this test-only commit.

Coverage limits

This development environment has no GPU and cannot run two-rank communication; the real one-/two-rank CUDA Kokkos validation above was executed in GitHub CI on 21053699. GPU energy finite differences are not claimed by the new adapter-equivalence tests, and no actual GPU mutation run is claimed. Communication is host-staged rather than CUDA-aware MPI. The six-atom MPI regression is not a large-system communication-buffer stress test. The full GPU Python suite and the remaining CPU/static checks also passed on 21053699.

Fixes #6077
Fixes #6075

Summary by CodeRabbit

  • New Features
    • The LAMMPS dpa4spin host and Kokkos pair styles support an optional magnetic_force cartesian setting, which uses the raw energy gradient with respect to spin. Cartesian mode requires units metal; precession remains the default.
    • Check the selected convention through LAMMPS’s fm_cartesian_force extraction value.
    • The host dpa4spin pair style is available as a LAMMPS runtime plugin.
  • Documentation
    • Updated the spin-model guides with force conventions, archive compatibility, unit requirements, and usage examples.

Preserve the default precession convention and expose Cartesian -dE/dS
for native-spin integrators. Replace algebra-only checks with mandatory
LAMMPS adapter finite differences, zero/tiny-moment, scaling and parser
regressions. Scope the PyTorch CPU SIMD workaround to the test fixture.

Based on the implementation in deepmodeling#6078.

Co-authored-by: OutisLi-Bot <44916828+OutisLi-Bot@users.noreply.github.com>
@OutisLi
OutisLi marked this pull request as ready for review October 17, 2026 13:41
Copilot AI balanced review requested due to automatic review settings October 17, 2026 13:41

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.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing. Review the Copilot code review billing settings.

@OutisLi OutisLi added the Test CUDA Trigger test CUDA workflow label Oct 17, 2026 — with ChatGPT Codex Connector
@github-actions github-actions Bot removed the Test CUDA Trigger test CUDA workflow label Oct 17, 2026
Add a separate compressed canonical fixture and explicit /kk integration
coverage for zero, tiny and finite moments, one/two MPI ranks, scaling and
overlay accumulation. Build matching CUDA Kokkos LAMMPS/plugin in the
opt-in CUDA job and require all test prerequisites.

Keep the repository's one-shot CUDA label trigger unchanged. GPU runtime
and finite-difference acceptance remain for the CUDA runner.
@OutisLi OutisLi added the Test CUDA Trigger test CUDA workflow label Oct 17, 2026 — with ChatGPT Codex Connector
@github-actions github-actions Bot removed the Test CUDA Trigger test CUDA workflow label Oct 17, 2026
Comment thread source/lmp/tests/test_dpa4spin_kokkos_magnetic_force.py Fixed
@coderabbitai

coderabbitai Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Review in 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 8a7b9a57-5864-419c-bc09-72663f55604d
📥 Commits

Reviewing files that changed from the base of the PR and between 9459630 and 2105369.

📒 Files selected for processing: 4
  • .github/workflows/test_cuda.yml
  • source/install/test_lammps_kokkos.sh
  • source/lmp/tests/run_mpi_dpa4spin_conventions.py
  • source/lmp/tests/test_dpa4spin_kokkos_magnetic_force.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

📝 Walkthrough

The host and Kokkos DPA4Spin pair styles now support Cartesian magnetic forces alongside the default precession convention. The change adds convention selection and extraction, registers the host pair style as a plugin, and adds CPU and CUDA Kokkos regression coverage.

Changes: DPA4Spin Magnetic-Force Convention

Layer / File(s) Summary
Host convention and pair-style registration
source/lmp/pair_dpa4spin.cpp, source/lmp/pair_dpa4spin.h, source/lmp/plugin/deepmdplugin.cpp, doc/model/dpa4c.md, examples/spin/dpa4c/lmp/*
The host pair style accepts magnetic_force precession or magnetic_force cartesian, defaults to precession, and rejects Cartesian mode unless units are metal. Cartesian mode uses energy-unit conversion without moment scaling; precession mode retains moment and (\hbar) scaling. fm_cartesian_force exposes the selected mode, and the plugin registers the host pair style.
Kokkos scaling and CUDA test build
source/lmp/pair_dpa4spin_kokkos.cpp, source/install/test_lammps_kokkos.sh, .github/workflows/test_cuda.yml
The Kokkos pair style applies mode-specific magnetic-force scaling. The CUDA test script builds MPI-enabled Kokkos LAMMPS and the DeepMD plugin, checks the loaded pair style, and runs the Kokkos magnetic-force test. The CUDA workflow installs MPICH and configures the test environment.
Host fixture and convention tests
source/tests/infer/gen_dpa4c_spin_lmp.py, source/install/test_cc_local.sh, source/lmp/tests/test_dpa4spin_magnetic_force_convention.py, .github/workflows/test_cc.yml
The generated native-spin fixture supports CPU tests for Cartesian force gradients, precession scaling, pair scaling, and invalid settings. The workflow sets whether the LAMMPS tests are required based on PyTorch availability.
Kokkos and MPI regression coverage
source/lmp/tests/run_mpi_dpa4spin_conventions.py, source/lmp/tests/test_dpa4spin_kokkos_magnetic_force.py, source/tests/infer/gen_dpa4c_spin_lmp_kokkos.py
The MPI runner and tests compare host and Kokkos results across single- and multi-rank runs, convention selections, repeated computations, scaling, and hybrid overlays. A generator creates and checks the compressed Kokkos model fixture.

Priority: ➖ Normal

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

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant LAMMPS
  participant PairDPA4Spin
  participant Model
  participant AtomFM
  participant Consumer
  LAMMPS->>PairDPA4Spin: Set magnetic_force convention
  PairDPA4Spin->>Model: Evaluate energy and magnetic gradient
  Model-->>PairDPA4Spin: Return magnetic gradient
  PairDPA4Spin->>AtomFM: Accumulate convention-scaled magnetic force
  Consumer->>PairDPA4Spin: Extract fm_cartesian_force
  PairDPA4Spin-->>Consumer: Return convention flag
Loading
Merge Risk: ⚪ Minimal · up to 21053

No identified issue blocks merging; complete the planned CUDA and multi-rank validation.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 15.38% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 39 functions across 11 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Issue #6077 is open and directly linked. The PR adds explicit magnetic_force precession|cartesian selection with precession as the default. Cartesian mode applies energy-per-model-spin conversion wi…
Out of Scope Changes check Passed The changes remain within Issue #6077. Adapter code, Kokkos code, extraction, plugin registration, fixtures, documentation, regression tests, and CI support the requested force convention or validate …
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely identifies the main change: adding Cartesian native-spin magnetic-force support for LAMMPS.
Full details: Linked Issues check

Explanation

Issue #6077 is open and directly linked. The PR adds explicit magnetic_force precession|cartesian selection with precession as the default. Cartesian mode applies energy-per-model-spin conversion without moment or hbar scaling, including zero moments, and requires metal units. Pair::extract("fm_cartesian_force", dim) reports the selected mode. Host and Kokkos paths retain force accumulation, and the runtime plugin registers the host style. CPU tests cover finite differences, selection, extraction, scaling, repeatability, and invalid settings. The Kokkos test covers single-rank and two-rank paths when mandatory CI prerequisites are available. Pending GPU/MPI execution does not establish an unmet implementation requirement.

Full details: Out of Scope Changes check

Explanation

The changes remain within Issue #6077. Adapter code, Kokkos code, extraction, plugin registration, fixtures, documentation, regression tests, and CI support the requested force convention or validate its built-in and plugin behavior. The scoped fixture-export workaround and MPI setup address test execution. No unrelated product change is demonstrated.

Full details: Docstring Coverage

Explanation

Docstring coverage is 15.38% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 39 functions across 11 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • 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

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

@OutisLi OutisLi added the Test CUDA Trigger test CUDA workflow label Oct 17, 2026 — with ChatGPT Codex Connector
@github-actions github-actions Bot removed the Test CUDA Trigger test CUDA workflow label Oct 17, 2026
@OutisLi OutisLi added the Test CUDA Trigger test CUDA workflow label Oct 17, 2026 — with ChatGPT Codex Connector
@github-actions github-actions Bot removed the Test CUDA Trigger test CUDA workflow label Oct 17, 2026
@codecov

codecov Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 66.12903% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.83%. Comparing base (668b60c) to head (aa3bb29).

Files with missing lines Patch % Lines
source/lmp/pair_dpa4spin.cpp 60.37% 16 Missing and 5 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #6084      +/-   ##
==========================================
+ Coverage   77.79%   77.83%   +0.03%     
==========================================
  Files        1171     1171              
  Lines      141562   141607      +45     
  Branches     5066     5078      +12     
==========================================
+ Hits       110135   110214      +79     
+ Misses      29550    29455      -95     
- Partials     1877     1938      +61     

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

@OutisLi OutisLi added the Test CUDA Trigger test CUDA workflow label Oct 17, 2026 — with ChatGPT Codex Connector
@github-actions github-actions Bot removed the Test CUDA Trigger test CUDA workflow label Oct 17, 2026
@OutisLi OutisLi added the Test CUDA Trigger test CUDA workflow label Oct 17, 2026 — with ChatGPT Codex Connector
@github-actions github-actions Bot removed the Test CUDA Trigger test CUDA workflow label Oct 17, 2026

@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

Source review LGTM for exact head aa3bb2928546b0bdd09a8f78e89df4d21cbd9fb2.

I rechecked the host/Kokkos convention selection and accumulation, default-precession compatibility, Cartesian metal-unit restriction, scalar extraction, host plugin registration, and the regression/CI integration. I found no remaining actionable defect in this scope. The delta from 210536990c3df8444da4296908d20e9cdcbd4f32 adds only the 22-line model-independent plugin-registration test; production code and workflows are unchanged. Four exact-test control-flow checks with doubles cover automatic/explicit loading, missing-style failure, quoted paths and context cleanup.

Validation scope:

  • The actual CUDA run succeeded on 210536990c3df8444da4296908d20e9cdcbd4f32: all 6 dedicated Kokkos tests passed with 0 skips, including genuine two-rank MPI; ordinary LAMMPS 295 passed/24 skipped; i-PI 8 passed; CUDA Python 14,070 passed/8,709 skipped. These are CI executions, not local GPU runs by this review.
  • That evidence remains attributed to the earlier SHA. At this submission, current-head C++ and Python tests are still running; the current CUDA workflow's actual C++/Python jobs are skipped.
  • Local checks of the latest test used doubles, not a real LAMMPS runtime. No new GPU finite-difference, GPU mutation, CUDA-aware-MPI or large-system communication-stress validation is claimed.

This is source approval; the remaining current-head checks still need to complete.

@OutisLi
OutisLi added this pull request to the merge queue Oct 18, 2026

@iProzd iProzd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed the exact head and the LAMMPS stable communication contract. AtomVecSpin already reverse-communicates fm/fm_long for the host path; the pair-specific comm_reverse=6 is correctly confined to the Kokkos device path. Cartesian scaling, unit validation, extraction, host/plugin coverage, and one-/two-rank Kokkos tests are covered. All current checks are green; I found no blocking issue.

Merged via the queue into deepmodeling:master with commit 24e8132 Oct 18, 2026
58 checks passed
@OutisLi
OutisLi deleted the feat/lammps-cartesian-magnetic-force branch October 18, 2026 16:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

6 participants