Skip to content

feat(dpa4): add DPA4.5 models, merge-aware training and graph deployment - #6163

Queued
OutisLi wants to merge 33 commits into
deepmodeling:masterfrom
OutisLi:pr/dpa4.5
Queued

OutisLi wants to merge 33 commits into
deepmodeling:masterfrom
OutisLi:pr/dpa4.5

Conversation

@OutisLi

@OutisLi OutisLi commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Introduce DPA4.5 presets for PT-expt and JAX. Models can set a cutoff and mixing depth per block, normalize the density against measured training neighborhoods, and use inversion-equivariant readouts. Existing DPA4 presets keep their defaults.

  • Add merge-aware mixture-of-experts training and initialization from a compatible dense model. A selected task and composition can be merged for deployment.
  • Support DPA4 training and graph inference in JAX, including forces, virials and native-spin magnetic forces. Extend isolated-atom references to carry the conditions under which their energies were computed.
  • Add compact canonical graph deployment for eligible DPA4 models. Existing canonical archives need to be frozen again; this is an export format change, not a request to retrain.
  • Let the LAMMPS deepmd/kk, dpa4spin and dpa4spin/kk pair styles accept model ensembles, as deepmd and deepspin already do. The first model drives the dynamics. The others are evaluated on deviation-output steps, using the existing output and unit conventions.
  • Add DPA4C v20261111 presets with a measured neighborhood density floor and isolated-atom references.

Validation

Targeted CPU tests covered preset expansion, dense-to-MoE initialization, task-local compiled outputs, per-block cutoff parity and JAX JIT values and gradients. The full CUDA matrix is checked separately.

Train and evaluate DPA4 in the JAX backend on the portable implementation.

Model. Energies, conservative forces and virials, and native-spin magnetic
forces are differentiated on fixed-capacity, frame-segmented neighbor
graphs. The backend covers analytical bridging, including the contact clamp
of the learned part, DPA4 fitting with case conditioning, invariant
properties and LoRA adapters. PyTorch DPA4 model records convert to JAX
models and back, including the bridging truncation and contact clamp, and
frozen StableHLO models keep every neighbor inside the cutoff, as the
descriptor requires.

Training. HybridMuon, Adam and AdamW, gradient clipping with a non-finite
guard, EMA and full validation, multi-task training with shared descriptors
and fittings, and single-host data-parallel training with per-device loss
normalization and optional optimizer-state sharding; a model on a dense
neighbor list trains on one device. Training batches are built as compact
graphs before device transfer, and the contacts of each batch are recorded
in the contact clamps of a bridged model before the step reads the data
edges. Checkpoints hold the model, optimizer and EMA states and the training
data progress, so a restart continues the uninterrupted trajectory.

Shared code. LMDB sampling, the pair-clearance frame filter, inference
precision policies, EMA naming, multi-task case-embedding configuration and
the PyTorch SeZM record normalization move to portable modules used by the
JAX and PyTorch Exportable backends. Matrix products of the portable DPA4
code pass through one helper that applies the JAX precision policy. The JAX
automatic batch size accepts an atom ceiling that bounds the compiled shapes
during repeated evaluation. Inference reads a checkpoint without converting
its optimizer state.
LAMMPS develop removes Modify::find_compute(), Modify::find_fix() and
the public lists nfix, fix and compute (lammps/lammps 355cc8f40f, after
the 30 Sep 2026 feature release), so the plugin no longer compiles
against it: pair_base.cpp and compute_deepmd_fparam_dedn.cpp resolved
the fparam and aparam sources, the TTM fix and the derivative source by
index.

Both files now resolve an ID through deepmd_compute_by_id() and
deepmd_fix_by_id() of modify_lookup.h, which call
Modify::get_compute_by_id() and Modify::get_fix_by_id() from LAMMPS
7 Jan 2022 on and keep the index lookups for older versions, so the
supported range from 8 Apr 2021 is unchanged. A pointer lookup has no
separate invalid-entry case, so a missing compute reports only the
existing "is not found" error.

Tests: the plugin builds against LAMMPS develop (e42e0bb7fc); both
branches of modify_lookup.h compile against the 4 Jul 2026 headers.
The fparam/aparam lookup cases of test_lammps_faparam.py and
test_lammps_fparam_from_fix_dedn.py pass on LAMMPS develop when run
with the PyTorch copy fparam_aparam.pth of their TensorFlow model.
DPA4.5 is DPA4 with options that bound the response of the model away
from the training data and reallocate its capacity. Every option
defaults to the behavior of DPA4, so DPA4 inputs and checkpoints load
and train unchanged. The options belong to the portable implementation,
which the JAX and PyTorch Exportable backends run; the PyTorch
descriptor accepts them at their defaults, so that normalized inputs and
portable records of plain DPA4 models load, and raises for any other
value.

