Repository navigation
perf(pt): add opt-in SO2 edge-cohort inference backward 【hnu】 - #2
Draft
macqueen09 wants to merge 40 commits into
Draft
macqueen09 wants to merge 40 commits into
macqueen09 wants to merge 40 commits into
Conversation
…ling#6084) ## Summary Implements deepmodeling#6077, fixes deepmodeling#6075, and supersedes deepmodeling#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 deepmodeling#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](mpi4py/mpi4py#547)); 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](https://github.com/deepmodeling/deepmd-kit/actions/runs/39067298863/job/117497541231) 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](https://github.com/deepmodeling/deepmd-kit/actions/runs/39067298863/job/117497541440) 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 deepmodeling#6077 Fixes deepmodeling#6075 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## 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. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: OutisLi-Bot <44916828+OutisLi-Bot@users.noreply.github.com>
…els (deepmodeling#6080) ## Summary Fixes deepmodeling#6076 and supersedes deepmodeling#6079, retaining its module-local NumPy buffer-device fix and CPU-before-fold export ordering. This addresses both excessive vacuum-reference allocation and a CUDA-target DPA4 export regression introduced by moving the eager fold to CPU. ## Changes - Evaluate DPA4/DPA4C isolated references using one node per type and two masked guard edges, instead of sizing a dense neighbor list from `get_nnei()`. DPA4C's `[999999]` graph sentinel must not become almost one million padded neighbors per type. - Introduce an explicit `supports_graph_vacuum()` capability. DPA4/DPA4C opt in; legacy DPA1/DPA2 reference semantics and explicit graph-disable routing remain unchanged. Preserve type, charge and native-spin conditioning. - During export, temporarily reconstruct only descriptors requiring references on the CPU with reference kernels. Fold under `torch.no_grad()`, retaining bias/reference tables on the original fittings, then restore deployment descriptors and their optimized bindings before fake tracing. Runtime graph-disable state and environment settings are restored, including failure paths. - Retain deepmodeling#6079's device-selection fix for NumPy buffer assignments, including newly materialized nonpersistent reference tables. Simply moving a CUDA-bound float32 DPA4 model to CPU does not unbind its CUDA-only operators. Conversely, disabling deployment kernels throughout tracing would silently lose acceleration. The scoped reference-descriptor context avoids both problems without reconstructing the whole folded model or losing `vacuum_table` through serialization. ## Regression coverage - Allocation guards prohibit querying dense capacity or calling the dense adapter for graph references, including sentinel values 999999 and 1999999. - Float32/float64 DPA4/DPA4C, charge/native-spin combinations, empty/masked edges, and nonzero learned conditioning. - Nonzero-mean DPA1 legacy reference energies and disabled graph lowering. - Export order, CUDA-only operator dispatch without a CPU implementation, preservation of the optimized operator in fake tracing, fparam/aparam reference tables, restoration after failures, and no-reference fast exit. ## Validation - **40 passed**: new graph-reference tests, new export-reference tests, and common wrapper tests, using current Python source and a freshly rebuilt CPU PyTorch extension (MPI disabled because this host lacks MPI headers; TensorFlow build disabled). - **44 passed**: graph-reference tests plus existing dpmodel vacuum and capability coverage. - **36 passed**: broader export/kernel-policy/vacuum suite, including actual CPU `.pt2`/`.pte` compilation, fparam `.pt2`, and archive reserialization/refreezing. This run used the existing installed CPU native library with current Python source. - Additional independent checks covered mixed DPA4+DPA4C linear and native-spin models, nonpersistent tables and restoration of original descriptor objects. - Repository-wide Ruff check/format and `git diff --check` passed. ### Memory sanity check An untrained default-size DPA4C descriptor with the bundled 89-element OMat24 type map, float64 and charge/native-spin conditioning, retained its actual `get_nnei() == 999999`. Vacuum evaluation produced finite `(89, 207)` output in approximately 0.01–0.03 s, with about 34 MiB incremental process peak RSS. This is a CPU sanity check, not a benchmark of the reporter's pretrained checkpoint or a directly comparable speedup claim. ### Not verified - Real CUDA kernel execution and CUDA-target AOT compilation on GPU hardware. - Full large pretrained-checkpoint GPU/host peak-memory benchmarking. The CPU dispatch regression uses an operator without a CPU implementation and checks fake-trace preservation; it is not presented as a GPU integration test. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Vacuum-reference evaluation now supports graph-based DPA4 and DPA4C models, including when dense neighbor capacity is unavailable. Descriptors without graph-based vacuum support continue to use dense evaluation. * **Bug Fixes** * Improved consistency of vacuum-reference folding during model export, including preserving model settings and keeping folding on the CPU. * Corrected buffer assignment so arrays follow the model’s device when possible, rather than always using the default device. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: OutisLi_Bot <198997215+OutisLi-Bot@users.noreply.github.com>
Use a compiled single-cohort branch for small edge sets and retain a streamed runtime path for larger frozen Neo input gradients. Keep native fallback and explicit stride defaults, add 60 CUDA checks and cold-first-peak evidence. The switch remains disabled by default; multi-model and AOT deployment are not validated. N64 cold allocated peak falls 3.62%; no speedup is claimed.
) ## Summary Replace deepmodeling#6068 with a deliberately smaller change based on current master (`4f78c2d0`). Current master already shares bounded, sel-independent graph trace inputs between compilation and export. The remaining gap is sample coverage: a seven-atom sample assigned types modulo the type-map length never exercises type 117 in a 118-type model, and random geometry does not guarantee an isolated owned center. - Keep the sample size and existing dynamic-axis strategy; place a connected three-atom cluster and an isolated owned center in the periodic sample. - Put the highest valid type index on a connected node, independent of type-map size. - Add real graph export regression coverage for changed frame/node/edge counts, including zero-edge runtime, with energy/force/virial eager parity. - Protect existing preparation and introspection semantics with strict-normalization, hybrid, DPA4/DPA4C dispatch, and both checkpoint-layout regressions. No extra neighbor-contract abstraction, hot-path dispatch, graph ABI, C++ source, or metadata schema changes are introduced. Legacy `sel`/`nnei` remain available to dense consumers and existing C++ readers. DPA1 auto-sel and normalization/statistics are deliberately unchanged; removing their semantic dependence on sel belongs to deepmodeling#5824. This PR does not claim to complete all of deepmodeling#5825. ## Validation CPU, using the installed native extension: - 17 new graph sample/export cases, including 118 types and dynamic N/E energy/force/virial parity. - 5 existing graph regressions: actual DPA2 Inductor compilation, DPA1 attention 0/2 traces, DPA4 trace, dynamic-aparam export. - 40 checkpoint/preparation tests plus 33 subtests. - Native-spin traced forward/magnetic-force double-backward regression (compile backend intentionally mocked by that existing test). - `ruff check .`, `ruff format .`, and `git diff --check`. GPU execution and a fresh C++ rebuild were not performed. Metadata compatibility is asserted, not presented as an executed C++ integration test. Refs deepmodeling#5825, deepmodeling#5824, deepmodeling#5755. Supersedes deepmodeling#6068. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Tests** - Added compatibility coverage for neighbor preparation, automatic and explicit selections, hybrid descriptors, and minimum-distance handling. - Added regression checks for descriptor and fitting outputs across standard and compiled checkpoints. - Expanded graph-tracing tests for deterministic sparse inputs, varied node/type counts, data types, canonicalization, and high-type models. - Added end-to-end validation confirming exported graphs preserve energy, force, and virial results across multiple inputs. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…#6058) ## Review follow-up: focused regression scope (2026-10-19) Addressing [OutisLi's requested changes](deepmodeling#6058 (review)). The production implementation is unchanged from `7cfd926b`; this follow-up changes **only the test file**. No new inference level, autotuning, performance study, production-size benchmark or full-model GPU test suite was added. | Coverage contract | Current cases | Mapping | |---|---:|---| | Numerical/reference, shapes, caller-input preservation | 7 | The suggested representative list retains all five shape profiles, both alpha modes, empty/partial edges, zero/one/multiple gated layers and narrow/BMM paths | | Workspace identity | 4 | Unchanged function: all with_weights/keep pairs; final out-of-place; gz/output always distinct | | Dtype/alpha versus separate buffers | 6 | Unchanged function and tolerances: FP32/FP16/BF16 × alpha on/off | | Actual autograd dispatch | 6 | Trainable/partially frozen/frozen weights × create_graph=False/True; mocked gradient operators test selection only | | Saved-output cotangent dispatch | 2 | Frozen inputs with a cotangent on z or the final activation must use the protected training path | | Unique frozen direct-stack derivative numerics | 1 | One small FP32 force-loss case checks output, first derivative and second-order objective gradients; no optimizer loop or width cross-product | | **Total** | **26** | 17 core + 8 dispatch guards + 1 numerical higher-order check | Existing `TestSeZMModelCompile.test_forward_backward_double_backward_matches_compile` covers ordinary model-level parameter gradients, force loss and short training; `TestSeZMTrainPathParity.test_training_step_matches_the_dense_path` covers descriptor/training binding parity. Those do not automatically establish the fully frozen **direct-stack** force-loss path, so one representative numerical check remains. The six new dispatch cases execute real `torch.autograd.grad(..., create_graph=...)`; their mocked gradient operators are not presented as numerical training-equivalence evidence. Fresh validation: **26 CUDA tests passed**; with no visible GPU **26 skipped**. The retained ownership guard still fails at its residual/output alias assertion when the exact baseline traversal is substituted in an isolated diagnostic process. Both retained guard/dtype functions are AST-identical to the previous head. Full-repository Ruff check/format and whitespace checks passed; production source is byte-for-byte unchanged. Local CUDA coverage executes the three new statements (lines 3199–3201 at this revision), including both outcomes of the line-3200 guard. This is **not** a claim that upstream Codecov/required checks are green. No CI configuration or coverage exclusions were changed. Please verify GPU execution and the uploaded coverage in the new upstream runs. The 106-case counts, full-model measurements and multi-step training evidence below are **historical pre-review results**, not newly rerun tests or performance claims for this follow-up. --- ## Summary Reuse the internally owned residual-gradient workspace in the SO2 mixing-stack backward traversal when neither weight gradients nor saved per-layer state are needed. This removes one edge-sized allocation without changing kernel arithmetic, model parameters, precision settings or public APIs. This is an isolated workspace change. It does not include compiler scheduling passes, the inference-compiler flag from deepmodeling#6056, additional fusion, checkpoint changes, or local benchmark infrastructure. ## Why the alias is safe The gated-layer backward GEMM computes `residual + gz @ W.T`. Its matrix input `gz` remains separate from the output. Each output tile reads only its matching residual elements before writing those same locations; distinct programs do not read one another's residual tiles. The final-layer GEMM remains out-of-place. Only buffers allocated inside this traversal are reused. Caller inputs and forward-saved tensors are not mutated, so the operator's `mutates_args=()` contract is unchanged. The weight-gradient and saved-state traversals keep their original allocation paths. The guard uses actual gradient/state requirements, not simply `model.eval()`, which matters for frozen-weight and force-loss cases. The generated full-model graph was checked as well: four gated GEMM calls alias residual/output, while both final-layer calls and every matrix-input/output pair remain separate. ## Scope - `deepmd/pt_expt/kernels/triton/sezm/so2_value_path.py`: local allocation change and the alias-safety explanation. - `source/tests/pt_expt/kernels/test_so2_workspace.py`: generated-input CUDA regressions, with no checkpoint or machine-specific dependencies. The current focused tests cover the contracts mapped in the review follow-up above. They retain the allocation-identity baseline-fails/candidate-passes assertion, unchanged dtype/alpha checks and tolerances, lightweight autograd-dispatch checks, and one numerical frozen-weight force-loss case rather than repeated updates. ## Full-model measurements Base: `dbca0b1cfabc9be166feffcbbc93e9c833603aca`. RTX 5090, driver 595.91.07; Python 3.11.12, PyTorch 2.11.0+cu128, Triton 3.6.0, Warp 1.16.0. Same DPA4-Neo checkpoint and normal ASE/DP energy/forces/virial/stress evaluation, including neighbor construction. `DP_COMPILE_INFER=1`, `DP_TRITON_INFER=2`, TF32/AMP off, one host thread, `PYTORCH_ALLOC_CONF=expandable_segments:True`. Diamond C, lattice 3.567 Angstrom, seed 0, position noise sigma 0.02 Angstrom. Each process: 8 warmup calls including the first, 30 synchronized wall-clock samples, and a separate 30-call memory replay. Three independent processes for 4096 atoms; two for 1000. Timing values below are medians of process quantiles; memory values are the maximum measured peaks. GB means 1e9 bytes. | Atoms | Metric | Base | Candidate | Change | |---:|---|---:|---:|---:| | 4096 | Steady P50, ms | 155.339543 | 155.281764 | −0.0372% | | 4096 | Steady P90, ms | 155.657487 | 155.602488 | approximately unchanged | | 4096 | Full measurement-window allocated peak, GB | 24.061593 | 22.404837 | −6.885% | | 4096 | Steady allocated peak, GB | 23.970400 | 22.313645 | −6.912% | | 4096 | Reserved peak, GB | 25.612517 | 23.955767 | −1.656755 GB | | 1000 | Steady P50, ms | 40.442513 | 40.511280 | +0.1700% | | 1000 | Full measurement-window allocated peak, GB | 5.968265 | 5.563780 | −6.777% | | 1000 | Steady allocated peak, GB | 5.869245 | 5.464760 | −6.892% | This is a memory optimization, not a claim of significant speedup. The small observed 1000-atom latency increase is disclosed rather than classified as a speed improvement. The 4096-atom allocation reduction is exactly 1,656,755,200 bytes, matching one `[2, 647170, 320]` FP32 workspace. First-call compilation is excluded from steady timing but included in the full memory window. GPU clocks were not locked, and these short research runs are not a long-duration performance acceptance test. ## Numerical validation and limitations Full-model comparison uses all energy, force, virial and stress elements with finite-value checks and `abs(actual-reference) <= 1e-5 + 1e-4*abs(reference)`. - 1000 atoms: candidate versus same-round compiled base passes in both independent processes; all 10 three-frame self-repeatability rounds pass. - 4096 atoms: all 3 candidate-versus-base comparisons pass, but strict self-repeatability is not universally satisfied: candidate 6/15 and base 9/15 rounds pass. The failed checks are the third frame's virial. Baseline cross-process comparisons also fail that component in both repeat runs. No tolerance was relaxed and no output was excluded. These observations do not establish either a fix or a regression in global numerical determinism. An additional independent dense eager GPU reference, with compilation and Triton/CUDA fast paths disabled, also passes for both 1000-atom candidate runs and both base runs at the same elementwise thresholds. This was one three-frame reference evaluation, not an exhaustive determinism test. ## Historical local test evidence (before the focused-test revision) - New workspace regressions: **106 passed** on CUDA. - Full-repository Ruff check and format check: passed. - Project-configured pre-commit hooks for both changed files: all applicable hooks passed. - Patch whitespace check and clean application to the base: passed. - Original model/descriptor/training-path regressions: **87 passed, 5 skipped, 127 subtests passed**. All nine `TestSeZMModelCompile` tests passed. The five skips require DPA4 native CUDA operators absent from the installed library. - Red/green: the unmodified base fails the allocation-identity assertion as expected; the candidate passes. - NVIDIA Compute Sanitizer memcheck: four alias/guard cases passed, **0 errors**. - CPU native tabulation forward/backward/second-order smoke: **6 passed**. - GPU native tabulation smoke: **2 failed on both base and candidate**, because the installed customized-op library was built without GPU support. This is an environment limitation, not a passing test or a newly introduced failure. - Without a visible GPU the new file collects normally and skips 106 tests. The local source-selection harness used the new Python checkout with existing native libraries from the measured environment. This does not claim a fresh C++/wheel build or TensorFlow/JAX/Paddle validation. Other GPU architectures and Torch 2.12/2.13 are not locally validated here. A CUDA-native rebuild is needed to cover the missing native paths; this PR does not claim that every local or required CI check is green. ## Historical additional cross-checkout training equivalence Separate BASE and candidate processes, identical generated inputs/initialization, TF32 disabled, same GPU/environment: | Path | Cases / updates per case | Compared | |---|---|---| | Direct mixing stack, widths 32 and 96, all / partially frozen / frozen weights | 6 cases, 5 AdamW steps each | output, force-loss second derivatives, gradients, updated parameters, step counters and moments | | Actual SeZM model, dense eager | 3 SGD + momentum steps | energy/force/virial loss, gradients, updated parameters and optimizer state | | Actual SeZM model, eager Triton training level 1 | 3 SGD + momentum steps | same | | Actual SeZM model, default dense compiled training | 3 SGD + momentum steps | same | **2516/2516 finite arrays pass** the same `atol=1e-5, rtol=1e-4` elementwise comparison. 1384 arrays are bitwise identical; global maximum absolute difference is **3.725290298461914e-9**; maximum error/tolerance ratio is **0.0003452008823**. This is bounded multi-step equivalence evidence, not a claim that arbitrary long training is bitwise identical. The normal `model.train()` route is excluded from this inference stack by the existing `not self.training` guard in `so2.py`. Direct-stack force-loss tests additionally cover trainable, partially frozen and frozen operands: observed backward calls requiring weight gradients retain separate workspace, and calls saving second-order state retain the saved-state path. No public training flags or APIs change. An additional tiny-model configuration combining Triton training with compilation triggered a Torch 2.11 Inductor `replace_by_example` pattern-matcher assertion on the **unmodified BASE**. The final comparison therefore explicitly separates eager Triton training from default compiled training, rather than claiming that combined configuration passed. Candidate equivalence for that failing BASE configuration is not established. The installed native library also lacks CUDA operators; local CUDA toolkit 13.2 does not match this Torch cu128 build, and a fresh matching-toolkit CUDA build remains for CI/a suitable environment. ## Reproduction / reviewer requests Run the new test file using the normal project installation. It generates all operands and does not download a model. Also run the original `TestSeZMModelCompile`, `TestSeZMTritonValuePath`, descriptor and training-path regressions. The commands and standalone scripts below provide reproduction without committing machine-specific benchmark infrastructure. The exact checkpoint is `DPA4-Neo-OMat24-v20260627.pt`, SHA256 `8d8b2b02b9575cb9e0af420cc1e8b1d9ffcbc04752c2203d29f48ccd0cd5f07d`; it is not bundled. Exact full-model numbers require an authorized copy. Please trigger the upstream CUDA workflow and verify that relevant compile tests actually run rather than skip under the workflow's Torch version. Local results do not replace required status checks, maintainer review, or the merge queue. ## Reproducible commands Install each revision following the project's CUDA/PyTorch build instructions in separate environments, then verify `deepmd.__file__` and `torch.__version__`. Do not accidentally import another editable checkout. Tests below need no checkpoint: ```bash CUDA_VISIBLE_DEVICES=0 OMP_NUM_THREADS=1 python -m pytest -q \ source/tests/pt_expt/kernels/test_so2_workspace.py CUDA_VISIBLE_DEVICES=0 OMP_NUM_THREADS=1 python -m pytest -q \ source/tests/pt/model/test_sezm_model.py::TestSeZMModelCompile \ source/tests/pt/model/test_descriptor_sezm_triton.py::TestSeZMTritonValuePath \ source/tests/pt/model/test_descriptor_sezm_train_paths.py \ source/tests/pt/model/test_descriptor_sezm.py ruff check . ruff format --check . prek run --files deepmd/pt_expt/kernels/triton/sezm/so2_value_path.py \ source/tests/pt_expt/kernels/test_so2_workspace.py CUDA_VISIBLE_DEVICES=0 compute-sanitizer --tool memcheck --error-exitcode 86 \ python -m pytest -q \ source/tests/pt_expt/kernels/test_so2_workspace.py::test_reuse_only_without_weights_or_saved_state ``` Memcheck does not prove absence of all global-memory races; see the tile-level read/write argument above. For full-model reproduction, save the following script outside the repository. Run serially on an otherwise idle GPU, with a fresh output directory and cache for every invocation. With BASE installed/imported first: ```bash CUDA_VISIBLE_DEVICES=0 MODEL=/path/to/authorized/model.pt OUTPUT=/scratch/base-r0 \ TORCHINDUCTOR_CACHE_DIR=/scratch/cache-base-r0 NREP=8 \ python /scratch/public_benchmark.py # Switch to the candidate environment/checkout: CUDA_VISIBLE_DEVICES=0 MODEL=/path/to/authorized/model.pt OUTPUT=/scratch/candidate-r0 \ TORCHINDUCTOR_CACHE_DIR=/scratch/cache-candidate-r0 NREP=8 \ REFERENCE=/scratch/base-r0/outputs.npz python /scratch/public_benchmark.py ``` Repeat 3 processes for `NREP=8` (4096 atoms), 2 for `NREP=5` (1000 atoms), using different paths; interleave/reverse order when repeating. Inspect every JSON comparison and finite check. This portable script reproduces normal API timing/memory and cross-revision checks; the reported main experiment additionally ran five three-frame self-repeatability rounds per process and audited generated wrappers. Those extra diagnostics are not implemented by this short script. Do not use `torch.inference_mode()`: conservative force evaluation needs differentiation. No private compiler hooks are needed for this change. <details> <summary>Standalone public_benchmark.py (normal DP / ASE APIs)</summary> ```python """Standalone normal-API reproduction; attach as text, not a production file. Use a fresh process with the chosen checkout installed. MODEL is supplied by the caller. No private compiler hooks or absolute machine paths are used. """ import hashlib import json import os from pathlib import Path import time os.environ.update( DP_COMPILE_INFER="1", DP_COMPILE="0", DP_TRITON_INFER="2", DP_TF32_INFER="0", DP_AMP_INFER="0", DP_INTRA_OP_PARALLELISM_THREADS="1", DP_INTER_OP_PARALLELISM_THREADS="1", OMP_NUM_THREADS="1", PYTORCH_ALLOC_CONF="expandable_segments:True", ) import numpy as np import torch import deepmd from ase.build import bulk from deepmd.calculator import DP torch.set_num_threads(1) torch.set_float32_matmul_precision("highest") torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False model = Path(os.environ["MODEL"]) out = Path(os.environ["OUTPUT"]) out.mkdir(parents=True, exist_ok=False) nrep = int(os.environ.get("NREP", "8")) warmup, samples = int(os.environ.get("WARMUP", "8")), int(os.environ.get("SAMPLES", "30")) assert warmup >= 1 and samples >= 1 base = bulk("C", "diamond", a=3.567, cubic=True).repeat((nrep,) * 3) rng = np.random.default_rng(0) frames = [base.positions + 0.02*rng.standard_normal(base.positions.shape) for _ in range(max(3, warmup + samples))] calc = DP(model=str(model)) def evaluate(pos): calc.reset() atoms = base.copy() atoms.positions = pos atoms.calc = calc force = atoms.get_forces().copy() return dict(energy=np.asarray(atoms.get_potential_energy()), forces=force, virial=np.asarray(calc.results["virial"]).copy(), stress=atoms.get_stress().copy()) torch.cuda.synchronize() start = time.perf_counter() evaluate(frames[0]) torch.cuda.synchronize() first_ms = 1000*(time.perf_counter()-start) for pos in frames[1:warmup]: evaluate(pos) times = [] for pos in frames[warmup:warmup+samples]: torch.cuda.synchronize() start = time.perf_counter() evaluate(pos) torch.cuda.synchronize() times.append(1000*(time.perf_counter()-start)) full_allocated, full_reserved = torch.cuda.max_memory_allocated(), torch.cuda.max_memory_reserved() torch.cuda.reset_peak_memory_stats() for pos in frames[warmup:warmup+samples]: evaluate(pos) torch.cuda.synchronize() steady_allocated, steady_reserved = torch.cuda.max_memory_allocated(), torch.cuda.max_memory_reserved() outputs = {f"{i}_{key}": value for i, pos in enumerate(frames[:3]) for key, value in evaluate(pos).items()} np.savez_compressed(out/"outputs.npz", **outputs) comparison = {} if "REFERENCE" in os.environ: with np.load(os.environ["REFERENCE"]) as expected: for key, actual in outputs.items(): ratio = np.abs(actual-expected[key])/(1e-5+1e-4*np.abs(expected[key])) comparison[key] = dict(passed=bool(np.isfinite(ratio).all() and (ratio <= 1).all()), max_ratio=float(ratio.max())) result = dict(source=deepmd.__file__, torch=torch.__version__, atoms=len(base), model_sha256=hashlib.sha256(model.read_bytes()).hexdigest(), first_ms=first_ms, samples_ms=times, p50_ms=float(np.median(times)), p90_ms=float(np.percentile(times,90)), full_allocated=full_allocated, full_reserved=full_reserved, steady_allocated=steady_allocated, steady_reserved=steady_reserved, comparison=comparison, finite=all(bool(np.isfinite(x).all()) for x in outputs.values())) (out/"result.json").write_text(json.dumps(result,indent=2,allow_nan=False)) print(json.dumps(result,indent=2,allow_nan=False)) ``` </details> <details> <summary>Supplementary multi-step training comparison (outside the production branch)</summary> Save this as `training_equivalence.py` outside the repository. Run once from each installed checkout's root in a fresh process/cache: `CUDA_VISIBLE_DEVICES=0 PYTHONPATH="$PWD" TRAIN_OUTPUT=/scratch/train-base TORCHINDUCTOR_CACHE_DIR=/scratch/train-cache-base python /scratch/training_equivalence.py`. Use distinct candidate output/cache paths. The code below only makes GPU selection configurable relative to the measured local script; computations are the same. It uses existing repository test helpers and generated data; no pretrained model is required. ```python """Save actual optimizer trajectories for cross-checkout comparison; local only.""" import os from pathlib import Path import json for key in list(os.environ): if key.startswith('DP_'): del os.environ[key] os.environ.update(CUDA_VISIBLE_DEVICES=os.environ.get('CUDA_VISIBLE_DEVICES', '0'), OMP_NUM_THREADS='1', DP_INTRA_OP_PARALLELISM_THREADS='1', DP_INTER_OP_PARALLELISM_THREADS='1', DP_TRITON_TRAIN='1', DP_TRITON_INFER='2', DP_TF32_INFER='0',DP_AMP_INFER='0') import numpy as np import torch import deepmd from deepmd.pt_expt.kernels.triton.sezm import so2_value_path as vp from source.tests.pt.model.test_sezm_model import TestSeZMModelCompile, get_sezm_model # The repository test package deliberately installs an invalid default device; # restore normal application semantics for Adam's CPU scalar step counters. torch.set_default_device(None) torch.set_num_threads(1) torch.set_float32_matmul_precision('highest') torch.backends.cuda.matmul.allow_tf32=False torch.backends.cudnn.allow_tf32=False out=Path(os.environ['TRAIN_OUTPUT']) out.mkdir(parents=True,exist_ok=False) arrays={} counts={} originals={} for name in ('_stack_backward_traversal','_stack_train_traversal'): original=getattr(vp,name) originals[name]=original def observed(*args,_name=name,_fn=original,**kwargs): key=f'{_name}:weights={kwargs.get("with_weights")}:keep={kwargs.get("keep")}' counts[key]=counts.get(key,0)+1 return _fn(*args,**kwargs) setattr(vp,name,observed) def save(key,value): arrays[key]=value.detach().cpu().numpy().copy() assert np.isfinite(arrays[key]).all(),key def state(prefix,optimizer,leaves): for i,p in enumerate(leaves): save(f'{prefix}/param/{i}',p) for name,value in optimizer.state[p].items(): if isinstance(value,torch.Tensor): save(f'{prefix}/optimizer/{i}/{name}',value) # Direct stack coverage includes narrow fused training and wide replay paths. for lmax,width in ((2,32),(6,96)): for mode,requires in (('all',(True,True,True)),('partial',(True,False,False)),('frozen',(False,False,False))): torch.manual_seed(19) edges,focus,gates=7,2,2 row,m0,m1=(3*lmax+1)*width,(lmax+1)*width,2*lmax*width operands=[torch.randn(focus,edges,row,device='cuda')*.1, torch.rand(edges,focus,device='cuda')+.2, torch.randn(gates+1,focus,m0,m0,device='cuda')*.02, torch.randn(gates+1,focus,m1,m1,device='cuda')*.02, torch.randn(gates,focus,width,lmax*width,device='cuda')*.02] for value,enabled in zip(operands,(True,True,*requires),strict=True): value.requires_grad_(enabled) leaves=[p for p in operands if p.requires_grad] optimizer=torch.optim.AdamW(leaves,lr=1e-4,weight_decay=.01) prefix=f'stack/{lmax}_{width}/{mode}' for step in range(5): optimizer.zero_grad(set_to_none=True) output=vp._mixing_stack_op(*operands,lmax,width,True)[0] energy=output.square().sum()/edges force=torch.autograd.grad(energy,operands[0],create_graph=True)[0] loss=energy+force.square().sum() save(f'{prefix}/{step}/output',output) save(f'{prefix}/{step}/force',force) save(f'{prefix}/{step}/loss',loss) loss.backward() for i,p in enumerate(leaves): assert p.grad is not None save(f'{prefix}/{step}/gradient/{i}',p.grad) optimizer.step() state(f'{prefix}/{step}',optimizer,leaves) print('STACK DONE',prefix,flush=True) # Real SeZM energy/force/virial losses, not merely an isolated stack. for name,original in originals.items(): setattr(vp,name,original) # Match the repository's model-test context. Keep the default compiled route # separate from eager Triton training; neither is an inference benchmark. torch.set_default_device('cuda:9999999') helper=TestSeZMModelCompile() helper.setUp() coord,atype,box,energy_target,force_target,virial_target=helper._make_tiny_frame() for mode,compiled,triton_level in (('dense_eager',False,0),('triton_eager',False,1),('dense_compiled',True,0)): os.environ['DP_TRITON_TRAIN']=str(triton_level) os.environ['DP_TRITON_INFER']='0' params=helper._build_model_params(use_compile=compiled) params['descriptor']['l_schedule']=[1,1] params['descriptor']['so3_readout']='mlp' if triton_level: params['descriptor'].update(channels=32,n_focus=2,l_schedule=[2,2],so2_layers=3, n_radial=8,ffn_neurons=64) model=get_sezm_model(params) helper._randomize_params(model) model.train() optimizer=torch.optim.SGD(model.parameters(),lr=1e-7,momentum=.9) leaves=list(model.parameters()) prefix=f'model/{mode}' for step in range(3): optimizer.zero_grad(set_to_none=True) outputs=model(coord,atype,box=box) loss=0 for key,target in (('energy',energy_target),('force',force_target),('virial',virial_target)): save(f'{prefix}/{step}/{key}',outputs[key]) loss=loss+(outputs[key]-target.to(outputs[key].dtype)).square().mean() save(f'{prefix}/{step}/loss',loss) loss.backward() for i,p in enumerate(leaves): if p.grad is not None: save(f'{prefix}/{step}/gradient/{i}',p.grad) torch.nn.utils.clip_grad_norm_(leaves,1.) optimizer.step() state(f'{prefix}/{step}',optimizer,leaves) print('MODEL DONE',prefix,flush=True) np.savez_compressed(out/'trajectory.npz',**arrays) (out/'manifest.json').write_text(json.dumps(dict(source=deepmd.__file__,torch=torch.__version__, arrays=len(arrays),traversals=counts,finite=True),indent=2)) print('SAVED',len(arrays),counts,flush=True) ``` Compare the two generated archives with shape/key/dtype and finite checks: ```python import numpy as np with np.load("/scratch/train-base/trajectory.npz") as base, \ np.load("/scratch/train-candidate/trajectory.npz") as candidate: assert set(base.files) == set(candidate.files) for name in base.files: a, b = base[name], candidate[name] assert a.shape == b.shape and a.dtype == b.dtype, name assert np.isfinite(a).all() and np.isfinite(b).all(), name assert (np.abs(b-a) <= 1e-5 + 1e-4*np.abs(a)).all(), name ``` </details> ## Contribution / merge checklist - [x] Small source change with generated-data regression tests; no checkpoints, benchmark caches, raw customer data, or machine-specific files committed. - [x] Conventional commit / PR title; Ruff and applicable project hooks pass. - [x] Numerical, memory, latency, training results and limitations disclosed. - [ ] Upstream required status checks and actual CUDA job coverage. - [ ] Maintainer approval and resolution of review threads. - [ ] Maintainer-managed merge queue after approval/checks. Prepared against the [contributing guide](https://github.com/deepmodeling/deepmd-kit/blob/dbca0b1cfabc9be166feffcbbc93e9c833603aca/CONTRIBUTING.md) and linked [coding conventions](https://docs.deepmodeling.com/projects/deepmd/en/stable/development/coding-conventions.html) and [CI documentation](https://docs.deepmodeling.com/projects/deepmd/en/stable/development/cicd.html). Current default-branch rules require seven check contexts (C++ tests, C++ build, C-library build, Python tests, wheel builds, CUDA aggregate, pre-commit.ci), at least one approval, resolved threads, and the squash merge queue. The CUDA workflow needs maintainer activation (e.g. the `Test CUDA` label); a passing aggregate with skipped GPU jobs is not CUDA validation. Please also check Torch-version gates on compile tests. No claim is made that local tests replace these server-side requirements. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Performance** * Reduced temporary memory allocation during SO(2) backward computations when weight gradients and saved per-layer state are not needed. Computations that require weight gradients or retained state continue to use separate workspace as needed. * **Tests** * Added coverage for numerical correctness, input preservation, and consistency across workspace strategies and supported configurations, including autograd behavior for trainable and frozen weights and force-loss derivatives. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: OutisLi <137472077+OutisLi@users.noreply.github.com>
…eepmodeling#6074) Models trained with `preset_out_bias` reapply checkpoint presets and skip residual fitting when `dp change-bias` computes statistics on downstream data. This can overwrite an adjusted stored bias and prevent adaptation to the target dataset. Scope this fix to standalone PyTorch, Paddle, and pt_expt change-bias. Add an optional preset override through the existing model and statistics APIs: omitted overrides preserve the original model-configured preset behavior; an explicit empty mapping disables checkpoint presets for this operation. CLI statistics updates pass that empty mapping, while `--bias-value` continues to override bias directly. Fine-tuning, training initialization, and post-training bias updates retain their original call sites and default behavior. No JAX trainer or training-workflow changes remain. The checkpoint preset metadata is preserved. Validation: - Changed-file Ruff checks, full-repository formatting, and diff checks pass. - Full-repository Ruff still reports two pre-existing unrelated RUF100 errors. - Preserve the original atomic-model preset tests and extend them to check the standalone override and subsequent unchanged default behavior. Add a PyTorch CLI regression test for a checkpoint containing preset metadata. Extend pt_expt checkpoint and frozen-model (.pte/.pt2) tests with a preset-configured model carrying adjusted stored biases [7, 8], check results against the no-preset statistics path, and verify preset metadata is preserved. Check that the default pt_expt helper still applies configured presets. - Isolated execution of the actual dpmodel, PyTorch, and Paddle bias-change methods with the real preset helper and stub statistics provider passed default-preset and explicit-override scenarios in both statistic modes. - Runtime pytest remains blocked at collection by the missing local `deepmd.lib` extension; backend integration tests were not completed. - Isolated pt_expt helper validation confirms default, empty, and explicit preset forwarding; the shared checkpoint/frozen CLI statistics branch supplies an empty override. The pt_expt runtime test was also blocked by missing `deepmd.lib` at collection. Spin wrappers normalize non-empty downstream presets on their public real-type map and extend them with unassigned virtual-type entries before forwarding. Regression tests cover dpmodel SpinModel, PyTorch SpinModel, and SeZMSpinModel sequence overrides. Add Paddle CLI checkpoint-preset regression coverage that checks fitted bias and metadata preservation. Isolated spin-wrapper validation passed default, empty, sequence, and element-map presets. Runtime spin tests remain blocked by missing `deepmd.lib`; Paddle runtime tests are additionally blocked by missing `paddle`. Review audit: - Three initial non-finite-preset findings: the broad default behavior change was removed; original training/fine-tuning preset fallback and its existing regression test are preserved. Those threads are resolved. - CUDA NumPy conversion finding: the affected inference block was removed when restoring default tests; the unsafe conversion is no longer present. The thread is resolved. - Adjusted-bias coverage suggestion in the review body: dpmodel, PyTorch, and Paddle tests now seed a finite non-preset bias and assert the prediction baseline before fitting, not only the final bias (0be5abf). - pt_expt omission: optional override forwarding and standalone checkpoint/frozen CLI coverage were added. The human reviewer reported 34 tests passed and 2 skipped on the preceding head and approved the PR. - Three spin sequence-preset findings: public real-type presets are normalized and extended for virtual types; regression tests were added. Those threads are resolved. - Paddle CLI coverage: the checkpoint-preset regression is present and checks fitted bias plus preserved metadata. This is the only inline thread still marked unresolved; local execution remains blocked by missing Paddle/native dependencies. The preceding head (4f5af64) has successful CI testing summary checks. The new adjusted-baseline tests pass changed-file Ruff and diff checks, but local pytest collection remains blocked by missing `deepmd.lib`; their CI results are pending. Latest review follow-up (e0edaa4): - Fix the still-applicable standalone override recovery regression: before residual prediction, replace only non-finite stored cells covered by finite checkpoint presets. Preserve finite adjusted baselines, recover preset-covered absent types, and keep outputs eligible for residual fitting. Omitted-override training/fine-tuning behavior remains unchanged. - Add shared scalar/tensor component recovery tests and a PyTorch non-finite serialized-model regression that exercises an explicit empty override, checks the prediction baseline, and verifies residual fitting against target labels. - Document the override in all six forwarding wrappers, including real-to-virtual spin type mapping. Update train-energy documentation to describe standalone statistics behavior and explicit --bias-value replacement. - Isolated recovery unit tests and actual-source dpmodel/PyTorch/Paddle method validation passed for NaN/positive infinity/negative infinity, absent covered types, finite adjusted cells, and unchanged defaults. Changed-file Ruff, full formatting, and diff checks passed. Local native pytest collection is still blocked by missing deepmd.lib; full Ruff reports the two previously documented unrelated RUF100 errors. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…ing#6089) ## Summary Fixes deepmodeling#5816. Supersedes deepmodeling#6061 with a fresh implementation on current master. - Run an all-rank non-finite-gradient preflight before any checkpoint state changes or serialization. Agree on the accumulated flag before gradient diagnostics as well, since sharded diagnostics can themselves be collective. - Full validation proposes a top-K candidate without changing state, checks only when a checkpoint will actually be saved, then records the selected state before serialization. Restart metadata therefore includes the checkpoint being written. - Share the PT regular/final/zero-step publication path and check once for each live-plus-EMA save. PT-expt includes every rank in checkpoint preflight, including ordinary DDP and the post-bias final save. The optimizer-step path and gradient-clipping algorithm are unchanged. Existing serialization/reconciliation I/O-error behavior is retained; this fix does not introduce a general checkpoint rollback or file-recovery protocol. ## Validation - Focused guard, checkpoint, validator, and real PT training-loop regressions: **63 passed, 15 subtests passed**. - Additional existing PT/PT-expt full-validation, EMA, zero-step, retention, and restart training regressions: **24 passed, 2 subtests passed**. These overlap some focused coverage. - Repository-wide Ruff check/format, changed-file isort, and `git diff --check`: passed. - Added a bounded two-process CPU Gloo regression with real DDP and ZeRO-1 checkpoint collection, covering both backends and regular/live-best/EMA-best boundaries. It injects a failure only on rank 1 and includes finite-save controls. **Not locally validated:** this environment blocks Gloo sockets, and elevated execution failed before Python started. The test remains enabled on Gloo-capable CI; it was deselected for the passing local runs above. - **Hosted CI on `04f93d9`: all 12 Test Python shards passed.** [Shard 6](https://github.com/deepmodeling/deepmd-kit/actions/runs/39280333675/job/118154760334) ran all 23 cases in `test_checkpoint_guard.py` successfully, including the two-process Gloo/DDP/ZeRO-1 regression; none of those 23 cases were skipped. CodeQL, pre-commit, and documentation checks also passed. - Local testing did not include GPUs or the full suite. CUDA test jobs were skipped, so no GPU validation is claimed. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Checkpoint saves now check for non-finite gradients consistently across distributed training ranks, including during periodic, validation, and final saves. * If any rank has detected a non-finite gradient, training raises an error before saving a checkpoint or updating best-checkpoint records. * Finite-gradient saves continue to work for both sharded and unsharded training, including zero-step and post-bias-adjustment saves. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
## Summary - Allow a model's element map to be a subset of an LMDB's declared element table when the unsupported entries are unused. - Derive batch layout from a selected frame and inspect only the box for PBC discovery, so an unselected unsupported frame cannot reject a valid selection. - Share lookup construction between `LmdbDataReader` and `LmdbTestData`, and validate the actual nonnegative atom-type indices in the common frame decoder. - Reject genuinely unsupported elements before writing remapped types, with the dataset, original frame index, and element names in the error. Preserve negative virtual-atom sentinels and positive-index bounds checking. ## Motivation and behavior An LMDB element table defines the source index namespace; it does not imply that every listed element occurs in the frames being read. Both readers currently reject a declared element missing from the model before examining the data. For example, source metadata `[O, He, H]`, actual atom types `[0, -1, 2]`, and model types `[H, O]` should produce `[1, -1, 0]`. The unused `He` entry must not reject these frames. A later frame that actually uses source type `1` still fails rather than turning that real atom into a virtual sentinel. Validation occurs when frames are decoded, including spawned decoder workers. This requires no additional dataset-wide scan and preserves selected-frame testing. The LMDB format and stored data do not change; missing source metadata and omitted test-model type maps retain their existing index interpretation. ## Validation - The three new focused regression cases fail against the base because construction rejects the declared element table before decoding. - 165 related CPU tests and 21 subtests passed, covering the common LMDB reader/decoder, PT consistency and loading, and PT-expt data-system paths. - Reverse-order regressions fail before the follow-up fix and pass afterward, including real parallel batch decoding and box/zero-box/missing-box PBC probes. - Coverage includes reordered subsets, virtual atoms, unsupported elements in a later frame, selected-frame limits, malformed positive indices, and real spawned-worker success/failure. - Ruff, read-only formatting/import-order checks, and non-formatting commit hooks including Pylint passed. Independent pre-push review completed. No GPU testing, full-dataset model inference, or performance claims. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * LMDB datasets can now be read with a model that supports only a subset of the source type map when unsupported types are absent from the frames being read. * If a decoded frame contains an unsupported atom type, reading reports an error identifying the frame and incompatible types. * Virtual atoms retain their sentinel type during decoding. * Selecting frames or checking periodic boundary conditions no longer requires validating an unselected first frame. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
…deling#6103) Add bundled `openmd` and `domain_cluster` atomic reference tables through the same loading and serialization path as `omat24`. Select either with `"preset_out_bias": {"energy": "openmd"}` or `"preset_out_bias": {"energy": "domain_cluster"}`. The table preserves all 83 H–Bi values from the supplied `ABACUS_PBE_PW_atom_E0.json` without rounding. Update the input-option help and energy-training documentation with the ABACUS PBE PW calculation conditions and the accepted unconverged La final-step value. Add regression coverage for table loading, type-map reordering, missing elements, and self-contained configuration resolution. The `domain_cluster` table preserves the supplied nine reference biases for Al, Si, Ni, Cu, Ru, Pd, Ag, Pt, and Au. Document the supported elements and add loading, type-map ordering, missing-element, and configuration-resolution coverage. Validation: - `pytest source/tests/common/test_preset_out_bias.py -q`: 21 passed. - Compared all 83 bundled values against the original JSON; verified type-map ordering and JSON configuration round-trip. - Backend-disabled editable package build, `dp --version`, and `dp -h` passed. - Ruff checks on changed Python files, repository-wide formatting, and `git diff --check` passed. - Repository-wide `ruff check .` reports two existing unused `PYI034` suppressions in `deepmd/pt_expt/utils/network.py` and `source/tests/pt/test_sampler.py`. No backend operator code is changed; TensorFlow/PyTorch runtime and backend-specific C++ tests were not run. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Added the `openmd` isolated-atom energy reference table, covering 83 elements from hydrogen to bismuth. * Added the `domain_cluster` reference table for nine elements: Al, Si, Ni, Cu, Ru, Pd, Ag, Pt, and Au. Other elements are unassigned in this table. * **Documentation** * Expanded guidance on available reference tables, their coverage, and how to select `domain_cluster`. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
deepmodeling#6096) ## Summary - Accept multiple LMDB paths and recursively expand every `systems` entry through shared, format-aware dataset discovery. Existing NPY and HDF5 inputs use the same discovery entry point; nested HDF5 groups are included correctly. - Accept `training_data` as either its existing dictionary or a list of independently configured groups. Each group can specify `prob`, its probability of supplying a whole training batch, alongside its own batch size and internal sampling options. - Keep native readers and compose their batch streams. Shared configuration, source planning, and probability calculation cover all training backends, while LMDB reading remains supported by PyTorch and PyTorch Exportable. ```json { "training_data": [ {"systems": "data/collection_a", "batch_size": "auto:32", "prob": 0.6}, {"systems": ["data/collection_b", "data/extra"], "batch_size": "auto:64", "prob": 0.4} ] } ``` Each probability applies to the complete group after recursive discovery, not separately to every discovered dataset. Unspecified groups share the remaining probability in proportion to their batch counts. Sampling is with replacement, as for existing NPY system selection; a nominal epoch does not guarantee exactly one visit to every frame. ## Compatibility and integration Existing dictionary configurations, NPY/HDF5 `sys_probs`, and single-LMDB internal block rules remain supported. A group containing multiple sources including LMDB accepts `auto_prob: prob_sys_size` (implicit or explicit) or `prob_uniform`, but no `sys_probs`; separate groups provide source weights and per-LMDB block rules without introducing cross-LMDB system indices. `prob_uniform` gives every retained NPY/HDF5 system and every eligible internal LMDB system the same long-run share of sampled frames, not the same file or batch probability. LMDB without system identifiers counts as one system. Internal LMDB frame counts are balanced before native packing, and source probabilities correct for differing batch frame counts; `mix:N` continues to mix systems. This intentionally changes older NPY/HDF5 uniform behavior when batch sizes differ. Explicit `sys_probs` and outer group `prob` retain their batch-probability semantics. A uniform LMDB pass draws `ceil(N / M)` frames from each of its `M` nonempty systems, where `N` is the retained frame count. Its pre-DDP-padding size is therefore less than `N + M`, rather than `M * max(system_nframes)`. Large systems are sampled without replacement across homogeneous groups; small systems retain and repeat frames. A pass need not visit every large-system frame. Native batch counts still determine `numb_epoch` and implicit outer-group probabilities, while explicit outer `prob` is unchanged. Custom block targets and their expansion algorithm remain unchanged. Both PyTorch backends use the established PT default for omitted/empty `model_prob`: NPY/HDF5 system counts and retained LMDB frame counts, summed across groups without weighting by group probabilities. For example, 100/900 retained LMDB frames gives default task weights 0.1/0.9. Explicit `model_prob` and `num_epoch_dict` are unchanged; nominal-epoch-based default task weighting is not included. Group composition preserves statistics collection, source-specific frame filtering, full validation, and native resource ownership. Size-based group probabilities use global source sizes; uniform composition accounts for rank-averaged batch frame counts. Actual local workloads determine distributed epoch lengths. NPY uniform streams retain their reader cursors across loader passes, and cached sets apply `numb_copy` only once. Unseeded distributed PT-expt groups use deterministic source selection. `dp test --train-data` accepts grouped input, honors each group's discovery patterns and input-file-relative paths, and visits all discovered data independently of training probabilities or atom-count filters. `validation_data` remains a dictionary and also accepts recursive/multiple-LMDB inputs. ## Validation - Current follow-up validation: 245 targeted CPU tests and 13 subtests passed, covering shared LMDB sampling, native PT/PT-expt loading, uniform composition, filtering, worker IPC, and training logs. - The skewed count-only regression requests 101,000 indices for `[100000] + [1] * 999`, not 100,000,000; small native sampler tests verify exact system quotas, epoch replay, frame coverage, and zero-quota group reachability. No large expanded pass was allocated. - Forty-eight bounded exact-source custom-block comparisons reproduce the prior head's full batch sequences across batching layouts, shuffling, seeds, and label-availability partitions. The logger fixture retains its task-probability and checkpoint-ownership checks. - Earlier feature validation: 348 targeted CPU tests and 13 subtests passed. Coverage includes native LMDB readers/composition, fixed/atom-budget/mixed batches, label availability, filtered-out systems, NPY/HDF5 short sets and copy weights, persistent-worker cleanup, CLI grouped input, all nine EMA tests, spin CLI subprocesses, schemas, and sampling. - Six additional one-step CPU trainer checks passed during the earlier feature validation across PT/PT-expt, covering flat/grouped NPY inputs with unequal batch sizes and retained-LMDB-frame defaults under filtering/internal resampling. - Distributed sampler/source-selection metadata was checked with independent simulated ranks on CPU, including queued-versus-prefetched pass accounting and omitted seeds. This is not a real multi-process collective validation. - Paddle is not installed locally. Its native interfaces were checked against official source, and its framework-independent buffer cancellation and trainer-exit logic passed exact-source checks; full Paddle execution remains unverified. - Previously reported feature validation covered TensorFlow/TF2 grouped training, validation, checkpoint output, and TensorFlow grouped checkpoint bias adjustment. The previously reported JAX/Orbax checkpoint stall was reproduced with legacy dictionary input as well; end-to-end JAX checkpoint validation remains incomplete. - Ruff and read-only Python-format, import-order, and Markdown-format checks passed. Non-formatting commit hooks, including Pylint, passed. Independent pre-push review completed. The earlier CI spin subprocess failure could not be reproduced locally. Both focused cases pass, and a failing subprocess now exposes its captured output; this does not establish the original CI failure's cause. No GPU testing or performance claims, and no CI monitoring or reruns. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit - **New Features** - Added grouped training-data configuration with per-group probabilities and batch-size controls. - Added recursive discovery and combined loading of DeePMD and LMDB datasets, including mixed-source training and validation. - Added uniform sampling that accounts for retained frames and batch sizes, plus support for multiple LMDB validation sources. - **Improvements** - Improved distributed epoch sizing, statistics collection, and pair-filter control across data sources. - Improved data-loader cleanup when training ends or encounters an error. - Updated default multi-task sampling weights to reflect native data sizes. - Improved recursive path matching and handling of relative data paths. - **Documentation** - Documented grouped data configuration, dataset discovery, LMDB usage, sampling behavior, and probability constraints. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
…ng#6093) ## Summary Supersedes deepmodeling#6069. Reimplements the checkpointable data-source protocol proposed by @OutisLi-Bot there, on current master (`d07c097b`), while retaining the small reader-owned `state_dict` / `load_state_dict` interface. - Persist each rank's per-task logical data cursor and selection RNG in optimizer checkpoints. Gather compact rank states only at checkpoint boundaries, not per batch: minimum-distance filtering can consume different numbers of batches on different ranks. - Reconstruct directory/HDF5 order from canonical source data and the pre-shuffle RNG state. Never serialize frame permutations or decoded data. - Track the LMDB cursor consumed by training, independently of prefetched work. Restore lazily after requirements/layout setup, validate sampling identity, and retain reusable sampler and worker-pool caches during diagnostic peeks. - Keep statistics, compilation warmup, chief-only display, and full validation from advancing training cursors or selection RNG. Best-validation saves precollect rank states before entering their chief-only callback. - Preserve legacy restart behavior when progress is absent. Initialization, finetuning, and EMA-only deployment snapshots do not restore training progress. ## Compatibility and scope Continuation requires the same immutable dataset at the same locations, batching settings, and world size. It guarantees continuation of the data stream, not bitwise reproducibility of every stochastic model or data transform. For intentional data relocation or changed data settings, `training.reset_data_progress: true` explicitly retains newly initialized data cursors and task/system selection RNG for all tasks while preserving model/optimizer/LR/step and EMA restart. It warns that batches may repeat and exact data-order continuation is unavailable. The default remains strict; path and metadata checks are not weakened into basename-only identity. Malformed progress envelopes still fail. The flag has no effect on fresh training, initialization, finetuning, frozen models, or legacy checkpoints without data progress. Changing the world size remains supported for model/optimizer/step restart. In that case, a warning explains that data cursors and selection RNG stay newly initialized, so batches may repeat and exact data-order continuation is unavailable. Malformed progress envelopes remain errors. Directory/HDF5 passes now index an unshuffled canonical set. This intentionally changes later single-set pass order relative to older releases that repeatedly shuffled the existing cache, and prevents `numb_copy` multiplicities from compounding. Cold LMDB restoration reconstructs the saved sampler pass on first use and skips batch indices, not decoded frames or earlier epochs. Same-pass diagnostic rewinds retain that sampling plan; index-prefix traversal and distributed partition-list allocation remain possible optimization work. ## Validation Built and used the native PyTorch CPU extension with Python 3.12, PyTorch 2.11.0+cpu and NumPy 2.3.5: - 292 common/data tests, including directory/HDF5, repeated shuffles, `numb_copy`, compact/lazy restore, real LMDB process prefetch, mixed pass lengths, and rank-local cursors. - 90 native trainer tests, including 20-step uninterrupted versus checkpoint-at-10 restart for directory, LMDB and ragged LMDB; next optimizer inputs and final weights agree. Also covers real best-validation save/restart, legacy/init/finetune/EMA, diagnostic isolation, filtered-rank restoration, and checkpoint/validation collective orchestration. - 1 additional distributed sampler partition test and 2 actual CPU compiled-restart tests. - Total: **385 tests and 30 subtests passed**. `ruff check .`, `ruff format .`, project-pinned isort, and `git diff --check` pass. Two real two-rank Gloo restart tests are included, but local execution was blocked by sandbox socket permissions. Mock-collective orchestration and real rank-local data-source tests passed; they are not presented as executed multi-process DDP validation. GPU, TensorFlow, and the standalone C++ suite were not run. The native CPU build disabled its optional MPI interface. Follow-up compatibility validation: **127 tests and 3 subtests passed** after preserving changed-world-size restart behavior. The existing single-process-to-two-rank restart regression is unchanged. Final CI qualification at `3d7e08d`: all 12 Python shards and all 4 C++ test variants passed. The 45-case restart-progress suite, including both real two-rank Gloo cases and the fallback tests, passed in [Python shard 5](https://github.com/deepmodeling/deepmd-kit/actions/runs/39569442075/job/119119646493). The unchanged single-process-to-two-rank restart regression passed in [Python shard 12](https://github.com/deepmodeling/deepmd-kit/actions/runs/39569442075/job/119119646455). Actual CUDA test jobs were skipped. Relocation follow-up validation at `20a9107`: **220 tests and 3 subtests passed** on the CPU build, including copied directory/HDF5/LMDB multitask restart with EMA, strict default rejection, explicit reset equivalence to legacy model/optimizer/LR/step restart, all-task/RNG isolation, malformed-envelope rejection, and schema checks. Ruff, formatting, isort, and whitespace checks passed. The two real Gloo tests were deselected locally because of the previously established socket restriction; GPU tests were not run for this follow-up. The CI qualification above remains specific to the older `3d7e08d` head, not this new commit. Refs deepmodeling#5814. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit - **New Features** - Training checkpoints preserve and restore data-reading progress and selection state. - Resumed training continues from the next directory, HDF5, or LMDB batches, including distributed and multitask training. - Progress restoration checks dataset and training configuration compatibility; incompatible or malformed saved progress is rejected. - Statistics, validation, and diagnostics do not advance training data progress. - A new setting lets you reset saved data progress while restoring the model, optimizer, schedule, and training step. - If the distributed rank count changes, training starts with fresh data progress. - **Documentation** - Clarified restart behavior, compatibility requirements, and cases where progress is not restored. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: OutisLi_Bot <44916828+OutisLi-Bot@users.noreply.github.com>
for more information, see https://pre-commit.ci
…deling#6095) ## Summary Validate Triton grid-pair launch resources before graph capture so cold compiled force training can select a feasible tile or retain the reference composition. Previously, `wrap_triton` could record a call during fake-tensor tracing without loading its kernel. The launch retry loop treated successful tracing as successful resource validation and cached an invalid tile. The actual shared-memory error then arrived during Inductor backward compilation, outside the retry loop. An eager warmup could hide this failure. ## Implementation - Separate candidate selection from execution. Compile candidates with dtype-only `warmup` inputs and load their handles to check device resource limits without allocating inputs or executing kernels. - Share specialization parameters across validation and execution, and reuse the selector for forward, first backward, and force-loss second backward. - Cache selections by kernel, device, static geometry, operand signature, and accumulator count. Keep pair counts and physical strides dynamic; cache unsuccessful searches as well. - Validate existing tuned choices through the same path. Only resource-limit errors reject a candidate; unrelated compiler errors remain visible. Preserve compiler-visible Triton operations and the reference composition when no candidate fits. ## Review follow-up validation - Five CPU checks exercise the real cached selector, including warmup/handle resource rejection, candidate retries, cached exhaustion, and propagation of unrelated compiler errors. These checks do not require CUDA hardware. - Five small cold compiled force-backward cases passed on one RTX PRO 6000 Blackwell GPU with isolated compiler caches. Before any eager reference call, all three derivative stages must have attempted validation; fallback is permitted exactly for stages without an independently observed successful handle load. Thus a selector that returns None without validation fails, while genuinely resource-limited hardware may use the reference path. On this device all four non-forced cases use fused launches; the forced case exercises all three reference paths. These five cases and the exact-parent resource failure were repeated after the portability refinement. - The cold cases use P=147 and a distinct grid size of 587, and do not call the newly introduced selector API to clear caches before the regression. - In a separate process, replacing only `_launch` with its exact pre-PR parent implementation makes the multifocus FP32 case fail during second-backward compilation with `OutOfResources`: 145408 bytes required versus a 101376-byte shared-memory limit. Repository source was not changed for that comparison; this is not an AttributeError-based failure. - Independent pre-push review and read-only lint/format checks passed. No training run or performance measurement was performed for this follow-up. ## Original PR validation Based on master `d07c097b`; this PR contains one cherry-picked commit with an identical patch to the source change. It does not depend on the ASE or native-spin PRs. Validation uses an NVIDIA RTX PRO 6000 Blackwell Server Edition with PyTorch 2.13.0+cu130 and Triton 3.7.1: - A process-local reproduction using the exact parent `_launch` implementation, with repository files unchanged, fails the cold FP32 force-backward regression: shared memory required is 118784 bytes, exceeding the 101376-byte device limit. - All 20 tests in `source/tests/pt_expt/kernels/test_grid_pair_train.py` pass in a fresh process on the unmodified branch, using separate compiler caches from the parent-launcher reproduction. - Coverage includes FP32/BF16 output and first/second-gradient checks against the float64 reference, dynamic layouts, and five cold-compile regressions. The new cases cover both production layouts, changing node counts with a single compiled graph, and a forced reference path. - Independent source review found no actionable issues. Scoped pre-commit hooks, repository Ruff, formatting checks, patch-identity checks, and whitespace checks passed. Other GPU architectures and the project-pinned PyTorch 2.10 environment were not exercised. The original commit's full-training and layout-sweep results are historical and were not repeated for this PR. No throughput improvement is claimed. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit - **Performance** - Selects suitable launch configurations before execution, prioritizing optimized options on supported hardware while retaining bounded alternatives. - Reuses successful configuration choices for matching workloads to reduce repeated selection overhead. - **Reliability** - Avoids launching configurations that exceed device resources and falls back to eager execution when no suitable compiled option is available. - **Compatibility** - Validates forward, backward, and second-order results against eager execution across dynamic batch sizes, including when compiled kernels are unavailable. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
…eling#6094) ## Summary Allow native-spin models to initialize directly from compatible spin-free checkpoints through `--finetune`, without a manually converted checkpoint. This covers PT DPA4/SeZM and PT-expt DPA4/DPA4C. The target is constructed from its fine-tuning configuration first. A shared transfer implementation copies compatible geometric weights while preserving target spin configuration, magnetic-element masks, analytical bridging, output-bias/statistics initialization, and fresh optimizer/EMA state. Same-name multitask conversion performs fine-tuning statistics rather than resuming the spin-free branch unchanged. ## Implementation - Share descriptor-specific transfer rules between PT and PT-expt; initialization does not add work to the training hot path. - Preserve DPA4's additive spin routes. For DPA4C, insert spin features between the geometric readout and trailing masses/type embeddings, preserving frame/atomic fitting parameters as well. - Support MLP and GLU input projections, including no-hidden-layer fittings, and share expanded tensors across state-dict aliases. - Reject incompatible shapes/fitting families and input residuals whose semantics would change on expansion, before loading target state. Explicit random fitting initialization remains supported. - Keep native-to-native validation and existing type-map constraints; deprecated virtual-spin conversion is outside this change. ## Validation on this branch Based on master `d07c097b`; this PR contains one cherry-picked commit, with the same patch as the requested source change. It does not depend on the ASE or grid-pair PRs. Python 3.13 / PyTorch 2.13.0+cu130, CPU only: - **115 tests and 2 subtests passed** across `test_finetune_native_spin.py`, `test_finetune.py`, `test_finetune_utils.py`, and `test_get_model_bridging.py` in the PT-expt/common suites. - Checks include initial energy/force/virial preservation, zero initial magnetic force, trainable spin gradients, MLP/GLU layouts, presets, parameter tails, failure without target mutation, serialization, and single/multitask CLI training with plain/ZBL targets. - The first restricted run passed 111 tests; four PT CLI cases hit filesystem/IPC sandbox limits. The same four unmodified tests passed with a writable Warp cache and permission to run PyTorch's shared-memory manager. No skips or assertion changes were introduced. - Independent source review found no actionable issues. Scoped pre-commit hooks, repository Ruff, formatting checks, patch-identity checks, and whitespace checks passed. GPU and distributed execution were not rerun for this PR. The original commit's validation record is historical; the results above describe this branch's verification. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Native-spin models can now be initialized from compatible spin-free pretrained models, including supported descriptor, fitting-network, multitask, and bridged-model configurations. * Fine-tuning can preserve randomly initialized fitting networks while transferring descriptor parameters. * Compatible DPA4C fitting widths can be inherited automatically, and spin references can be calibrated from fine-tuning data. * **Bug Fixes** * Improved preservation of model outputs and target settings during fine-tuning, with clearer handling of incompatible configurations. * **Documentation** * Expanded guidance on compatibility requirements and spin-free-to-native-spin fine-tuning. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
…ng#6085) ## Summary This PR combines two related ASE improvements: compiling eligible checkpoints at calculator construction, and reducing the neighbor-search and graph-preparation work performed on every evaluation. It also exposes single-pass PT-expt compression during freezing, which ASE selects automatically for supported DPA4C models. The changes are rebased onto master after deepmodeling#6045, so automatic compression uses the shared model capability interface already present upstream. The ASE stress symmetrization from deepmodeling#5799 is retained. ```python from deepmd.calculator import DP calculator = DP( model="model.pt", freeze=True, neighbor_graph_method="auto", neighbor_skin=1.0, ) ``` To reuse the compiled artifact without compiling again: ```python calculator = DP(model="model-ase_single.pt2") ``` Compression is also available directly: ```console dp --pt-expt freeze -c model.pt -o model.pt2 --compress ``` ## Checkpoint freezing and compression - Add `DP(..., freeze=True)` for PT SeZM/DPA4 checkpoints and graph-eligible PT-expt checkpoints. Eligibility is determined from the loaded model and selected head, rather than from the file extension alone. - Release the eager evaluator before invoking the existing backend exporter. Each opted-in construction rebuilds and loads a private artifact owned by its evaluator, then atomically publishes a separate copy as `<stem>-ase_single.pt2` beside the checkpoint. Concurrent processes retain their selected heads and later serialization keeps reading the private artifact; failed export/loading/publication preserves the previous public copy. The last successful publication wins. The extra private copy is removed when its evaluator is collected. Backend compilation is process-concurrent, not thread-safe; reuse the public copy after concurrent exporters finish. Unsupported models and already-frozen files keep their normal loading behavior. - Preserve multi-task head selection and normalize single-task PT heads to `None`, matching the eager loader. - Add `with_comm` to the exporters with a backward-compatible default of `True`. ASE passes `False`, compiles only the single-process artifact, and records `has_comm_artifact=False`. - Reuse the backend kernel policy: CUDA DPA4 defaults to `DP_CUDA_INFER=1` and `DP_TRITON_INFER=2`, honoring explicit environment overrides; DPA4C retains its required CUDA inference level of 2. - Keep `freeze=False` as the default. Eligible checkpoints warn about the potentially slower eager path; that path remains useful for debugging and short runs that do not amortize compilation. - Add `--compress` / `compress=True` to PT-expt freezing. The freeze and existing compress commands share the model-compression/export pipeline, including neighbor-distance handling and table defaults. Compression happens before export, without compiling an intermediate uncompressed artifact. Other backends reject `freeze --compress` during argument parsing. When saved neighbor-distance statistics are missing, the error directs CLI users to freeze without compression and then use `dp --pt-expt compress ... -t INPUT.json`. - Fold vacuum references before specializing charge-dependent compression tables. Eligible CUDA targets use the compact canonical input schema; CPU targets use the graph schema. - Share the DPA4C compression eligibility check between explicit compression and ASE selection. Unsupported precision, type exclusions, compiled profiles, or missing initial charge states produce an explicit error for `--compress`; automatic ASE compression logs the reason and continues with ordinary freezing. Other model families retain uncompressed export. - Leave `CompositeImplicitAutograd` operators to their decompositions instead of registering conflicting independent fake/Meta implementations. ## Persistent neighbor searches and graph preparation ### Search policy and cache lifetime - Expose `neighbor_graph_method` and `neighbor_skin` at the ASE boundary and forward them through `DeepPot`, including the reload after automatic freezing. ASE defaults to a 1.0 angstrom skin; direct evaluator callers retain their zero-skin default. - Prefer Vesin for single-frame CUDA graph inference and Toolkit-Ops for multi-frame CUDA batches. Preserve native CPU graph search, explicit backend choices, and native fallback when optional search dependencies are absent. - Share the extended-coordinate/edge-vector neighbor strategy factory across PT and PT-expt. SeZM/DPA4 applies inference selection in its geometry stage, preserving native forward and compiled core execution; training retains its own policy. - Keep a persistent Vesin calculator per frame. Reuse candidate lists extending to `rcut + skin`, rebuilding after sufficient displacement or changes to the cell/atom count. Every evaluation still refreshes geometry and enforces the exact model cutoff. Returned search data are copied so later evaluations cannot overwrite tensors needed by earlier autograd graphs. - Cache element-to-model type mappings until atomic numbers, atom order, or `type_dict` changes. `neighbor_skin=0.0` disables candidate reuse. ### Compact graph inputs - Construct compressed DPA1/DPA4C canonical inputs directly from Vesin displacement vectors. Produce destination-major payloads and both CSR views, with `uint32` source/order arrays, `float32` geometry, and guard storage for zero or one physical edge. - Avoid the generic graph conversion and its tensor-value reads on the host when direct canonical preparation applies. Keep generic conversion for other neighbor builders and pair-excluded graphs. - Use PyTorch destination sorting on CUDA instead of Vesin sorting. Preserve differentiable coordinate/cell geometry in the generic graph path, select virtual endpoints once, and reuse NV destination ordering where exclusion semantics allow it. - Avoid per-edge cell replication and frame-offset work for a single frame; pass a single edge-vector frame through without concatenating its arrays. - Centralize graph input packing for ordinary and native-spin inference while preserving their generic/canonical schemas, optional fitting inputs, and compressed charge-state handling. ## Compatibility and integration - Restrict CPU horizontal fusion for PyTorch 2.11 inference in the shared compiler compatibility options. Its fused gather/scatter code can reuse an index array before its declaration. This avoids the reproduced `tmp40` C++ compilation failure while retaining SIMD and vertical fusion; training, CUDA kernel fusion, and other PyTorch versions keep their existing configuration. No export/parity test is skipped or replaced with a mocked compile. - Make local spin samples contiguous before PT edge-vector export, so traced frame strides do not depend on ghost storage and work for batched input. Existing affected native-spin edge-vector artifacts must be regenerated to obtain this layout correction. - Restrict the Vesin CUDA empty-cache workaround to the specific known pointer error with skin enabled. An uncached retry is accepted only when it returns an empty result; unrelated failures and nonempty retries still raise the original exception. - Load PTE archives within a CPU device context at both inference and serialization boundaries. This avoids accidental default-device placement of the storage wrapper in PyTorch 2.13 while retaining tensor devices recorded in the archive. - Require both `vesin` and `vesin-torch` >= 0.6 on supported PyTorch targets. Older PyTorch targets and macOS x86_64 retain native neighbor construction without requiring these bindings. - Put the shared tiny SeZM test configurations in a backend-neutral test module. Collecting the PT-expt ASE tests no longer initializes the PT test package, repeats its global interop-thread setup, or inherits its sentinel default device. - Scope the synthetic CUDA device query to entering the real export-policy context in the policy test. Lazy imports during model/schema construction retain the actual query, so subsequent CPU exports cannot inherit a mocked CUDA target. The real policy and environment-restoration checks remain covered. - Document the calculator options, supported input schemas, cache invalidation, compression fallback, and artifact reuse in the ASE guide. ## Validation ### Cell-cache review validation (2026-10-21) - Rebuild only the affected frame's Vesin calculator when its cell values or periodicity change. Store an independent detached cell snapshot so in-place cell updates are detected; fixed-cell searches keep reusing their calculator. Skin-zero searches do not compare or snapshot cells. - The one-atom, multiple-periodic-image contraction regression fails before the fix and passes afterward for both image shifts and displacement vectors. It also checks fixed-cell reuse, in-place contraction, frame isolation, and periodic/nonperiodic transitions. - Correct the default neighbor-builder expectation and test the actual strategy factory across CPU/CUDA and Vesin/NV availability combinations. - CPU validation: **87 passed, 26 skipped, 38 subtests passed**, covering Vesin graph/search behavior, checkpoint inference, nlist integration/builders, and cached ASE energy/force/stress parity. Independent review found no actionable issues; scoped pre-commit, repository Ruff, and whitespace checks passed. - Comparing cached periodic CUDA cells synchronizes the rebuild decision. This is a correctness tradeoff; its overhead and GPU execution were not measured in this review fix. ### Review-fix validation (2026-10-19) - PyTorch 2.13 CPU: the full ASE calculator, freeze/compression, graph-builder dispatch, graph-archive metadata, and CLI argument-parser files passed **152 tests**, with **15 existing conditional skips**. The compiler-compatibility file passed **9 tests** separately. - PyTorch 2.11.0+cpu with AVX2 code generation: the complete freeze/compression and compiler-compatibility files passed **23 tests**, including actual float64 AOTI export and energy/force/stress comparisons. The undeclared-index-temporary failure was reproduced before the production compiler-option fix. - All five artifact-ownership/concurrency/failure checks failed before the ownership fix and passed afterward. The negative CLI cases and both stale regression expectations were also reproduced before their corrections. The concurrency test controls file I/O with exporter doubles; actual compilation is covered by the sequential export tests. - Final independent review found no actionable issues. Scoped pre-commit hooks, repository Ruff, and whitespace checks passed. - These review fixes were validated on CPU; CUDA and performance/MD matrices were not rerun. The earlier CUDA and benchmark results below remain historical validation, not new measurements. ### Rebased-branch validation Validation uses Python 3.13, PyTorch 2.13.0+cu130, and Vesin / vesin-torch 0.6.1. CUDA runs use one RTX PRO 6000 Blackwell Server Edition GPU. Tests generate their own small models/artifacts; the benchmark matrices below were not rerun. - Full CPU ASE/freezing/compression/graph-utility/export-policy suite: **109 passed, 32 skipped**, including real single-artifact exports, native-spin edge-vector reloads, DPA4C compressed export, and the float64 uncompressed fallback. - CPU PT neighbor-backend and PT-expt checkpoint inference suites: **48 passed, 7 skipped, 34 subtests passed**. - CPU PTE default-device, frame/atomic-parameter, and neighbor-backend checks: **13 passed, 2 skipped, 2 subtests passed**. - The upstream asymmetric-virial ASE stress regression: **1 passed**. - CUDA canonical/Vesin graph checks, cached-neighbor/type parity, and real automatic freeze/reload comparisons: **32 passed**. This includes actual compilation and energy/force/stress comparisons for PT SeZM/DPA4 and PT-expt DPA4, DPA4C, DPA1 and DPA2. - The policy-mock/CPU-compression sequence reproduced the test-isolation failure before the scoped-mock correction and passes all **13 checks** afterward. This correction changes only the test harness, not production device selection or numerical tolerances. - Repository Ruff, scoped pre-commit hooks, and whitespace checks pass. Independent review found no remaining actionable issues and additionally checked bridged/native-spin DPA4C compression/serialization and preservation of the analytical component. That additional review simulated final artifact writing; actual AOTI compilation is covered by the tests above. The full repository test suite and the historical performance/MD matrices were not rerun for this rebase. CPU-only runs skip CUDA-conditional cases; missing-dependency branches also skip when the optional dependency is installed. ### Original development validation The original two commit messages record the following development runs. These groups cover different stages and may overlap; they are not an aggregate test count or a claim that every run was repeated for this rebase. - Freezing: 44 checkpoint/head/kernel/export-policy checks; 43 CPU export/compatibility checks; two existing ASE calculator tests; and five real CUDA export/ASE round trips across PT SeZM/DPA4 and PT-expt DPA4, DPA4C, DPA1, and DPA2. Checks include energy, forces, stress, reload, source-checkpoint integrity, and exactly one compilation per ASE export. - Compression: 57 focused CLI/shared-pipeline/fallback/error/fake-op checks; actual float64 fallback export; compressed CPU and CUDA ASE exports with compression operators in the exported graph; and trained `dpa4c-air-v20260911` checkpoint comparisons. - Graph/input preparation: 53 CPU/CUDA graph-utility checks, 28 CPU inference checks, 13 CPU edge/neighbor checks, and three CUDA compressed charge-state route checks. Coverage includes dual CSR, zero/one edge, empty systems, virtual atoms, multiple frames, periodic geometry, cache updates, result lifetime, gradients, and empty/nonempty transitions. - All 22 frame/atomic-parameter and spin-parameter checks passed after the archive-loading correction. Default-device regressions covered CPU/CUDA execution under meta and invalid-CUDA defaults; the corresponding cases failed before the correction. - 120 real exported-model comparisons covered ordinary/compressed Air, DPA1 canonical and DPA4C native-spin canonical inputs, multiple frames, isolated/padded atoms, and periodic/nonperiodic systems. - All 24 paired MD initial-state comparisons passed, with maximum differences of `1.074e-5 eV/angstrom` in force and `1.202e-7 eV/atom` in energy. The larger scaling matrices below additionally passed all 54 Mini and 120 Air initial energy/force/stress comparisons, with model/artifact/runtime-library hashes verified. ## Original performance measurements The following results are reproduced from the original commit messages. They were measured during development, not rerun against the rebased branch. Each experiment has its own baseline; speedups from separate tables should not be multiplied. Timings exclude initialization/export/warmup unless explicitly stated and describe the measured workloads, not a universal performance guarantee. ### Eager versus frozen ASE evaluation Preset `dpa4c-air-v20260911`, float32 with `vacuum_ref` enabled, PyTorch 2.13.0+cu130, one NVIDIA RTX PRO 6000 Blackwell Server Edition GPU. Three OMat24 validation structures and periodic supercells were evaluated with 20 warmup steps and five timed blocks of 40 steps, alternating execution order. Coordinates changed every step to invalidate the ASE cache; GPU synchronization bracketed each block. The median timings include neighbor construction and transfers. Inference environment overrides were unset. | Atoms | Eager (ms/step) | Frozen (ms/step) | Speedup | | ---: | ---: | ---: | ---: | | 16 | 15.85 | 4.54 | 3.49x | | 64 | 16.23 | 4.63 | 3.51x | | 128 | 16.35 | 4.68 | 3.50x | | 1,024 | 17.20 | 5.91 | 2.91x | | 8,192 | 24.17 | 11.86 | 2.04x | Eager initialization took 4.38 s, automatic freezing/loading 50.91 s, and direct reload of the compiled artifact 0.26 s in that benchmark process. Maximum frozen/eager differences were `4.47e-7 eV/atom` in energy, `1.67e-5 eV/angstrom` in force components, and `2.91e-8 eV/angstrom^3` in stress. The source checkpoint was unchanged. ### Ordinary versus compressed frozen ASE evaluation The same preset, precision, vacuum-reference setting, PyTorch version, OMat24 structures and supercells were used. Coordinates changed each step and execution order alternated. End-to-end force-evaluation timings include neighbor construction/transfers; export and warmup are excluded. CUDA: one RTX PRO 6000 Blackwell Server Edition GPU, 20 warmup steps, five blocks of 40 steps, synchronized around each timed block. | Atoms | Frozen (ms/step) | Compressed (ms/step) | Speedup | | ---: | ---: | ---: | ---: | | 16 | 4.67 | 3.64 | 1.28x | | 64 | 4.73 | 3.70 | 1.28x | | 128 | 4.82 | 3.75 | 1.28x | | 1,024 | 6.03 | 4.99 | 1.21x | | 8,192 | 12.00 | 6.19 | 1.94x | CPU: Intel Xeon Platinum 8558P, `OMP_NUM_THREADS=1` and one PyTorch compute thread, 10 warmup steps, three blocks of 20 steps. | Atoms | Frozen (ms/step) | Compressed (ms/step) | Speedup | | ---: | ---: | ---: | ---: | | 16 | 41.66 | 1.55 | 26.91x | | 128 | 64.57 | 6.67 | 9.68x | | 1,024 | 242.45 | 44.86 | 5.40x | Maximum compressed/eager differences: | Device | Energy (eV/atom) | Force components (eV/angstrom) | Stress (eV/angstrom^3) | | --- | ---: | ---: | ---: | | CUDA | 5.66e-7 | 1.78e-5 | 7.25e-8 | | CPU | 6.29e-7 | 1.43e-5 | 6.54e-8 | Compressed export/loading took 26.60 s on CUDA and 13.60 s on CPU in those processes. Compression increases artifact size: the measured CUDA artifact grew from about 15 MiB to 145 MiB because it contains frozen tables. Source checkpoints and earlier exported artifacts were preserved. ### Isolated graph/input-preparation effect RTX PRO 6000 Blackwell Server Edition and Xeon Platinum 8558P, PyTorch 2.13.0+cu130, one CPU thread and identical frozen artifacts. Complete ASE NVE steps used a 1 fs timestep, 300 K initial velocities, 20 warmup steps and 100 timed steps, with three alternating before/after repetitions. The reference in this experiment already uses cached Vesin searches. It isolates the graph/input-preparation changes within that shared design, rather than comparing the complete PR with unmodified ASE. | Preset / artifact | Atoms | Before (ms/step) | After (ms/step) | | --- | ---: | ---: | ---: | | Mini, ordinary | 512 | 9.16 | 9.22 | | Mini, ordinary | 8,000 | 92.56 | 92.50 | | Air, ordinary | 512 | 6.67 | 5.81 | | Air, ordinary | 8,000 | 36.50 | 32.60 | | Air, compressed | 512 | 4.22 | 2.61 | | Air, compressed | 8,000 | 10.04 | 4.69 | Compressed Air improved by 1.62x / 2.14x at 512 / 8,000 atoms. Mini showed no stable end-to-end improvement. Shared-host load varied: compressed Air at 8,000 atoms ranged from 8.33–10.11 ms before and 3.58–5.06 ms after. ### Complete ASE optimization and deployment scaling Here, "before" means the parent of the neighbor/graph optimization commit and "after" includes that complete optimization. This is distinct from the isolated graph-preparation experiment above. One RTX PRO 6000 Blackwell Server Edition GPU per run, Xeon Platinum 8558P CPUs, PyTorch 2.13.0+cu130, TF32 disabled, and one MPI rank for LAMMPS. All variants use diamond carbon with identical coordinates and 300 K initial velocities, NVE at 1 fs, 20 warmup steps and 100 timed steps, repeated three times. Values are median complete-MD throughput in atoms/s, rounded to integers; export, compression, loading and warmup are excluded. Checkpoint rows use PT for DPA4 and PT-expt for DPA4C. Freeze rows use uncompressed PT-expt `.pt2` artifacts; freeze + compress rows use compressed artifacts. Each frozen artifact is shared across its frontend comparisons. Ordinary LAMMPS uses the allocated CPU thread count. Kokkos uses device MD/neighbor-list execution with one host thread, the same CPU allocation and DeePMD intra-op limit, and the shared PT-expt model. DPA4 preset Mini: eight physical CPU cores per run. Independent runs execute concurrently on separate GPUs and disjoint GPU-local CPU cores; all variants in a repetition use the same GPU. | Variant | 512 atoms | 3,136 atoms | 9,680 atoms | | --- | ---: | ---: | ---: | | ASE `.pt` before | 13,188 | 17,505 | 18,214 | | ASE `.pt` after | 13,480 | 18,500 | 18,479 | | ASE freeze before | 56,141 | 77,661 | 80,307 | | ASE freeze after | 65,248 | 85,011 | 87,357 | | LAMMPS freeze | 76,718 | 87,101 | 87,988 | | LAMMPS Kokkos freeze | 75,165 | 87,353 | 88,945 | DPA4C preset Air: 24 physical CPU cores local to the GPU per run; all runs execute serially. | Variant | 512 atoms | 3,136 atoms | 9,680 atoms | 49,248 atoms | | --- | ---: | ---: | ---: | ---: | | ASE `.pt` before | 29,867 | 93,962 | 116,377 | 118,342 | | ASE `.pt` after | 32,049 | 110,497 | 122,495 | 120,628 | | ASE freeze before | 83,740 | 175,846 | 230,227 | 239,501 | | ASE freeze after | 117,170 | 220,846 | 252,397 | 249,470 | | ASE freeze + compress before | 113,548 | 456,463 | 1,052,187 | 1,510,584 | | ASE freeze + compress after | 253,795 | 1,268,573 | 2,199,040 | 2,698,941 | | LAMMPS freeze | 156,523 | 198,797 | 203,997 | 180,545 | | LAMMPS Kokkos freeze | 169,509 | 247,170 | 269,813 | 269,648 | | LAMMPS freeze + compress | 310,375 | 794,813 | 927,621 | 753,016 | | LAMMPS Kokkos freeze + compress | 585,428 | 2,836,777 | 4,239,738 | 6,439,693 | All 54 Mini and 120 Air initial energy/force/stress comparisons passed. Across these scaling matrices, the maximum initial force difference was `1.848e-5 eV/angstrom` and the maximum energy difference was `5.886e-7 eV/atom`. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * ASE can freeze eligible PyTorch models for inference, with automatic compression for supported DPA4C models. * Configure neighbor-search methods and skin distance in ASE and inference workflows; automatic selection adapts to device and frame count. * Freeze models with optional compression and choose whether to include communication artifacts. * Compatible PyTorch installations can use Vesin-based neighbor search. * **Bug Fixes** * Improved graph inference, device-independent model loading, and single-frame handling. * Unsupported automatic compression falls back with a warning; explicit compression reports unmet requirements. * Invalid neighbor skin values are rejected. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
…epmodeling#6110) ## Summary This PR speeds up compressed DPA4C models in LAMMPS on CUDA (pt-expt backend, `pair_style deepmd/kk` and `dpa4spin/kk`). It rebuilds the inference path from the Kokkos graph build to the force epilogue, derives its launch choices for the Tesla V100, L20 and H20 as well as the RTX PRO 6000 Blackwell it was developed on, and extends the compact canonical schema to multi-task branches with a shared fitting network and to graphs whose node count exceeds the 32-bit index range. The fp32 contract of the model is kept throughout. Every change either leaves every output unchanged bit for bit, or reorders a floating-point sum by design and is checked against the uncompressed model in fp32 and fp64. No reduced-precision arithmetic (TF32, bf16, fp16, split precision) is used. Forces are now assembled in 64-bit fixed point, so they no longer depend on the scheduling order and runs are reproducible. ## Measured speedups All timings are LAMMPS step times against the parent build with the same frozen models; each commit message gives the conditions and the number of runs per point. RTX PRO 6000 Blackwell (sm_120), the five v20260911 grades (Nano to Plus), ratio of old to new step time: | System | 512 atoms | 10,296 atoms | 100,800 atoms | | --- | --- | --- | --- | | diamond carbon | 3.5-4.9x | 2.5-2.9x | 2.0-2.9x | | B, C and N at random on the same sites | 3.5-5.1x | 2.4-2.7x | 1.9-2.6x | | five elements at random (frozen geometry) | - | 2.5-3.5x | 1.9-2.7x | | native spin, Newtonian NVE | 3.5-5.3x | 2.3-2.7x | 1.8-2.8x | The largest system that one device runs grows from 14.05 to 22.43 million atoms, and the throughput above one million atoms grows by 2.6-3.0x. Per-GPU tuning, change of the step at 10,296 / 100,800 atoms of diamond carbon relative to the sm_120-tuned build: - V100: Nano -21.0 / -25.9%, Mini -25.2 / -36.8%, Air -4.9 / -6.1%; native-spin Nano -21.5 / -24.6% - H20: Nano -3.2 / -3.9%, Neo -5.1 / -2.5%, Air -3.7 / -1.5%; native-spin Neo -8.2 / -4.3% - L20: Nano -3.8 / -0.0%; the other grades within 0.3% Where the freeze-time measurement departs from the rules, the step takes up to 11% less time again (Neo at 6,160 atoms on the L20: -11.2%; Plus at 720 atoms on the H20: -9.3%). A frozen branch of a multi-task DPA4C with a shared fitting network now reaches the fused path: the OMat24 branch of the two-branch OpenLAM DPA4C Mini takes 0.151 / 0.449 / 2.905 ms per step on diamond carbon at 512 / 10,296 / 100,800 atoms, against 1.133 / 1.504 / 10.19 ms before (3.1-7.7x, similar on B/C/N). Several ranks without a GPU-aware MPI: on three RTX PRO 6000 GPUs, Nano at one million atoms takes 6.8 ms per step with a CUDA-aware Open MPI, 11.3 ms with MPICH and the device fold of this PR, and 13.8 ms with the host path of LAMMPS, against 15.2 ms on one GPU. ## Commits The five commits are self-contained and are easiest to review one at a time; each message records its design and its measurements. 1. **perf(dpa4c): accelerate compressed DPA4C inference on CUDA in LAMMPS** (the core) - Kokkos graph build: one pass fills every row of the compact canonical graph (cp.async staging of the neighbor lists, fixed-point squared-distance keys, warp sorts, decoupled look-back for the output offsets). The edge storage is sized by the candidate count, so the edge count never leaves the device and the per-step readback and synchronization disappear. - Model replay: the evaluation of a graph without halo nodes is captured once into a CUDA graph and replayed, keyed by the addresses and extents of its inputs. A per-instance mutex serializes the runs of a model, a failed capture turns capturing off for that model, and a step that requests the per-atom virial evaluates eagerly. - Fused energy-force operator: prologue and epilogue kernels derive the ownership mask, frame offsets and segment sums inside the operator; the edge backward assembles the force directly in 64-bit fixed point (2^-32 eV/A); a frame with a non-finite energy or virial or an out-of-range force contribution reports NaN forces. - Edge scans: rows of small systems are shared among 2, 4 or 8 warps; wide profiles co-schedule 16-24 rows per block in lockstep windows of bond length; one node type takes folded scans, two to eight types take slotted scans with 4 or 8 per-type slots; a low-rank radial table is adopted at compression only where it reproduces every channel and its radial derivative at the knots to 1e-8; bond vectors are prefetched into L2. Generated shards (`shard.cu.in`) replace `graph_compress_c*.cu`. - Fused fitting network: one kernel carries a node panel through every hidden layer, the energy head and the input-gradient backward, bitwise equal to the per-layer kernels; small runs split a panel over a thread-block cluster. 2. **perf(dpa4c): tune compressed DPA4C CUDA inference for V100, L20 and H20** - The fitting route follows the fp32 ridge (peak FLOP rate over DRAM bandwidth) and the compute capability of the device. Freezing or compressing for a CUDA device times the fused shapes against the per-layer kernels with CUDA-graph replays and stores the departures from the rules with a fingerprint of the device; another device takes the rules. The measurement adds 15 s to 3 min to a freeze, and every route gives the same outputs bit for bit. - sm_70 register budgets; every launch choice follows from the device and the system, without environment overrides. - Without a GPU-aware MPI, `deepmd/kk` and `dpa4spin/kk` pack the ghost values on the device and stage only those through pinned host buffers, bit for bit as the host path. - dpmodel: integer indices are bounded with `maximum` instead of `clip`, which array_api_compat < 1.14 lowers to `isnan` on integers, an operation AOTInductor cannot compile. 3. **perf(dpa4c): deploy the per-GPU tuning on V100, L20 and H20** - The route measurement holds on boards at their power limit: bursts and long single-route trains, over samples of one and of several node types, and a route departs from the rules only where it wins both. - The shared Inductor options give kernels separate output buffers, which avoids a Triton 3.7.1 race in in-place reductions under warp replication. - The RUNPATH of the LAMMPS plugin also holds `$ORIGIN/..`, so `LAMMPS_PLUGIN_PATH` alone loads it. - Documentation: `pair_style dpa4spin` and its Kokkos variant in the LAMMPS command reference, when compression keeps a fitting kernel other than the default, and the CUDA support of Open MPI for runs on several GPUs only (it lengthens a small single-rank step by 10-18%). 4. **perf(pt_expt): fold the case embedding of a shared fitting network at export** - The constant one-hot case embedding of a deployed branch is folded into the bias of the first fitting layer, so the export, the launch tuners and the fused operators see a plain fitting network while `model.json` keeps the branch as trained. A first layer whose residual carries the case embedding past the activation keeps it, with a warning. 5. **feat(pt-expt): support automatic-width canonical graph indices** - Source indices are 32- or 64-bit by the node extent, while edge counts, CSR offsets and source-grouped edge positions stay int64. A byte-word carrier lets one exported canonical artifact accept either width without copying; the Kokkos producer gains 64-bit edge prefixes and source CSR. ## Interfaces and compatibility - Compressed DPA4C `.pt2` archives must be re-frozen: the schema of the fused operator and the source-word ABI of canonical artifacts changed. DPA4 archives keep loading. - C API version 31: `DP_DPA4ComputeCanonicalGraphGPU` and `DP_DPA4SpinComputeCanonicalGraphGPU` replace `DP_DeepPotComputeCanonicalGraphGPU` and `DP_DeepSpinComputeCanonicalGraphGPU` of versions 28 to 30, and take the graph virial, the caller's stream, the node positions and the MPI communicator. The new names are deliberate: a binary built against an earlier version fails to load instead of calling a function of another signature. - The backend plugin interface is version 2 (`deepmd_create_deeppot_backend_v2`, `deepmd_create_deepspin_backend_v2`); a version-1 plugin is refused at load. Binaries and plugins built against C API version 30 or backend interface version 1 must be rebuilt. - `DP_DeepPotHasLongRange`, `DP_DeepPotModelDeviHasLongRange` and `has_long_range()` on `DeepPot` and `DeepPotModelDevi`, together with the node-position and communicator arguments above, are the interface of a long-range module that a follow-up PR adds. No model in this PR has a long-range module, so these paths are inactive here; carrying them now avoids a second version bump of the C API and the plugin interface. ## Validation on this branch The branch is based on master 1ded5d2 and holds the five commits cherry-picked from the development branch. Against the commits validated there, the rebase changes no file under `source/api_c`, `source/api_cc`, `source/lib`, `source/lmp` or `source/op`. - One semantic conflict with deepmodeling#6085: its new test `test_compact_canonical_deep_eval` asserted the former `uint32` source carrier. The last commit updates it to the byte-word carrier (`uint8` with a word axis of 4 for a small graph) and the int64 `source_order`; the test failed before the update and passes after it. - pre-commit over the whole range: all hooks passed. - Local run on an RTX PRO 6000 Blackwell (PyTorch 2.13.0+cu130, CUDA 13.3): `source/tests/pt_expt/descriptor` 1611 passed and 81 skipped (the skips need the CPU operators or `DEEPMD_ENABLE_DPA1_HIGH_LMAX=ON`, which this build did not compile), apart from the test above. The other Python suites, the C++ suites and the LAMMPS tests were not rerun locally for this branch and are left to CI, including the `Test CUDA` jobs. The validation records in the commit messages (pytest and C++ suites, bitwise LAMMPS comparisons, fp64 accuracy checks, multi-rank runs) describe the development branch. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Compact canonical graph inference now supports automatic-width indices, optional virial outputs, caller-provided streams, and long-range capability queries. * Added CUDA graph replay, fitting-route selection, low-rank radial-table compression, and optional source-CSR generation. * Compressed native-spin models can use the `dpa4spin` LAMMPS pair style, including Kokkos execution. * Eligible case embeddings can be folded into fitting networks during export. * **Bug Fixes** * Improved handling of optional compression artifacts and compiled inference buffers. * Long-range models now reject periodic boundaries during LAMMPS initialization. * **Documentation** * Updated installation, LAMMPS/Kokkos, MPI, spin-force, and backend-plugin compatibility guidance. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
…#6113) ## Summary - Add `atol=1e-14` only to the Paddle/TensorFlow **atomic-virial** consistency assertion. - Keep NumPy's default `rtol=1e-7` and all energy, force, total-virial, loss, and parameter-gradient assertions unchanged. - Explain why near-zero atomic virials need an absolute roundoff allowance. ## Why [The failing Python CI job](https://github.com/deepmodeling/deepmd-kit/actions/runs/40690631898/job/122824196329) on `1293cefa3` failed at `TestEnergy.test_consistency`'s atomic-virial comparison: 1 of 1728 components violated `rtol=1e-7, atol=0`. The maximum absolute difference **among the violating components** was `3.80690488e-17`, with relative difference `2.17352101e-7`. Paddle forms atomic virials by adding a force-coordinate product and an atomic correction. Cancellation can make individual components close to zero, where a purely relative comparison is brittle. The new floor is a conservative float64 roundoff budget, not a mathematical error bound; it is also 100 times tighter than the `1e-12` absolute tolerance used by neighboring Paddle model fixtures. No production calculation changes. ## Validation Isolated CPU environment: Python 3.12.14, Paddle `3.4.0.dev20260310` (the CI-pinned nightly), TensorFlow CPU 2.21.0, NumPy 2.5.4; TensorFlow custom C++ operators built locally. - `python -m pytest source/tests/pd/model/test_model.py source/tests/pd/model/test_dp_model.py -q`: **15 passed** (with CI's Paddle-before-TF import order and stride-kernel setting). - Ten additional complete consistency-test runs, including parameter-gradient checks: **10 passed**. Atomic-virial values spanned approximately `[-0.1045, 0.1805]`; per-run maximum absolute differences over the full array were `6.15e-16–2.09e-15`. - These ten local samples would also pass the original relative-only check; the intermittent CI failure was **not** reproduced locally. - A synthetic pair at the reported CI scale fails the old assertion and passes the new one. The updated assertion still rejects `1e-13` absolute errors at zero/near zero and a `2e-9` error at value `1e-2`. - Repository-pinned Ruff 0.16.0: `ruff check .` and `ruff format --check .` passed; `git diff --check` passed. - `dp --version` and `dp --pd -h` passed. No GPU/CUDA testing or full-suite claim. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Tests** * Adjusted the atomic-virial consistency check to allow for floating-point roundoff when values are near zero. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
) ## Summary Reduce test-suite maintenance and execution overhead without changing production code or CI workflows. - Consolidate model and atomic-model metadata checks into contract tests, retaining assertions on original, deserialized, and supported TorchScript models. Keep Python-only capability checks on the original model. - Remove seven unused descriptor parameter matrices while preserving all 55 retained factory configurations. Keep the full one-hot type-map boundary matrix; use permutation, growth, and shrinkage cases for fixed-width electronic-configuration embeddings. - Reuse training checkpoints and exported artifacts across related freeze and fine-tuning checks. Keep both fine-tuning configuration policies and isolate their output directories. Compare against the original pretrained weights instead of an overwritten checkpoint. - Remove duplicated TF compression and learning-rate tests, permanently skipped unsupported Paddle cases and their exclusive fixtures, and obsolete force-gradient suites. - Remove tests that only pin prose or source spelling, while retaining executable documentation examples and configuration checks. No new skips or relaxed numerical tolerances are introduced. Distinct gradient, cold-cache, error-path, and second-export checks are retained. ## Scope and expected benefit - 34 test files changed; net reduction of 2,504 lines. - The four universal model/atomic-model modules collect **4,749 tests instead of 11,068**. Their metadata assertions and model variants remain; this reduces test-framework overhead, not an equivalent number of JIT compilations. - Source-level accounting removes **9 repeated training runs and 5 repeated exports**, in addition to redundant internal parameter combinations. These are collection and operation-count reductions, not a measured end-to-end CI speedup. ## Validation Targeted local CPU checks: | Coverage | Result | | --- | --- | | Universal metadata and capabilities | 976 passed, 7 skipped | | Descriptor and embedding type-map changes | 40 passed | | Fine-tuning CLI, including actual PT2 export | 7 passed, 6 subtests passed | | TF radial/angular compression suites | 24 passed | | Executable examples and retained force finite differences | 7 passed | | Shared unit tests, activation/TF2, neighbor selection, multitask training, compiled varying shapes, and freeze/vacuum-reference regressions | 205 passed, 48 skipped, 4 subtests passed | All 55 retained descriptor factory configurations were compared with the base commit and matched. Repository pre-commit checks passed. Paddle was unavailable locally: its deletions were checked by AST comparison and consumer/reference searches, not Paddle execution. GPU and full-suite CI runs were not performed locally. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Tests** * Expanded validation of model metadata, serialization round trips, frozen-model evaluation, and finetuning across supported artifact formats. * Added coverage for multitask training workflows, including checkpoint restarts, selected-head freezing, and changes to model parameters. * Broadened type-map test cases and strengthened checks for compiled training behavior with varying atom counts. * Consolidated related test checks and removed redundant or skipped test cases. These changes affect test coverage, not end-user functionality. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
…deepmodeling#6111) ## Summary Replace the CUDA workspace-budget policy introduced in deepmodeling#6024 with one shared adaptive batch controller. Successful inference no longer reads allocator statistics/snapshots/device free memory or clears the CUDA cache. The PyTorch adapter only detects and recovers from OOM; PT and PT-expt use the same generic control flow. - Grow full successful batches geometrically, using actual successful work when even one frame exceeds the initial atom budget. Reuse the atom budget across systems instead of recalibrating on every atom-count change. - On OOM, back off from the **actual attempted size**, retry the same input, and preserve one-frame failure and `RetrySignal` semantics. - A remembered OOM bound is not permanent: try crossing it after 2 successful full batches, then 4, then at most 8 on later recovery probes. A successful actual batch can disprove the old bound; a clipped tail cannot. Ordinary growth below a known bound is immediate. This favors recovering large batches after dense-to-sparse changes while damping repeated probes, including alternating workloads. - Whole-input retry mode defers probes beyond a known failed bound until `execute_all` has successfully assembled the complete result, then schedules the probe for the next invocation. This prevents repeated `RetrySignal` restarts while preserving recovery on later sparse inputs; direct `execute` calls in retry mode remain conservative because they have no completion boundary. - Preserve positive `DP_INFER_BATCH_SIZE` and CPU no-growth behavior, output concatenation/ownership, and the existing `dp test` streaming pipeline. Short tails neither shrink the budget nor trigger growth. The 2/4/8 schedule is a deliberately short, bounded recovery policy, not a hardware-optimal constant. It permits occasional OOM retries on a stationary workload; avoiding every OOM would require either permanent conservative limits or additional observations. This does not claim an exact maximum batch size or universally optimal GPU throughput. ## Validation Fresh PyTorch CPU editable build from upstream `1ded5d2429467fb16cb1d6c3d3059fac881f82a7`; verified imported source paths point to this worktree. - `ruff check .`, `ruff format .`, `git diff --check`: clean. - `NUM_WORKERS=0 OMP_NUM_THREADS=2 MKL_NUM_THREADS=2 python -m pytest source/tests/common/test_auto_batch_size.py source/tests/pt/test_auto_batch_size.py source/tests/pt/test_dp_test.py source/tests/common/test_dp_test_ener_split.py source/tests/pt_expt/test_dp_test.py -q`: **54 passed, 4 subtests passed** (82 s), rerun after the retry-mode fix. - Real PT and PT-expt tests cover model construction/checkpoint or export and `dp test` outputs. `NUM_WORKERS=0` avoids this container's unsupported shared-memory-manager subprocess/socket; inference itself is unchanged. - Additional validation: all 8 `source/tests/pt/model/test_embedding.py` tests passed after installing the missing optional `e3nn` dependency. An exact-production `_eval_legacy_feature` harness also verified repeated 41-frame dense evaluations and dense-to-sparse recovery, with one bounded restart and no duplicated hook outputs. The new automatic-growth whole-input retry regression fails on the previous PR head within a bounded number of attempts, rather than hanging. - Regression cases cover repeated short systems, fixed-workspace batching, changed memory pressure, dense-to-sparse recovery at maximum probe delay, alternating capacities, actual attempted-size backoff, clipped probes, tails, fixed limits and retry mode. Four 8-frame systems with alternating atom counts execute as four batches, without successful-path allocator access. - Mutation check against the pre-change master controller catches the old allocator-profiling path even on a CPU runner by explicitly emulating the native CUDA environment. No GPU was available: these are correctness and mechanism checks, **not measured GPU speedup or CUDA execution evidence**. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * GPU inference batches grow after successful full batches and shrink and retry after out-of-memory errors. After recovery, the system gradually probes larger batches again. * Setting a positive `DP_INFER_BATCH_SIZE` keeps automatic growth and recovery probes disabled. * Batch sizing no longer relies on CUDA allocator-state inspection after successful inference. * **Documentation** * Updated guidance describes adaptive batch sizing for `dp test` and full validation, including how short final batches and explicit batch-size settings affect growth. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 4.2 to 4.3. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/pypa/cibuildwheel/releases">pypa/cibuildwheel's releases</a>.</em></p> <blockquote> <h2>v4.3.0</h2> <ul> <li>✨ Extends <a href="https://cibuildwheel.pypa.io/en/stable/configuration/#inherit">option inheritance</a> to every configuration layer, so global and platform-specific settings can append or prepend to existing values, including cibuildwheel's defaults. Environment variables can also extend earlier settings using <code>CIBW_INHERIT</code>. (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2928">#2928</a>)</li> <li>✨ Adds PyPy 3.12 support and updates PyPy 3.11 to v8.0.0, available with the <code>pypy</code> <a href="https://cibuildwheel.pypa.io/en/stable/options/#enable"><code>enable</code></a> flag (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2998">#2998</a>)</li> <li>✨ Adds GraalPy 3.13 (v25.3) support on Linux, Windows, and macOS arm64, available with the <code>graalpy</code> <a href="https://cibuildwheel.pypa.io/en/stable/options/#enable"><code>enable</code></a> flag (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2982">#2982</a>)</li> <li>✨ Adds <a href="https://cibuildwheel.pypa.io/en/stable/options/#log-fold-mode"><code>log-fold-mode</code></a> to override CI log folding, including <code>CIBW_LOG_FOLD_MODE=disabled</code> to keep build steps expanded (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2972">#2972</a>)</li> <li>✨ Adds a <code>python-path</code> input to the GitHub Action to choose the Python interpreter used to run cibuildwheel, and falls back to system <code>python3</code> on runner architectures unsupported by <code>setup-python</code>, such as native riscv64 (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2990">#2990</a>)</li> <li>🐛 Fixes Windows command execution when paths or arguments contain shell metacharacters, including dependency specifiers containing <code><</code> or <code>></code> (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2978">#2978</a>)</li> <li>🛠 Improves readability of logged commands whose arguments contain quotes (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2993">#2993</a>)</li> <li>🛠 Updates Pyodide to 0.27.8, 0.29.5, and 314.0.7, and updates its build tooling, including auditwheel-emscripten 0.3.0 (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2996">#2996</a>)</li> <li>🛠 Updates dependencies and container pins, including CPython 3.15.0rc3 (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2986">#2986</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/3003">#3003</a>)</li> <li>📚 Corrects references to <code>--archs</code> in CLI help, error messages, and documentation (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2992">#2992</a>)</li> </ul> <h2>v4.2.1</h2> <ul> <li>🐛 Respects the NuGet package sources configured on the machine when installing CPython on Windows, instead of always falling back to nuget.org (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2966">#2966</a>)</li> <li>🐛 Fixes a <code>NameError</code> on Pyodide when an already-compatible wheel was reused, which made the test step fail (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2968">#2968</a>)</li> <li>🛠 Updates the Android Python versions, and the Android testbed's Gradle version, making it compatible with Java 25 (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2962">#2962</a>)</li> <li>🛠 Updates dependencies including CPython 3.15.0rc2 (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2965">#2965</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/2970">#2970</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/2976">#2976</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/2981">#2981</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/2985">#2985</a>)</li> </ul> </blockquote> </details> <details> <summary>Changelog</summary> <p><em>Sourced from <a href="https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md">pypa/cibuildwheel's changelog</a>.</em></p> <blockquote> <hr /> <h2>title: Changelog ref: changelog</h2> <h1>Changelog</h1> <h3>v4.3.0</h3> <p><em>5 October 2026</em></p> <ul> <li>✨ Extends <a href="https://cibuildwheel.pypa.io/en/stable/configuration/#inherit">option inheritance</a> to every configuration layer, so global and platform-specific settings can append or prepend to existing values, including cibuildwheel's defaults. Environment variables can also extend earlier settings using <code>CIBW_INHERIT</code>. (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2928">#2928</a>)</li> <li>✨ Adds PyPy 3.12 support and updates PyPy 3.11 to v8.0.0, available with the <code>pypy</code> <a href="https://cibuildwheel.pypa.io/en/stable/options/#enable"><code>enable</code></a> flag (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2998">#2998</a>)</li> <li>✨ Adds GraalPy 3.13 (v25.3) support on Linux, Windows, and macOS arm64, available with the <code>graalpy</code> <a href="https://cibuildwheel.pypa.io/en/stable/options/#enable"><code>enable</code></a> flag (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2982">#2982</a>)</li> <li>✨ Adds <a href="https://cibuildwheel.pypa.io/en/stable/options/#log-fold-mode"><code>log-fold-mode</code></a> to override CI log folding, including <code>CIBW_LOG_FOLD_MODE=disabled</code> to keep build steps expanded (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2972">#2972</a>)</li> <li>✨ Adds a <code>python-path</code> input to the GitHub Action to choose the Python interpreter used to run cibuildwheel, and falls back to system <code>python3</code> on runner architectures unsupported by <code>setup-python</code>, such as native riscv64 (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2990">#2990</a>)</li> <li>🐛 Fixes Windows command execution when paths or arguments contain shell metacharacters, including dependency specifiers containing <code><</code> or <code>></code> (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2978">#2978</a>)</li> <li>🛠 Improves readability of logged commands whose arguments contain quotes (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2993">#2993</a>)</li> <li>🛠 Updates Pyodide to 0.27.8, 0.29.5, and 314.0.7, and updates its build tooling, including auditwheel-emscripten 0.3.0 (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2996">#2996</a>)</li> <li>🛠 Updates dependencies and container pins, including CPython 3.15.0rc3 (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2986">#2986</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/3003">#3003</a>)</li> <li>📚 Corrects references to <code>--archs</code> in CLI help, error messages, and documentation (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2992">#2992</a>)</li> </ul> <h3>v4.2.1</h3> <p><em>5 September 2026</em></p> <ul> <li>🐛 Respects the NuGet package sources configured on the machine when installing CPython on Windows, instead of always falling back to nuget.org (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2966">#2966</a>)</li> <li>🐛 Fixes a <code>NameError</code> on Pyodide when an already-compatible wheel was reused, which made the test step fail (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2968">#2968</a>)</li> <li>🛠 Updates the Android Python versions, and the Android testbed's Gradle version, making it compatible with Java 25 (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2962">#2962</a>)</li> <li>🛠 Updates dependencies including CPython 3.15.0rc2 (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2965">#2965</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/2970">#2970</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/2976">#2976</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/2981">#2981</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/2985">#2985</a>)</li> </ul> <h3>v4.2.0</h3> <p><em>4 August 2026</em></p> <ul> <li>🌟 CPython 3.15 wheels are now built by default - without the <code>"cpython-prerelease"</code> <a href="https://cibuildwheel.pypa.io/en/stable/options/#enable"><code>enable</code></a> set. It's time to build and upload these wheels to PyPI! This release includes CPython 3.15.0rc1, which is guaranteed to be ABI compatible with the final release. (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2944">#2944</a>)</li> <li>✨ Adds Pyodide 3.15 support with the <code>cp315-pyodide_wasm32</code> build identifier, using Pyodide 315.0.0a2. These are also stable wrt. the final release. (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2958">#2958</a>)</li> <li>🐛 Retries a failed download six times with exponential backoff, so short network outages no longer stop a build. A <code>4xx</code> response is still reported at once. (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2953">#2953</a>)</li> <li>🐛 Accepts <code>default</code> as a <a href="https://cibuildwheel.pypa.io/en/stable/options/#build-frontend"><code>build-frontend</code></a> value on Pyodide, and accepts <code>pyodide-build</code> in the top-level table and in overrides (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2951">#2951</a>)</li> <li>🛠 Holds pip back on GraalPy, where newer pip breaks the build (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2955">#2955</a>)</li> <li>🛠 Updates Pyodide to 314.0.4 (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2949">#2949</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/2952">#2952</a>)</li> <li>🛠 Updates dependencies and container pins (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2952">#2952</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/2960">#2960</a>)</li> <li>💼 Updates CI action pins (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2948">#2948</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/2954">#2954</a>)</li> <li>🧪 Uses pp311 for the abi3 test, and deletes <code>test_overridden_pip_constraint</code>, which is not necessary since <a href="https://redirect.github.com/pypa/cibuildwheel/issues/2583">#2583</a> (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2956">#2956</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/2957">#2957</a>)</li> </ul> <h3>v4.1.1</h3> <p><em>24 July 2026</em></p> <ul> <li>✨ Adds <code>pyodide-build</code> as a separate <a href="https://cibuildwheel.pypa.io/en/stable/options/#build-frontend"><code>build-frontend</code></a>, now the default frontend for Pyodide, with verbosity flags handling. Any other frontend is ignored with a warning on Pyodide. (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2609">#2609</a>, <a href="https://redirect.github.com/pypa/cibuildwheel/issues/2945">#2945</a>)</li> </ul> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/pypa/cibuildwheel/commit/adba99c781d3746d38b3a09b1cf797965bcb7fe6"><code>adba99c</code></a> Bump version: v4.3.0</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/8a0d481dd293145615f5df51d5e5e594d74199fa"><code>8a0d481</code></a> Add the ability to set 'inherit' at all levels of the options cascade (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2928">#2928</a>)</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/8bc038b3b7636c6cf860204afc20bd3d98661873"><code>8bc038b</code></a> chore(deps): bump astral-sh/setup-uv from 10.1.0 to 10.2.0 in the actions gro...</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/5cad3d982fd4fbcddade622709b995e3052923b1"><code>5cad3d9</code></a> [Bot] Update dependencies (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/3003">#3003</a>)</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/82bef7c1ddbc1b4f7cfa558b6dc347fa284a243c"><code>82bef7c</code></a> Make logged commands readable when they contain quotes (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2993">#2993</a>)</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/84f6233892f964b4c2aba196595e85602bc61b34"><code>84f6233</code></a> feat: add GraalPy 3.13 (25.3) (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2982">#2982</a>)</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/85ca3f62182ff85b1de2a37c8052ff0d91c84404"><code>85ca3f6</code></a> fix(ci): use GitHub's dedicated self-repository syntax (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/3002">#3002</a>)</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/ae4799ab957ab5fd566c0391808109e130bf15b2"><code>ae4799a</code></a> [Bot] Update dependencies (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2986">#2986</a>)</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/69adf525493be7c3f7640c5f6843653b0581ae2b"><code>69adf52</code></a> fix: don't run call() through cmd.exe on Windows (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2978">#2978</a>)</li> <li><a href="https://github.com/pypa/cibuildwheel/commit/ad9dc7ab4128aaf29be0b976b1290d1d2302ed60"><code>ad9dc7a</code></a> feat: add log fold mode override (<a href="https://redirect.github.com/pypa/cibuildwheel/issues/2972">#2972</a>)</li> <li>Additional commits viewable in <a href="https://github.com/pypa/cibuildwheel/compare/v4.2...v4.3">compare view</a></li> </ul> </details> <br /> [](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) </details> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
## Summary - release every source environment acquired by `merge_lmdb()` through the refcount-aware LMDB cache path - use `finally` so malformed metadata or copy failures also balance the merge's temporary reference - add a regression that checks both shared-reader usability and exact cache refcount symmetry ## Root cause and fix `_open_lmdb()` caches readonly environments by resolved path because python-lmdb does not permit independently opening the same path multiple times in one process. Every acquisition increments a cache refcount, and `_close_lmdb()` is the matching release operation. `merge_lmdb()` acquired each source through `_open_lmdb()`, but called `src_env.close()` directly. If a reader already shared that cached environment, the merge invalidated its live handle while the cache still retained it. A later reader could then receive the same closed object. The source loop now pairs `_open_lmdb(src_path)` with `_close_lmdb(src_path)` in `finally`. This releases only the reference owned by the merge; existing readers retain their references and environment. The `finally` scope covers metadata parsing, source/destination transactions, frame copying, and system-ID offset updates. ## Why existing tests missed this Existing merge tests opened readers only after the merge and did not keep a source reader alive across the operation. They therefore never exercised the cache-sharing condition that makes a direct `Environment.close()` unsafe. The new regression: 1. opens a source `LmdbDataReader` and records its cached environment/refcount; 2. merges that same source; 3. verifies the exact same environment remains cached with an unchanged refcount; 4. verifies the existing reader still reads; 5. opens a new reader, verifies the refcount increases by exactly one, and verifies it also reads. On the previous implementation, the existing reader fails deterministically with: `lmdb.Error: Attempt to operate on closed/deleted/dropped object.` Validation performed: - focused old behavior reproduction: deterministic closed-environment failure - fixed regression: passed - complete `TestMergeLmdbSystemIds` group: 4 passed - duplicate-source and malformed-metadata refcount scenarios independently checked during review - `ruff format --check .` - `ruff check .` - `git diff --check` Closes deepmodeling#5635. Coding agent: Codex Codex version: codex-cli 0.144.1 Model: gpt-5.6-sol Reasoning effort: xhigh <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Tests** * Added regression coverage for merging data sources while readers are active, verifying that existing and newly opened readers remain usable and resources are released during cleanup. This helps catch issues that could affect data loading reliability in these scenarios. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: njzjz-bot <njzjz-bot@users.noreply.github.com> Co-authored-by: njzjz-bot <njzjz.bot@gmail.com>
## Summary
Add grid-based charge-density prediction for the PyTorch backend.
- Add `DensityFittingNet`, `DPDensityAtomicModel`, and
`GridDensityModel`
- fitting type: `density`
- model type: `grid_density`
- Add `GridDensityLoss` for density labels defined on user-provided grid
points.
- Support frame-major `grid.npy` and `density.npy` data in training,
validation, and `dp test`.
- Add `DeepDensity` inference with `grid=` input, including large-grid
chunking and charge/spin conditioning.
- Add DPA-2 and DPA-3 density examples with a small QM9 charge-density
dataset.
- Add documentation for data layout, training, evaluation, fine-tuning
limitations, and model serialization.
## Data format
Each `set.*` directory contains:
- `grid.npy`: shape `(nframes, ngrid, 3)`
- `density.npy`: shape `(nframes, ngrid, 1)`
The final entry of `type_map` is reserved for the virtual grid-point
type. Grid and density point counts are validated consistently during
data loading.
## Scope and limitations
This PR currently supports the PyTorch/TorchScript Python workflow:
- training: `dp --pt train`
- evaluation: `dp --pt test`
- Python inference: `DeepEval` / `DeepDensity`
C++ and LAMMPS inference are not included because the required
dpmodel/backend wrappers have not yet been implemented.
Multi-backend support tracking: deepmodeling#6029
---------
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Yuzhi Liu <yuzhiliu@YuzhiLiudeMacBook-Pro.local>
…g#6119) ## Summary Change `dpa4-ultra-v20260911` from 10 layers to 8 by setting `descriptor.n_blocks` to 8. This is a one-line change; all other preset settings remain unchanged. ## Rationale A pretrained model of this size has never been released, so compatibility with a released 10-layer model does not need to be preserved. The 10-layer configuration is too large to train in practice, so reduce it to 8 layers. ## Validation - Compared all 24 composed presets before and after the change: only `dpa4-ultra-v20260911.descriptor.n_blocks` changes, from 10 to 8. - Python syntax check and Ruff lint/format passed for the edited source. - Full backend training/tests were not run for this one-line preset change. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Model Presets** * The DPA4 ultra preset now uses 8 descriptor blocks instead of 10. Other preset settings are unchanged. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
## Summary - Change only the macOS arm64 wheel runner from `macos-14` to `macos-15`. - GitHub's macOS 14 retirement brownout prevented the arm64 wheel job from starting in the merge queue. The image retires on November 2, 2026; see [the runner-images announcement](actions/runner-images#13518). - `macos-15` is a supported arm64 runner. Keep the Intel runner, Python versions, wheel platform identifiers, deployment-target configuration, and all other build/publishing logic unchanged. ## Validation - Parsed the workflow as YAML and verified that the runner label is the only structural change. - `git diff --check` passed; the remote commit contains exactly one changed line in one file. - `ruff check .` passed; `ruff format .` left all files unchanged. - No macOS runner is available locally; the actual arm64 wheel build still needs CI validation. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Chores** * The macOS ARM64 wheel build now runs on macOS 15 instead of macOS 14. This is a change to the package build environment; no end-user functionality changes are included in this update. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
…eepmodeling#6116) ## Summary This PR adds a latent-charge long-range module to pt_expt models with a DPA4C descriptor. A charge network reads the descriptor that the energy fitting reads and predicts per-atom latent charges, and every pair of atoms interacts through them: ```math E = \sum_i E_i^{\text{SR}} + k_e \sum_{i<j} \sum_{c=1}^{C} q_i^c q_j^c\, K(r_{ij}), ``` with the LES kernel erf(αr)/r (the default) or a sum of Gaussians (SOG). Non-periodic systems take the direct sum over the pairs of a frame. Periodic systems, with `periodic: true`, take the sum over the images of the cell in reciprocal space, by smooth particle-mesh Ewald (SPME) by default or over explicit wave numbers. An optional constraint shifts one channel so that it sums to the total charge of the frame (neutral, from `fparam` or from `charge_spin`). The documentation is `doc/model/long-range.md`. **Credit.** This PR supersedes deepmodeling#6031 by @YuzhiLiu-ai, which introduced the module (LES/SOG kernels, charge channels, the total-charge constraint, the complete energy in the atomic model, and the direct-sum operator in C++ and LAMMPS) for non-periodic systems. The first commit here is the rebuilt form of that work and carries a `Co-authored-by` trailer for @YuzhiLiu-ai. It is rebuilt on the interfaces that deepmodeling#6110 reserved for it, and it adds periodic systems and fine-tuning. The other two commits are the performance work that followed. ## What the module covers - **Configuration:** a `long_range` section (`type: latent_charge`) with the `les` or `sog` kernel, several charge channels, the total-charge constraint, and `periodic: true` with SPME or explicit wave numbers. Nothing existing is removed or renamed. - **One complete energy:** the atomic model owns the complete energy. Training, compiled training, DDP, `dp test`, output-bias statistics and change-bias, the Hessian and `linear_ener` compositions all see the long-range term. - **Fine-tuning:** a pretrained model without long range can be fine-tuned into one with it. The added module takes the input statistics of the fine-tuning data. - **Frozen models:** `.pt2` and `.pte`. The graph lower reads the pair list or the mesh of the cell as topologies after its inputs. Compressed DPA4C models frozen for a CUDA device evaluate the module in the compact canonical lower with `deepmd::latent_charge_sum`, which provides the direct sum, the SPME mesh, and the MPI exchange of the charges of a domain-decomposed system. - **C++ and LAMMPS:** `pair_style deepmd` and `deepmd/kk`, one or several ranks, periodic and non-periodic. A compressed model frozen for CUDA runs on several MPI ranks; every other model runs on one rank. - **Not supported with a long-range module:** multi-rank inference of a model that the dedicated operator does not evaluate (such as an uncompressed one), spin models, the tabulated ZBL potential, and short-range bridging. ## Commits 1. **feat(long-range): latent-charge long-range module for DPA4C.** The module: model, training, freezing, and the C, C++ and LAMMPS interfaces. 2. **perf(long-range): accelerate long-range DPA4C inference in LAMMPS.** - Periodic systems take part in the CUDA-graph replay of a single rank. The cell reaches the model through pinned memory that the operator reads on the device, so a replay evaluates the cell of its own call. The replay key holds the mesh size; after the size changes, the model runs eagerly for 64 calls before it captures again, so a barostat near a mesh boundary does not recapture at every crossing. - A module whose single-channel charge network the fused fitting kernels reproduce (the defaults give one) is evaluated by one fused operator, `dpa4c_canonical_compress_long_range_energy_force`. It runs one descriptor pass, the charge network, the long-range sum, the energy fitting with the charge-network backward, one descriptor backward with fixed-point force assembly, and the epilogue. - The archive records whether its compact lower reads the source CSR (`canonical_requires_source_csr`). LAMMPS then builds the source CSR for such a model only at steps that request the per-atom virial. 3. **perf(long-range): fuse the charge network and harden the LAMMPS path.** - The charge network has a fitting-route table of its own, which the freeze measures like that of the energy fitting. - The two fused DPA4C energy-force operators share the plan of the fitting runs and the epilogue. The outputs of models without a long-range module are unchanged. - `pair_style deepmd` rejects at init a model-deviation ensemble on a non-periodic system whose first model carries no module. `deepmd/kk` shifts positions to the box origin only for a model with a module. - New Kokkos LAMMPS regression: `source/lmp/tests/test_lammps_dpa4c_long_range_kokkos.py`, run by `test_lammps_kokkos.sh`. ## Measured performance LAMMPS with Kokkos on an RTX PRO 6000 Blackwell (compute capability 12.0), trained Air model with an LES or SOG module. Times are ms per step, before and after the second commit: | System | 512 atoms | 10,296 atoms | | --- | --- | --- | | periodic, LES | 0.665 → 0.280 | 1.469 → 1.242 | | periodic, SOG | 0.644 → 0.277 | 1.357 → 1.137 | | cluster, LES | 0.343 → 0.264 | 1.274 → 1.166 | | cluster, SOG | 0.353 → 0.263 | 1.479 → 1.302 | At 100,800 atoms (1000-step runs on two GPUs), periodic LES goes from 11.3–11.4 to 10.1–10.4 ms and periodic SOG from 9.8–10.0 to 8.9–9.0 ms. The third commit then shortens the charge-network kernels from 47 to 39 µs per step at 10,296 atoms and from 477–493 to 429 µs at 100,800 atoms. A periodic LES system whose cell is deformed at every step replays in 0.28–0.29 ms per step, as with a constant cell, against 0.35–0.38 ms evaluated eagerly. Replayed and eager trajectories agree bit for bit over 200 steps of NVE and NPT. Short-range models keep their kernel time. The commit messages give the full conditions. ## Interfaces and compatibility - **C API:** `DP_DPA4ComputeCanonicalGraphGPU` takes `const double* box`, the cell of a periodic system, right after `world`. `d_coord`, `world`, `DP_DeepPotHasLongRange` and `DP_DeepPotModelDeviHasLongRange` are the interfaces that deepmodeling#6110 reserved, now used. - API version 31 and the version-2 backend plugin interface were introduced by deepmodeling#6110 after v3.2.0 and are not in a release yet, so this PR extends them within the same version. - **Operators:** the new operators are `latent_charge_sum` and `dpa4c_canonical_compress_long_range_energy_force`. The schemas of the existing operators are unchanged. - **Frozen models:** only a model that declares long-range topologies traces the extra canonical inputs (positions, communicator, cell), as read from the export code. Archives of models without a module, including those frozen with deepmodeling#6110, keep their inputs. ## Validation on this branch The branch is based on master 4c3a598 and holds three commits cherry-picked from the development branch. - pre-commit over the whole range: all hooks passed. - Rebasing onto the merged deepmodeling#6110 needed two adjustments, both checked: - The long-range wrapper now takes the fitting-route tables from the energy model, following the structure deepmodeling#6110 adopted in review. A trace check confirmed that both measured tables reach the exported program. - The linear-composition test stub `_RecordingAtomicModel` gained `has_long_range()`. Its two `TestChangeTypeMap` tests failed before this and pass after it (7 passed). - On the development branch, which holds these commits plus unrelated later ones: `source/tests/pt_expt/model/test_long_range.py`, 126 passed on an RTX PRO 6000 Blackwell (PyTorch 2.13.0+cu130). - The other suites, the C++ tests and the Kokkos LAMMPS tests were not rerun for this branch and are left to CI, including the `Test CUDA` jobs. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Added latent-charge long-range energy modeling for non-periodic and periodic systems, with configurable interaction kernels and charge constraints. * Added latent-charge fitting and support for long-range evaluation in supported graph, C++, CUDA, and LAMMPS workflows. * Added fine-tuning, export, and inference support for long-range models in the PyTorch experimental backend. * **Bug Fixes** * Improved compatibility when loading older DPA4C model state dictionaries. * Added fitting-network width 64 to optimized routing support. * Improved force and virial handling for long-range graph evaluations. * **Documentation** * Added guidance on long-range configuration, supported workflows, and limitations. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
## Summary - Remove the virtual-atom DeepSpin implementation for DPA4/SeZM in the PyTorch backend, including the dedicated model, serialization route, coordinate/virial corrections, compile branches, PT2 nlist export path, example, and obsolete tests. - Enforce backbone compatibility at the `SpinModel` construction boundary in each PyTorch backend. One recursive check covers factory construction, direct wrappers, nested/hybrid backbones, and deserialization; factories do not duplicate it, and forward execution does not scan modules. - The explicit DPA4/SeZM entry point in `pt_expt` already required native spin. Its changes close generic-wrapper composition paths that bypassed that restriction; there is no separate `pt_expt` DPA4 DeepSpin implementation being deleted. - Keep native spin and other descriptors' spin implementations intact. Update the public documentation and configuration guidance without compatibility shims or historical notes in the implementation. DPA4/SeZM spin configurations must explicitly set `model.spin.scheme: native`. The shared default for other descriptors is unchanged. ## Validation CPU, Python 3.12, PyTorch 2.11.0; imports were verified against this worktree (using the installed native libraries). - Constructor-boundary regression selection (PT/PT_EXPT spin contracts, generic spin, optimizer interoperability, bridging, and DPA4 aliases): **177 passed**, **8 subtests passed**. - PT SeZM export suite: **28 passed, 1 skipped**. - Native-spin eager/finite-difference/equivariance/serialization/loss selection: **10 passed**. - Native-spin compiled/eager parity: **1 passed**. - Compile-cache slot and virial selection: **4 passed**. - Property/virial selection: **6 passed**. - Vacuum-reference suite: **9 passed, 1 skipped**. - Configuration examples and bridging selection: **30 passed**, **297 subtests passed**. - Repository-wide `ruff check .`, `ruff format --check .`, and `git diff --check`: passed. CUDA/GPU tests and the full multi-backend suite were not run. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Behavior Changes** * DPA4/SeZM spin configurations now require the native scheme; missing or unsupported schemes are rejected. * DeepSpin virtual-atom spin models for DPA4/SeZM are no longer supported, and the DPA4 DeepSpin example has been removed. * Frozen DPA4/SeZM models use the edge-based interface. Graph inference supports native spin and other eligible features. * Standard spin-model wrappers cannot be used with DPA4/SeZM descriptors; use the native spin model instead. * **Documentation** * Updated DPA4 and spin guidance on supported schemes, inference, and neighbor-list behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Reject nonpositive or oversized tabulation widths on the host before launching TensorFlow/PyTorch GPU kernels. Apply the launch-width guard to forward, first-gradient, and second-gradient wrappers. SE-T-TEBD uses fixed-size blocks and only requires a positive width. The regression tests explicitly keep PyTorch table metadata on the CPU and disable TensorFlow constant folding so they exercise the GPU-only validation. Validation: - Fresh TensorFlow/PyTorch CPU and CUDA native builds. - Slurm GPU run on node n2: 7 tests and 36 subtests passed, including SE-T-TEBD forward and gradients at width 1025. - CPU fallback tests, Ruff, formatting, whitespace checks, and commit hooks passed. Coding agent: Codex Codex version: codex-cli 0.164.0 Model: gpt-6-astra Reasoning effort: xhigh <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * GPU tabulation operations now reject invalid widths before processing: standard operations require widths from 1 to 1024. * SE-T-TEBD operations reject zero or negative widths while continuing to allow widths above 1024. * Consistent validation is applied to forward, gradient, and second-gradient operations in TensorFlow and PyTorch. CPU behavior is unchanged. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: njzjz-bot <njzjz-bot@users.noreply.github.com>
Fixes deepmodeling#5623 ## Summary - derive per-atom descriptor and neighbor widths through a shared checked helper instead of truncating integer division - reject partial atom rows, negative local-atom counts, and widths beyond the native kernel integer range - enforce the `se_a` four-value descriptor stride and the `se_r` one-value stride before output allocation - apply the checks to force, force-gradient, and virial-gradient CPU/GPU dispatch paths - add focused malformed-input tests for `net_deriv`, `in_deriv`, `nlist`, `rij`, and descriptor/neighbor stride mismatches ## Why existing tests missed this The existing tests use placeholders whose second dimensions are fixed to the correct `nloc * ndescrpt`, `nloc * ndescrpt * 3`, and `nloc * nnei` widths. Feeding a differently sized array is therefore rejected by TensorFlow before the custom op executes. The tests also cover only valid descriptor layouts, so the release-build paths where `assert` is compiled out were never exercised. The new tests construct malformed tensors directly at the op boundary. They verify `InvalidArgument` is returned by the custom op before output allocation or raw CPU/GPU pointer dispatch. ## Validation - CUDA TensorFlow op build: `cmake --build source/build --target deepmd_op` - isolated editable TensorFlow build with current `libdeepmd_op` and `libop_grads` - `pytest source/tests/tf/test_multi_device_shape_validation.py -v` (6 validation cases plus TensorFlow `test_session`, all passed) - existing happy paths: `TestProdForce::test_prod_force`, `TestProdForceGrad::test_prod_force_grad`, and `TestProdVirialGrad::test_prod_virial_grad` (3 passed) - `ruff format .` - `ruff check .` - clang-format check on changed C++ files Coding agent: Codex Codex version: codex-cli 0.144.4 Model: gpt-5.6-sol Reasoning effort: xhigh <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Force and virial operations now reject invalid flattened tensor dimensions, including non-divisible widths, inconsistent descriptor and neighbor sizes, and cases where the total atom count is smaller than the local atom count. * Improved handling of zero-width and oversized per-atom feature dimensions, with clearer errors for invalid inputs. * GPU operations now handle empty workloads without launching unnecessary computations and preserve correct zero-valued outputs. * **Tests** * Added regression coverage for malformed shapes and zero-work force and virial operations. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: njzjz-bot <njzjz-bot@users.noreply.github.com>
Closes deepmodeling#5686. ## Summary - freeze Paddle DPA3 parameters with Paddle's `stop_gradient` flag instead of assigning a PyTorch-style `requires_grad` attribute; - centralize descriptor-level trainability in `_apply_trainable()`; - reapply the setting after deserialization replaces type, charge/spin, MLP, edge/angle, and RepFlow child layers; - add a regression covering both direct construction and serialize/deserialize round-trip with charge/spin embeddings enabled. ## Root cause Paddle's autograd contract is `parameter.stop_gradient`. On the project's minimum supported Paddle 3.0.0, assigning `parameter.requires_grad` merely adds an unrelated Python attribute and leaves `stop_gradient=False`, so optimizers can still update a descriptor configured with `trainable=False`. Construction was not the only affected path. `DescrptDPA3.deserialize()` constructs a descriptor and then replaces several registered child layers with freshly deserialized parameters. The descriptor-level freeze therefore needs to run again after all replacements are complete. ## Why existing tests missed this Existing DPA3 consistency tests compare numerical outputs and serialization behavior, but do not inspect Paddle autograd flags. A model can produce identical inference values while its supposedly frozen parameters remain trainable. The regression temporarily masks newer Paddle's `requires_grad` compatibility alias, retaining the minimum-version semantics even in nightly CI. It then requires every named parameter to have `stop_gradient=True` both immediately after construction and after a round-trip. Enabling `add_chg_spin_ebd=True` ensures the optional replacement paths are included. ## Old-fail / new-pass validation - original implementation, Paddle 3.0.0: failed with 17 parameters still requiring gradients; - original implementation, Paddle `3.4.0.dev20260310`: failed with the same 17 parameters under the minimum-version compatibility seam; - constructor-only intermediate fix, Paddle 3.0.0: construction passed but round-trip failed with 22 unfrozen parameters; - constructor-only intermediate fix, Paddle `3.4.0.dev20260310`: round-trip failed with 28 unfrozen parameters; - complete fix, Paddle 3.0.0: regression passed, including both subtests; - complete fix, Paddle `3.4.0.dev20260310`: regression plus existing DPA3 consistency test passed (`2 passed`). Additional checks: - `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 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Fixed non-trainable DPA3 descriptor parameters becoming trainable after deserialization or type-map updates. * Ensured non-trainable settings consistently prevent gradient updates during initialization, model loading, and descriptor updates. * Preserved non-trainable behavior for charge, spin, and mixing embeddings. * Prevented parameter sharing between descriptors with incompatible trainability settings. * **Tests** * Added coverage for parameter gradient settings during initialization, serialization/deserialization, type-map changes, and parameter sharing. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: njzjz-bot <njzjz-bot@users.noreply.github.com>
## Summary Split Python CUDA tests into three independent GPU jobs, with directory-based, mutually exclusive coverage: - `pt_expt-model`: `source/tests/pt_expt/model` - `pt_expt-other`: `source/tests/pt_expt`, excluding `model` - `other`: `source/tests`, excluding `pt_expt` All retain the existing Paddle exclusion, CUDA/dependency installation, FP64 check, environment variables, and timeout. Run the C++ main chain and Kokkos on separate GPU runners using a second matrix with shared setup. The main chain retains model conversion/generation, CTest, ordinary LAMMPS, and i-PI. Kokkos independently builds its C API/backend installation and matching LAMMPS source, generates the required long-range models, and runs the original native-spin and long-range Kokkos regressions. Both retain the MPI and default CUDA dtype checks. `test_cc_local.sh` gains `--build-only` and `--models-only=kokkos`. Build-only installs the custom operator before exiting. Kokkos-only generation requires CUDA, PyTorch, the installed C API, and the matching custom operator; it cleans only its own fixtures. The no-argument behavior still builds, generates all models, and runs CTest. Both matrices disable fail-fast. The existing aggregate gate requires all five GPU jobs when CUDA testing is requested and preserves intentional skips otherwise. ## Validation - 31 focused tests passed: 13 new shell-orchestration regressions and 18 existing CI-splitting tests. The new tests execute the shell script with mocked compiler/model-generation commands and a real custom-operator file copy. They do not compile CUDA. - The new tests against the previous script produced 9 expected failures and 4 passes. - Default-mode command traces match the previous script for CUDA/CPU/ROCm, each with PyTorch enabled and disabled. - Pytest path-discovery comparison: **649 test files = 39 + 85 + 525**, with no omissions or duplicates, including the new regression file. This is file-level discovery without backend imports, not complete parametrized GPU-node collection. - Structural checks confirm unchanged Python setup, shared C++ checks, the projected main C++ chain, Kokkos test commands/required guards, and aggregate conditions. All 32 aggregate success/failure/skip/cancel combinations passed against the actual alls-green implementation. - Actionlint 1.7.12 (existing `gpu` label configured; shellcheck disabled), Bash syntax, shfmt, repository-pinned Prettier, full Ruff/format, scoped isort, and whitespace checks passed. The prior two-Python-shard revision completed CUDA successfully in about 3h50m. **The new three-shard plus independent-Kokkos layout still requires its own GPU run.** No new-layout speedup is claimed; wall time depends on GPU runner concurrency and duplicated preparation cost. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **CI** * CUDA Python tests run across three shards, while C++ tests run in separate main and Kokkos suites. * CUDA runs require the applicable Python and C++ jobs to complete; jobs may be skipped when CUDA testing is not requested. * **Testing** * Local test workflows now support build-only and Kokkos-only model-generation modes, with checks for required configuration and build artifacts. * Added coverage for local workflow modes, argument validation, fixture handling, and error reporting. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
for more information, see https://pre-commit.ci
macqueen09
force-pushed
the
perf/ecs-inference-backward-20261019
branch
from
November 4, 2026 16:31
6701a48 to
17819db
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Submitted by Hunan University.
Revision measured:
98a65e46d0076319f2fcb49ded77e6a93ecab6beintegrated with upstream4e1479d8. Matrix: 27 processes, 23 completed, 4 OOM (Neo4096 TORCH and Pro4096 in all three arms).Measured Neo results
N1000 passes against both Torch and BASE. At N4096, energy/forces/stress pass against BASE but virial does not; BASE and ECS also fail their respective repeated-run virial check. Torch N4096 runs out of memory.
Summary
Adds an opt-in, default-off SO(2) edge-cohort backward for frozen DPA4-Neo inference. Set
DP_SO2_EDGE_COHORT_INFER=1withDP_TRITON_INFER=2andDP_COMPILE_INFER=1to enable it. Unsupported layouts and protected gradient paths retain the existing implementation.Why it saves scratch memory
The native path advances each backward layer across the full edge set. This path completes the backward layers for a cohort of at most 8192 edges before advancing to the next cohort. The temporary
g,gz, andsigbuffers are reused across cohorts; saved activations and the returned input gradient still span all edges. This is an edge count, not an atom count. It reuses the native GEMM arithmetic and column parallelism, with separate full-graph and scratch strides for partial cohorts. Only owned scratch is overwritten; caller inputs are not mutated.Small runtime-dispatch correction
The latest revision changes two files (35 insertions / 5 deletions): the public backward dispatcher always enters the opaque runtime operator, and a regression test traces 37 edges and then compiles/runs 37, 8193, and 16385 edges. This prevents a small
make_fx/AOT example from fixing the large-input dispatch to the single-cohort trace. It does not change the numerical kernels. The complete feature diff remains two implementation files and one test file; no local benchmark data or experiment documents are included.Validation setup
Baseline: upstream
4e1479d8a23fcc1c9baf36004d5685898ad421a8. The feature branch retains its original base; results below use its clean local integration into that upstream commit. RTX 5090; PyTorch 2.11.0+cu128; Triton 3.6.0; FP32 with TF32 and AMP disabled; expandable CUDA allocator segments; one CPU intra/inter-op thread.TORCH = compiled PyTorch without native inference kernels; BASE = upstream native Triton inference; ECS = the updated feature enabled on the same upstream base. Each case uses the same checkpoint, device, and three deterministically perturbed diamond-carbon frames. There is one fresh process per implementation/case, three evaluations per frame for accuracy, eight timing warmups, and 30 synchronized wall-time samples. Timing includes the ASE energy/forces/stress evaluation, not just the SO(2) kernel. These are screening medians, not confidence intervals. Neo runs on GPU 0; Nano/Mini on GPU 1; Pro on GPU 0.
Checkpoints and actual dispatch
13edeea63448c0f8a0b38e08fd8ba196fb1e2fad5f12486b1cd23320829da268ded047546c2b44a50e2c850680d77279e2bf3e107c10f1c2fe39a5c344e693f68d8b2b02b9575cb9e0af420cc1e8b1d9ffcbc04752c2203d29f48ccd0cd5f07d446a6e893101fc52190cfccabb9d2328863d651aca36981fd8d3401c71a61221Pro's checkpoint metadata uses an older fitting-type alias; the same local load-only compatibility mapping is applied in every arm. Neo's supported narrow layout is the optimization target; Nano, Mini, and Pro are compatibility/fallback checks, not claims of ECS acceleration.
End-to-end latency
Negative change means lower latency. Compare BASE and ECS for incremental PR benefit; Torch is an additional reference.
Peak GPU memory
Decimal GB (10^9 bytes). Full-window allocated includes the first inference/compile window and timed evaluations. Steady allocated resets the peak after warmup. Reserved measures allocator-held capacity, not live tensors. Caches are shared per model, in TORCH → BASE → ECS order: cold compilation/autotuning can affect full-window peaks, so fallback-model first-window differences are not ECS savings. Use the steady allocated comparison to isolate runtime capacity. OOM runs have no valid steady timing or acceptance comparison.
Numerical consistency
Unchanged acceptance rule: every element must satisfy
abs(candidate-reference) <= 1e-5 + 1e-4*abs(reference). The table reports the worst error/tolerance ratio across energy, forces, virial, stress and all same-frame repeat pairs; ≤1 passes. Self-comparisons expose native reduction variability. These test implementation agreement, not physical accuracy against DFT. N1000 is the primary Neo accuracy case; N4096 is also reported without suppressing failures.Per-output absolute and relative errors
Relative error uses denominator
max(abs(reference), 1e-8)and is descriptive, not the acceptance criterion. Energy/virial: eV; force: eV/Å; stress: eV/ų.Regression coverage
Run the focused suite with the project's PyTorch/CUDA test environment:
The feature remains default-off and this PR remains Draft. Standalone AOTInductor/C++ deployment is not validated by the online-Python inference tests above. Multi-model failures/OOM and small-input overhead are reported rather than counted as improvements.
Reproducing the model comparison
Use a CUDA build of this revision and the same checkpoint. Run each arm in a fresh process, setting
DP_COMPILE_INFER=1,DP_CUDA_INFER=0,DP_TF32_INFER=0,DP_AMP_INFER=0,DP_INTRA_OP_PARALLELISM_THREADS=1,DP_INTER_OP_PARALLELISM_THREADS=1, andPYTORCH_ALLOC_CONF=expandable_segments:Truebefore importing DeePMD. SetDP_TRITON_INFER=0for TORCH, or2for BASE/ECS; only ECS setsDP_SO2_EDGE_COHORT_INFER=1.Collect three repeats of all three frames for each arm; compare corresponding frames with the tolerance above. For timing, warm up eight evaluations, synchronize CUDA, then time 30 evaluations with synchronization after each. Record
torch.cuda.max_memory_allocated()andmax_memory_reserved()from before the first evaluation; separately reset peak statistics after warmup and replay 30 evaluations for steady peaks. Raw measurements and checkpoint hashes are retained locally; the tables above are the review evidence, not additional repository files.