Skip to content

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

Open
OutisLi wants to merge 6 commits into
deepmodeling:masterfrom
OutisLi:feat/lammps-cartesian-magnetic-force
Open

OutisLi wants to merge 6 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 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 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.
  • CI on c985896e successfully built the actual CUDA Kokkos LAMMPS/plugin and exported the canonical GPU fixture. The new integration runner then exposed a missing explicit run_style verlet/kk; the corrected runner also checks the active integrator and finalizes Kokkos on exceptions. A real Kokkos Serial execution reproduced the setup failure and verified the correction, repeated computes, and overlay accumulation. On 94596308, the real single-rank GPU convention comparisons and three overlay cases ran successfully; the requested two-rank runs instead reported singleton worlds and correctly failed the rank-count assertion. The unified-MPI revision is awaiting full GPU/MPI CI.
  • 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.
  • Repository-wide Ruff check/format, focused isort/clang-format, shell syntax, workflow YAML parsing, and git diff --check passed.

Coverage limits

This development environment has no GPU and cannot run two-rank communication. GitHub CI has now exercised real single-rank CUDA Kokkos numerics, but genuine two-rank GPU/MPI validation is still pending after correcting the MPI installation. The dedicated CUDA job is triggered for the latest commit using the repository's one-shot Test CUDA label; its result is pending. Kokkos Serial compilation is not GPU runtime validation. GPU energy finite differences are not claimed by the new adapter-equivalence tests. The six-atom MPI regression is not a large-system communication-buffer stress test. The full multi-backend CI matrix remains for GitHub CI.

Fixes #6077

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 describes 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 (9459630).

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     5072       +6     
==========================================
+ Hits       110135   110216      +81     
+ Misses      29550    29454      -96     
- Partials     1877     1937      +60     

☔ 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

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.

[Feature Request] Native Cartesian magnetic-force mode for Newtonian spin dynamics in LAMMPS

3 participants