Options.
- density_floor sets the floor of every neighborhood normalization and
  the initial null mass of the attention in units of the mean envelope
  mass of the training neighborhoods. Training measures that mass at
  every block cutoff on the neighbor graph the descriptor reads, with a
  k-d tree over the periodic images whose cost is linear in the atom
  count, and stores it with the model; fine-tuning and restarts keep the
  stored value.
- readout_norm places an equivariant RMS normalization between the last
  block and the read-out. It is written with masks over the whole degree
  axis, so its result does not depend on the memory layout of its input.
- parity makes the model O(3)-equivariant: features keep their natural
  parity, the SO(2) maps share one weight between the two signs of an
  order, and the grid and Cartesian products keep the inversion-even
  paths. Native spin always uses it. LoRA adapters fold into the shared
  order weights.
- readout_kmax sets the Wigner-D frame order of the SO(3) read-out grid.
- rcut and mixing_layers take one value per block, and l_schedule may
  rise after a block. Each block reads the edge set and envelope of its
  own cutoff, compacted from the graph where that cutoff is smaller than
  the largest one; the structure key of compiled training includes the
  block cutoffs, and the inner potential of a bridged model uses the
  smallest cutoff.

Presets. dpa4.5-<size>-v20261111 for nano, mini, neo, air, plus, pro and
max set parity, density_floor 8, readout_norm, kmax 0 and
message_node_so3 off on top of the v20260911 options, with one cutoff of
6 A. Every layout above nano carries wider atom features than messages
(focus_dim below channels), and all of them run cheaper early blocks
before the last one. The family conditions its descriptor on the charge
and spin multiplicity of a frame, so its presets carry the embedding and
the neutral singlet as the state of a frame whose data gives none; the
other families leave the pair to the input.

Kernels and freezing. The fused CUDA and Triton paths read the parity
layout of the SO(2) weights and launch the half-width |m| = 1 blocks;
grid_pair takes a coefficient permutation with the even degrees first.
The profitability check of the fused SO(2) convolution counts one shared
block per order for parity weights. The Triton tile tables gain parity
families, and the fp16x3 launch sweep resolves its configurations per
weight layout. dp --pt-expt freeze of DPA4 defaults to
DP_CUDA_INFER=2.

Compilation. Three constraints of the PyTorch compilers shape the
implementation.
- AOTInductor cannot print the bound of a nested data-dependent edge
  count, which is what per-block cutoffs would ask of it, so every
  smaller cutoff compacts the edges of the graph cache directly.
- The CPU code that Inductor generates for compiled evaluation corrupts
  memory when the masked read-out normalization reads its scalar row
  through a slice of the degree axis, so it reads the row through the
  mask.
- The Triton sort lowering bounds a data-dependent count by an int16
  check, so stable sorts lower to the native ATen fallback; the patch is
  skipped where the fallback is missing.

Training and documentation. The HybridMuon arguments list the PyTorch
Exportable backend, which trains with it. The user guide documents the
DPA4.5 presets and the recommended optimizer setting, and
examples/water/dpa4/input_dpa45.json trains the nano preset with ZBL
bridging.

Tests: dpmodel and pt_expt consistency of every option alone and with
parity, rotation and inversion invariance, serialization round trips,
per-block cutoff graphs and freezing, the envelope mass against the
dense neighbor graph (including cells smaller than the cutoff), the
O(3) fused kernels against the reference, compiled force-loss gradients
of the DPA4.5 options, JAX energies, forces, virials and parameter
gradients against pt_expt with every option, the measured envelope mass
in JAX training and checkpoints, the pt refusal of every option, input
validation, and the preset catalog.
…very pair style

A single-precision DPA4 or DPA4.5 model frozen by `dp --pt-expt freeze`
on a CUDA device now exports the compact canonical lower of the
compressed DPA4C, so `pair_style deepmd/kk` serves the energy model and
`pair_style dpa4spin/kk` the native-spin model on one GPU or several,
ZBL-bridged models included. The graph lower of a native-spin model
carries its halo exchange in its main program, so `pair_style dpa4spin`
serves every native-spin model on one MPI rank or several. The five
LAMMPS pair styles write the model deviation of an ensemble through one
shared component.

One canonical lower. The lower kinds `dpa1_canonical` and
`dpa4c_canonical` become one kind, `dpa_canonical`, with one positional
schema. The metadata field `canonical_evaluator` names what evaluates a
model on the compact graph: the fused operators of a compressed DPA4C
(`dpa4c`) or DPA1 (`dpa1`), or the graph forward of the model itself
(`graph`). The graph forward serves a graph-lower energy or native-spin
model on CUDA whose atomic model reports `supports_canonical_graph`: a
DPA4 descriptor computing in float32, the inner pair potential, and a
linear model whose children all do, each without a model-level pair
exclusion, which the compact graph does not carry. Models with frame or
atomic parameters or a long-range module keep their lowers. Readers do
not branch on the evaluator; the exporter records what they must
provide as `canonical_requires_source_csr` (the graph forward, and a
DPA4C with a long-range module) and `canonical_requires_reciprocal`
(the fused operator of a multi-block DPA4C), which DeepPotPTExpt,
NativeSpinPTExpt and DeepEval read. `dp --pt-expt freeze` resolves the
lower of a graph-family `.pt2` automatically. Older canonical archives
must be frozen again.

Graph view and halo exchange. `neighbor_graph_from_canonical` presents
the compact graph to the graph forward as a destination-sorted
NeighborGraph without copying edge data. The storage guards past the
physical edges get masked endpoints spread round robin over the nodes:
DPA4's segmented operators sort every slot into its destination
segment, and guards on one node made one giant segment (Nano, 512
atoms, `deepmd/kk`: 10.6 to 3.45 ms/step). Further message-passing
blocks refresh their ghost rows through a `BorderPlan`, which drives
`deepmd::border_exchange`, with a registered backward for the reverse
communication of the gradients; device rows travel through MPI directly
when it reads device memory and through pinned host buffers otherwise.
Every operator library carries the exchange, and one built without CUDA
registers its host kernels alone. The Kokkos styles build the plan from
the swaps of the KOKKOS communication.

Native spin on the graph lower. The graph lower of a native-spin model
takes the same plan as its last three inputs, after `charge_spin`, when
its descriptor has further message-passing blocks, and runs the
exchange in its main program: a native-spin archive holds one program
for one rank or several and no with-comm artifact. NativeSpinPTExpt
builds the plan of the host styles from the swaps of the LAMMPS
neighbor list and passes an empty plan for a frame held whole; DeepEval
passes the single-domain plan. A multi-block DPA4C refreshes its ghost
rows from the same plan.

Native spin in one backward. `edge_energy_deriv` takes the gradient
with respect to the moment in the same `autograd.grad` as the force and
the virial. The separate backward repeated most of the reverse pass of
the descriptor (BCN diamond, ms/step, pt `deepspin` / `dpa4spin/kk`
before / after):
- nano, 512 atoms: 6.28 / 6.01 / 4.04
- mini, 512 atoms: 7.46 / 9.18 / 6.21
- nano, 10,296 atoms: 74.97 / 86.23 / 56.38
- mini, 10,296 atoms: 103.79 / 142.44 / 92.39

Kokkos producer. The compact graph reserves 1/256 of the edges plus 64
slots past the edge count when its storage grows, against 2% before:
every guard is edge work for the graph forward, and the 2% reserve cost
the frozen Neo and Nano programs 1.35% and 2.61% on a 10,296-atom
frame, against -0.07% and 0.39% now.

Pair styles. DeepSpin selects its backend from the `spin_scheme` of
the archive: every native-spin archive goes to NativeSpinPTExpt, and
DeepSpinPTExpt serves virtual-atom spin models and the edge-vector
`.pt2` of the pt backend, rejecting a native-spin graph archive at
`init`; its native-spin graph route is removed. `dpa4spin` therefore
runs on one MPI rank or several on either lower, the graph lower of a
model frozen in double precision or for a CPU included, and
`dpa4spin/kk` on the compact canonical lower. `dpa4spin` passes no frame
or atomic parameters, so a model that needs them runs with `deepspin`,
which serves both spin schemes; the error for a virtual-atom model names
it.

Model deviation. `ModelDeviation` (source/lmp/model_deviation.{h,cpp})
parses the options, stores the outputs and writes the file for
`deepmd`, `deepspin`, `dpa4spin`, `deepmd/kk` and `dpa4spin/kk`; the
host styles no longer use DeepPotModelDevi and DeepSpinModelDevi.
- The first model is the model of the pair style, held once, and drives
  the dynamics at every step with the age of the neighbor list. The
  further models are evaluated only at the steps that write the
  deviation and receive the age of the list only when no neighbor build
  has happened since they last evaluated: the count of builds, which
  every run restarts, identifies the list they hold. Before, the first
  model was loaded twice and every switch between its two instances
  rebuilt the cached topology.
- The outputs form one row per local and ghost atom, the layout of the
  reverse communication, which folds the rows of the ghost atoms onto
  their owners; the Kokkos styles fold them, and the centroid per-atom
  virial, through a rows mode of `CompactCanonicalGhostFold`, which
  replaces their separate virial buffer.
- The Kokkos styles evaluate the further models on the graph of the
  first one, into the same device buffers, after its outputs are
  consumed; their models share the cutoff and, for `deepmd/kk`, the
  input schema and the long-range module. The source CSR and the halo
  exchange are prepared when any model reads them and handed only to
  the models that do.
- The models share the type map and the frame and atomic parameter
  dimensions of the first one; the neighbor list of a host style covers
  the largest cutoff of the ensemble. A rank without atoms takes part in
  the reductions, the per-atom output follows the tags, `dpa4spin`
  appends to the file when a run continues a restart, and the parser
  keeps the earlier diagnostics. The deviation of the magnetic force is
  converted with the energy factor of the units, as the magnetic force
  is an energy per unit of moment; the two factors agree in metal and
  real units.
- The edge-input virial of `deepmd/kk` is summed in one array reduction
  of its nine components.

Fixes.
- A `.pt2` compiled for the CPU crashed when a CUDA device was visible:
  DeepPotPTExpt, DeepSpinPTExpt, NativeSpinPTExpt and DeepEval placed
  the inputs on the device that `torch.cuda.is_available()` names. They
  now read `AOTI_DEVICE_KEY` from the package and run a CPU package,
  with its deserialized model, on the CPU; a CUDA package without a
  CUDA device fails with a message.
- `pair_style deepspin` with a pt-backend model, which declares no spin
  types, rejected `virtual_len` and `spin_norm` with "wrong number of
  parameters"; it now names the option the model does not take.
- `dp --pt-expt freeze` warned that it overrode `--lower-kind nlist` on
  every freeze of a graph-capable model, although `nlist` was only the
  default. The default is now `auto`, and the warning appears only when
  `nlist` is requested.

C API. `DP_DeepSpinCanonicalGraphRequiresSourceCSR` joins
`DP_DeepPotCanonicalGraphRequiresSourceCSR` within API version 32.

Throughput (LAMMPS fork, BCN diamond, both backends at Triton and CUDA
level 2, mean of three runs on three GPUs): `deepmd/kk` against the pt
`deepmd` 1.04-1.17x for nano and mini and 0.99-1.00x for neo and air,
the residual being the forward of the pt-expt model; `dpa4spin/kk`
against the pt `deepspin` 1.04-1.61x.

Tests. test_dpa4_canonical.py and test_canonical_graph.py cover the
graph evaluator, its view and its border plan; the typed C/C++
canonical suite evaluates two-block DPA4 energy and native-spin
archives from gen_dpa4c_canonical.py; the Kokkos halo regressions run
the DPA4 fixtures; test_lammps_model_devi_canonical.py runs an ensemble
of a DPA4C and a DPA4 model through the four styles of the compact
lower on one and two ranks, across neighbor rebuilds, a migration
between ranks, a new run and a reset of the step, and on four ranks
with one empty; test_graph_export_with_comm.py pins the 17 inputs of
the graph-spin lower of DPA4 and two-block DPA4C and the 14 of a
single-block DPA4C; test_dpa4c_parallel.py and test_dpa4_zbl_parallel.py
compare the border plan, eagerly and through the traced graph-spin
lower, with the folded frame; the native-spin LAMMPS MPI tests run
`deepspin` and `dpa4spin` on two ranks and with owned-empty ranks;
TestDeepEvalCpuPackageOnCuda and a deepspin option test cover the
fixes.
A DPA4.5 model can carry a mixture of experts (MoE): its expert maps
compute the atom i of a frame of task t with the weight

    W + V_t + U_Z(i) + sum_k c_k A_k,

the shared weight of the plain map, an increment of the task of the
model, an increment of the element of the atom, and K experts mixed by a
router. The task and the element select their increment; the router
mixes the experts by the charge and spin multiplicity of the frame, the
task and the element. Training spends the additional weights, and
dp --pt-expt moe-merge turns the trained model into a plain DPA4.5, or
into one that keeps weights of its own for chosen elements, before it is
deployed.

No condition depends on a coordinate, so the energy keeps the smoothness
of DPA4.5 and the forces carry no routing term. Every term has the
layout of W, so every map keeps its symmetry for any conditions. All
terms but W start at zero, so a fresh model equals the plain model of
the same seed.

Model.
- descriptor.moe makes every linear map of the feed-forward subblocks of
  the interaction blocks and of the read-out an expert map: the SO(3)
  linear maps and the maps inside the nonlinearity. fitting_net.moe does
  the same for every layer of the fitting network. It is a capability of
  the fitting base class, so the plain energy fitting has it like the
  DPA4 fitting; it requires one network for all types and takes no case
  embedding. The two sections are independent.
- Both sections take n_experts (8; 0 builds no router), element (true
  for every element of the type map, false, or a list of symbols),
  mat_prob (0.37) and the shape of the router (dim 64, layers 1). An
  empty section uses the defaults.
- The router embeds its conditions additively, applies silu layers and
  gives every unit, a feed-forward network or the fitting network, a
  softmax over the experts. The descriptor router reads the charge/spin
  embedding of the frame (add_chg_spin_ebd); the fitting router reads
  the task and the element alone, so its experts require element.
- The task parameters, the increments V_t and the task embedding of
  every router, belong to the descriptor and the fitting of one model.
  Branches that share a descriptor or a fitting share its networks and
  routers and keep these parameters, so every branch is a task named by
  its key. A single-task model is one task, named by model.task, whose
  task parameters stay zero and are not trained.
- Fine-tuning continues a pretrained task (finetune_head, or a branch
  with the key of that task) or starts a new task from the shared
  weights, which takes the pretrained fitting network when that carries
  MoE. The rule also holds where a spin-free model becomes a native-spin
  one. The element increments are stored by slot, so a fine-tuned model
  names the elements of the pretrained one.

Merge-aware training (MAT). With probability mat_prob a training frame
is evaluated without anything specific to an element: its atoms take no
element increment and the router reads no element. One sample per frame
serves the descriptor and the fitting. These frames train the shared
weights as a model of their own, which is the model that the merge
without elements returns; with mat_prob 0 that merge is refused.
Evaluation uses the element weights in every frame, and so do the output
statistics of a bias change: the PyTorch Exportable model takes them in
evaluation mode whatever mode it is called in.

Forward. Atoms that share their conditions share their weights. The rows
of a unit are laid out in chunks of one element slot, or of one
charge/spin state and slot, the weights of every chunk are formed once
for all maps of the unit, and every map contracts the chunks in one
batched product, one per degree for the SO(3) linear map. The cost of a
contraction therefore depends neither on the number of elements nor on
the number of experts. A layout by few element slots has a chunk count
that follows from the number of rows, so a merged model that keeps
elements exports with static shapes.

A vacuum reference follows the weights of the atom it references: under
a router and in training, the atomic model appends one isolated atom per
frame and type to the graph; a merged model references per type and
folds the reference at freeze.

Merge. dp --pt-expt moe-merge adds the task increment and the experts at the
coefficients of one scenario to the shared weights and drops the router and
the task parameters. Without --elements the result is a plain DPA4.5 of the
same structure and type map. With --elements (or all) the named elements
keep an increment, and the result equals the trained model on systems of
these elements. --charge-spin gives the state of the scenario, which becomes
the default state of the result, and --task (aliases --head and
--model-branch) selects the branch of a multi-task checkpoint. The merged
checkpoint holds the weights of the model and starts a training, a
fine-tuning or a freeze; export refuses a model that still has a router. A
checkpoint that still has a router is evaluated as it is by DeepPot, dp test
and the ASE calculator, which load it eagerly, and its multi-task branches
are named by --task. The descriptor and the fitting declare the merge
through their base classes (has_experts, has_expert_router, merge_experts,
expert_options, branch_local_parameters), so nothing above them names a
class.
Code. An expert map is a subclass of its plain map with one mixin for
the increments, the experts, their merge and their record; modules that
own maps take an option instead of a subclass. One mixin holds what the
descriptor and the fitting share: the option, the task parameters, the
router, the weights of a forward, the merge and the record.

Compiled multi-task training traces one graph per model structure, and a
branch with task parameters of its own needs its own graph, so the
structure key holds the parameters a branch owns. Two conditions that
the trace bakes in the same way join the key: the per-type spin flags of
a native-spin descriptor, whose masks differ between replicas, and the
identity of a contact clamp, whose recorded contacts are those of the
data of its branch. A spin-free branch that shares the descriptor of a
native-spin branch takes the common learned layers of the spin-dependent
members and keeps the state its own configuration builds.

A compiled graph serves every number of frames in a batch. The states
of the frames are indexed by comparing every sorted frame with a
gathered predecessor, so the graph holds no condition on the number of
frames. The compile tail of the trainer writes the element counts that
make_fx records as aten.sym_numel as Tensor.numel: Dynamo specializes
an axis of length one and breaks the graph at an aten.sym_numel of a
specialized tensor, which a batch of one frame makes of every gather
over the frames, and with Tensor.numel such a batch is retraced as one
frame.

The weights of a unit sum the joined shared weights and the joined task
increments, and the backward of that sum hands slices of one buffer to
both. The trainer gives the gradients of the task parameters storage of
their own, so that clipping, which scales gradients in place, scales
every gradient once, in eager and in compiled training.

Data-parallel training at ZeRO stages 0 and 1 reduces the element
weights over the rows of the elements in the batches of the step. The
gradient of a row is zero without an atom of its element, so the ranks
take the union of their atom types before the forward, and the
communication hook reduces the other parameters whole and the banks over
the rows of the union. The descriptor and the fitting declare their
banks through their base classes (element_banks); the gradients equal
those of the whole reduction up to rounding, for any number of ranks and
without an option.

The options belong to the PyTorch Exportable backend. The PyTorch, JAX
and TensorFlow 2 descriptors and the energy fittings of the PyTorch,
JAX, Paddle, TensorFlow and TensorFlow 2 backends refuse them and name
the merge as the way to load a trained model.

Documentation. The DPA4 page is rewritten as a guide that follows a
first project, with a section that states what MoE is, when to use it
and how; the fine-tuning page describes new tasks of an MoE model. The
statements on the JAX backend are corrected: it trains property fitting
and LoRA fine-tuning of DPA4. The description of sel names the denoising
path alone as capped.

Cost. On DPA4.5-Mini, compiled training on OMol25 takes 16% longer per
step with the element increments alone and 31% longer with the defaults.
A frozen model that keeps eight elements takes 8 to 13% longer than the
plain model and 10 to 30% more memory between 8000 and 500 atoms; a
plain merge costs nothing.

Verified: a fresh model against DPA4.5 for every option combination;
rotation, inversion and permutation invariance; the response of the
router to the state, the element and the task; the three kinds of merge
against the model, with a vacuum reference, and of each branch of a
multi-task checkpoint; MAT in training forwards only, and a bias change
in training mode that keeps the bias of a model labelled with its own
energies; the row layout; the PyTorch Exportable model against the
reference implementation and finite-difference forces; tasks in
single-task training and in fine-tuning into several tasks, including
the native-spin conversion; the ordinary freeze of merged models against
their checkpoints through DeepPot; two-rank data-parallel training,
single-task, multi-task, at ZeRO stage 1 and compiled; the reduced
gradients of a step against their whole average on two ranks that see
different elements; zero gradients of the rows of absent elements; the
gradients of a step under scaling in place, eager and compiled; one
graph per branch in compiled multi-task training; compiled training of
two native-spin tasks through batches of one, two and more frames; the
bias change of one task of a multi-task checkpoint; the refusals of the
PyTorch and JAX backends; and input validation.
A branch of a multi-task model names an entry of shared_dict for its
spin settings and for its preset output bias, as it does for its type
map, descriptor and fitting network:

    "shared_dict": {"my_spin": {...}, "my_bias": {"energy": {...}}},
    "model_dict": {"a": {"spin": "my_spin", "preset_out_bias": "my_bias"}}

Branches with the same magnetic elements or the same reference energies
write the setting once. The two entries are settings, not networks:
every branch that names one receives a copy, as if the entry were
written in the branch, no parameter is linked, and a branch that does
not name it is unaffected.

- The entries a branch can reference are defined once, as the settings
  and the components of shared_dict, in the shared preprocessing of the
  PyTorch, PyTorch Exportable and JAX backends. The JSON schema of a
  multi-task input admits a string for the same entries.
- A table named inside a shared entry is resolved after the expansion,
  like a table written in a branch. The table resolution leaves a branch
  that still names a shared entry as it is, so an input that has not
  passed the shared preprocessing reaches the argument check.

The Paddle and TensorFlow 2 backends preprocess shared parameters with
code of their own, which is unchanged.

Verified: a model that names shared spin and bias entries is processed
to the configuration of the model that writes them out, through the
preset expansion, the shared preprocessing, the table resolution and the
argument check; the links hold the networks alone and every branch owns
its copy; the schema accepts the references in a preset branch; a
two-task native-spin DPA4.5 input with MoE trains with the references
and records the model sections of the input with inline entries.
The energy of an isolated atom depends on its spin moment. A native-spin
model with `vacuum_ref` gave its reference atom the unpaired-electron count
of the neutral ground-state atom, whatever moment the isolated-atom
calculation behind the preset converged to.

An entry of `preset_out_bias` may hold the value together with the magnitude
of that moment, in the units of the spin input:

    "preset_out_bias": {"energy": {"Fe": {"value": -3.4, "spin": 3.0}, "O": -1.5}}

The reference atom of such a type carries this moment, so an atom without
neighbors that carries it has exactly the preset energy. The magnitude alone
is given, for collinear and non-collinear moments alike: the energy of an
isolated atom does not depend on the direction of its moment. A type whose
entry names no moment keeps the unpaired-electron count, so existing inputs
and checkpoints behave as before. A type that is no element symbol can take
the reference when it names its moment and native spin is the only condition
of the reference atom.

The normalized preset keeps the moments per type under the key `@spin`, which
the type-map remap carries along; `reference_spin` reads them in the dpmodel
atomic model (pt_expt, JAX) and in the PyTorch SeZM atomic model. A moment
without a value, a negative or non-finite moment, and outputs that name
different moments of one type are rejected when the input is read.

The keys by which task branches share a compiled graph, `_sezm_structure_key`
(pt) and `_get_model_structure_key` (pt_expt), include the reference moments:
branches that share their networks and name different moments trace
different graphs.

The dipole atomic models test the outputs of their preset by name.

Tests: entry forms, errors, idempotence and remap of the normalized preset;
`reference_spin`; on pt_expt and pt, an isolated atom at the named moment has
its preset energy before and after the fold, the unpaired-electron count gives
another energy, and branches with different moments have different graph
keys.
The isolated-atom energy reference subtracts an isolated reference atom's
output from every atom under charge/spin conditioning. Which condition that
atom takes was fixed to the neutral ground state, so a materials model whose
data carry no charge/spin labels left every open-shell element unpinned.

The condition now comes from the preset table. An entry of preset_out_bias
may name the isolated atom its value belongs to with charge and multiplicity,
beside the spin moment it may already name; the normalized preset holds it
per type under @charge_spin. A type whose entry names no condition is
referenced to default_chg_spin, and an assigned type without a condition and
without a default is an error. A type without a preset energy needs no
condition, so a table of a subset of the elements serves a type map of all of
them.

The resolved condition belongs to the model: it is stored with the preset, so
a later change of the default condition, such as the one moe-merge
--charge-spin writes, does not move the reference. A merge carries the
resolved preset into the merged model, so it evaluates a structure at the
merged state exactly as the trained model did; fine-tuning resolves the
reference from its own preset.

The bundled omol25 table now names the neutral ground state of every element.
The compiled-graph keys of both PyTorch routes include the resolved reference
conditions, so branches with different references never share a traced graph.

The change of the bias of a pt_expt model now samples every system up to its
own pass length instead of the shortest one, and its statistics forward runs
in bounded, gradient-free inference batches.
DPA4C normalizes its degree-wise moments with a fixed floor of 1/4. A lone
neighbor has a mass of about one half, far below a bulk atom, so the
reduction of a sparse environment grows without bound as the coordination
falls and the fitting network reads inputs far outside its training range.
DPA4.5 already solves this by measuring the mean envelope mass of the
training neighborhoods; DPA4C now takes the same floor.

The new `density_floor` option scales that measured mass, and `0`, the
default, keeps the fixed floor so a record written before the option existed
loads and evaluates unchanged. The measurement reuses the DPA4 helper, the
mass is stored with the model and merged across sharing replicas by atom
count, and the compressed operators read it from their existing
`degree_floor` scalar, so the kernel schema is untouched.

The `dpa4.5c-<grade>-v20261111` presets ship the floor at 8 together with
the fixed Gaussian radial basis.
soft_saturate rescaled inputs by max(|x|, knee) so squaring stays finite in half precision. Under make_fx symbolic force tracing, abs backward emits aten.sgn.default, whose C++ second-order backward queries concrete aten.size.default and specializes the symbolic node and edge axes to constants on every new batch shape.

Express the saturation scale through sign-branch selection with where in both DPA4C attention implementations, and decompose aten.sgn.default alongside aten.silu_backward.default in build_make_fx_decompositions so any traced abs derivative lowers to shape-symbolic aten.sign.default.
Every term MoE adds starts at zero, so the state of a model without MoE to
the same architecture is the state a model with MoE starts from: its keys are
those of the MoE model minus the terms of the task, the elements, the experts
and the router, and it has no key the MoE model lacks. A fine-tuning or an
initialization that writes a `moe` section therefore starts at the model it
started from, whether that model was trained plain or merged from an MoE
model, and whether MoE is added to the descriptor, the fitting or both.

`--init-model` accepts such a checkpoint through `check_expert_state`, which
admits a source whose missing keys all name a term of MoE and refuses one
that holds a key the target lacks, and it now runs the element-slot check
that only `--finetune` ran before. `--finetune` compares the shape of every
term both sides hold, so a different expert count or element list is reported
instead of failing in the state load. `--use-pretrain-script` keeps a `moe`
section of the input when the pretrained record has none, and the key is left
out of the descriptor-configuration warnings.

The task increments of the maps take the AdamW path under HybridMuon: an
orthogonalized step moves every row of a matrix at the same rate, so an
increment that one task constrains only where its data reach would grow into
the directions no task labels. The descriptor and the fitting declare the
pattern, and the atomic model now forwards both, which it did for the
descriptor alone.
Copilot AI balanced review requested due to automatic review settings November 25, 2026 02:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

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

@github-advanced-security github-advanced-security AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

CodeQL found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.

@njzjz-bot njzjz-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Agent: dot

The standalone C-library consumer build fails while compiling the LAMMPS plugin. The diagnostic is invalid use of void expression in load_ensemble; the packaging job itself succeeds.

Comment thread source/lmp/model_deviation.h Resolved
@OutisLi OutisLi added the Test CUDA Trigger test CUDA workflow label Nov 25, 2026
@github-actions github-actions Bot removed the Test CUDA Trigger test CUDA workflow label Nov 25, 2026
@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.42459% with 329 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.77%. Comparing base (24478f1) to head (6c9b426).

Files with missing lines Patch % Lines
deepmd/jax/train/distributed.py 56.45% 91 Missing ⚠️
deepmd/jax/train/trainer.py 91.62% 36 Missing ⚠️
deepmd/jax/optimizer/hybrid_muon.py 94.68% 15 Missing ⚠️
deepmd/dpmodel/fitting/dpa4_ener.py 93.22% 13 Missing ⚠️
deepmd/jax/infer/deep_eval.py 86.31% 13 Missing ⚠️
deepmd/jax/model/model.py 87.64% 11 Missing ⚠️
deepmd/dpmodel/descriptor/dpa4_nn/grid_net.py 93.07% 9 Missing ⚠️
deepmd/jax/model/hlo.py 82.35% 9 Missing ⚠️
deepmd/dpmodel/descriptor/dpa4.py 95.67% 8 Missing ⚠️
deepmd/jax/common.py 80.55% 7 Missing ⚠️
... and 41 more
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #6163      +/-   ##
==========================================
+ Coverage   78.22%   78.77%   +0.55%     
==========================================
  Files        1218     1253      +35     
  Lines      147790   152408    +4618     
  Branches     5243     5181      -62     
==========================================
+ Hits       115605   120060    +4455     
- Misses      30206    30417     +211     
+ Partials     1979     1931      -48     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@OutisLi OutisLi added the Test CUDA Trigger test CUDA workflow label Nov 25, 2026
@github-actions github-actions Bot removed the Test CUDA Trigger test CUDA workflow label Nov 25, 2026

@njzjz-bot njzjz-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Agent: dot

The V100 model shard fails all three DP_CUDA_INFER cases at the all-block _cuda_conv_fn binding assertion, before comparing numerical results. The factory explicitly declines blocks that fail its performance gate. For this parity/float32 fixture at lmax=2 and focus width 32, _profitable charges 19,456 FMA per focus stream. A V100 SXM2's nominal FP32/bandwidth ratio gives roughly a 15,600 FMA budget with the current formula. That makes the absent binding consistent with intended fallback, even if the operator is registered. Please check registration and print support/profitability per block on this runner. Exercise the numerical fused-path checks with an admitted layout, and test fallback separately; removing the binding check by itself would allow the parity test to miss the fused path entirely.

The same shard's 12 teardown errors come from monkeypatch.setattr(torch.backends.cuda.matmul, "allow_tf32", False), which pytest later tries to undo with delattr on the cuBLAS proxy. Save and restore the backend precision values in a scoped finally instead.

Kokkos/LAMMPS and C++ now pass. Separately, the calculator shard still segfaults, on this run inside FakeTensor/AOTInductor while creating the archive at line 616. The last run faulted after loading it at line 631. Run each test_automatic_freeze_single_artifact_matches_eager parameter in a fresh process with its node ID printed before construction to identify whether this is one device/model combination or process-state dependent.

@OutisLi OutisLi added the Test CUDA Trigger test CUDA workflow label Nov 25, 2026
@github-actions github-actions Bot removed the Test CUDA Trigger test CUDA workflow label Nov 25, 2026
@OutisLi OutisLi added the Test CUDA Trigger test CUDA workflow label Nov 25, 2026
@github-actions github-actions Bot removed the Test CUDA Trigger test CUDA workflow label Nov 25, 2026
@OutisLi OutisLi added the Test CUDA Trigger test CUDA workflow label Nov 25, 2026
@github-actions github-actions Bot removed the Test CUDA Trigger test CUDA workflow label Nov 25, 2026
@OutisLi OutisLi added the Test CUDA Trigger test CUDA workflow label Nov 25, 2026
@github-actions github-actions Bot removed the Test CUDA Trigger test CUDA workflow label Nov 25, 2026

@wanghan-iapcm wanghan-iapcm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This PR extends the DPA4/DPA4C family and the pt_expt/JAX backends in several coupled areas. It adds DPA4.5 presets that configure per-block cutoff and mixing depth, a measured neighborhood-density floor, and inversion-equivariant vacuum readouts; a model-level mixture-of-experts layer with merge-aware training and a dp --pt-expt moe-merge entry point; DPA4 training and graph-native inference on JAX covering forces, virials and native-spin magnetic forces; a compact canonical graph deployment path with matching LAMMPS Kokkos support and a DPA4 serialization helper for normalizing SeZM records; and model-deviation ensembles for the deepmd/kk, dpa4spin and dpa4spin/kk pair styles. Tests, documentation and examples are updated alongside, including a new Kokkos per-atom-energy regression test, a corrected host-owned per-atom energy tally, and bounded dynamic graph extents for AOTInductor.

I found no blocking issue in this review.

@OutisLi
OutisLi added this pull request to the merge queue Nov 26, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants