---
name: processed-dkd-meal
description: "Run molecular dynamics (or any conservative mechanical simulation) with a machine-learned potential at larger time steps for the same accuracy, by training the potential for the step size you will use. Needs position and force training data (for example DFT forces), a differentiable scalar potential model, constant known masses, a fixed step and output on a regular time grid. The potential is fitted to a corrected force that cancels the integrator's leading error; simulation then uses ordinary forces only, one per step plus four at the start and four per saved frame, and is fourth-order accurate for the step-specific target potential. Best when forces are expensive and frames are saved every several steps. Also known as Modified-Equation-Aware Learning (MEAL) with processed leapfrog (processed drift-kick-drift, DKD, position Verlet with a symplectic pre- and postprocessor)."
---

# Processed-leapfrog MEAL (processed DKD)

## 1. What this solves

You fit a potential energy model to forces, for example a neural network trained on DFT forces, and then run dynamics with it. The usual recipe fits the forces as closely as possible and leaves accuracy to the integrator, so a leapfrog (Verlet) simulation still carries an error that grows with the square of the time step, and you pay for accuracy with small steps and many force calls. This method instead trains the potential **for the step size you will simulate with**, so that the integration error is compensated during training. With a small change to the integrator (a fixed change of variables at the start and at each saved frame), the simulation becomes fourth-order accurate for the step-specific target potential, while each step still costs one ordinary force evaluation. Training uses the same position-force pairs as ordinary force matching.

In technical terms: for a separable Hamiltonian $H = \tfrac12 p^\top M^{-1}p + V(q)$ with constant diagonal mass matrix $M$, plain leapfrog has a momentum-dependent $h^2$ error term that no learned potential can cancel (paper, Proposition 4.2). Processed leapfrog, $\Psi_h = \chi_h^{-1}\circ\Phi^{\rm DKD}_h\circ\chi_h$ (Eq. (36)), removes that term, leaving a position-only term $\tfrac{h^2}{24}\,\nabla V^\top M^{-1}\nabla V$ (Lemma 4.3) that a potential can absorb. Modified-Equation-Aware Learning (MEAL) fits $V_\theta$ so that its corrected gradient matches the force labels (Eqs. (41)–(42)). The processed map is explicit, symplectic and symmetric ($\Psi_{-h} = \Psi_h^{-1}$).

## 2. When to use

- Equations of motion $\dot q = M^{-1}p$, $\dot p = -\nabla V(q)$: conservative forces from a scalar potential, **constant diagonal masses** (repeat each atom's mass over $x, y, z$), no velocity or time dependence (paper Eq. (26)).
- You **train the potential** from samples $(q_i, F_i)$ with $F_i = -\nabla V_{\rm true}(q_i)$: DFT forces, or forces of a frozen teacher model you want to distil. No momenta, energies, trajectories or derivatives of the labels are needed. The model must be smooth enough to differentiate twice in position during training (one Hessian-vector product per configuration).
- One **fixed step** $h$ per trained checkpoint, and **physical output on a regular grid**, ideally every several steps: each output costs four extra force evaluations.
- Forces are expensive (a neural network or quantum chemistry), so saving force calls matters.

What the paper reports (Jiang, Guo, Zhu & Li, 2026, Section 5), on all ten molecules of rMD17 with a MACE potential:

- Against a teacher potential (Section 5.2), the fitted convergence order is 3.6 for MEAL with processed leapfrog versus 2.0 for leapfrog with the classically trained potential. At equal accuracy with physical output every 10 fs, it is up to 6.8× faster than classical leapfrog and up to 4.6× faster than fourth-order Yoshida integration (Table 4). The trained models do **not** show verified fourth-order convergence.
- Trained directly on DFT forces and compared with independent DFT trajectories (Section 5.3), it reduces the trajectory error by 56% relative to leapfrog at a 1 fs step and, with output every 10 fs, is 3.3× faster than leapfrog and 6.1× faster than Yoshida at equal accuracy (Table 5 and Figure 8). Below 1 fs all methods reach an error floor set by the potential and the reference calculation, not by the integrator.
- At 2 fs, 19 of 40 MEAL trajectories stayed intact for 200 ps against one for each classical integrator (Section 5.4, teacher-student setting).
- The gains depend on output frequency: at 2 fs with output every 2 fs, 400 of 504 force evaluations go to postprocessing and MEAL was slower than the matched leapfrog run (0.60×).

## 3. When not to use (and what to use instead)

| Situation | Use instead |
| --- | --- |
| The force law is given (a formula, an existing force field, a quantum-chemistry call at every step) and you will not train a model | `stormer-verlet`, or `yoshida4` for higher accuracy on smooth problems |
| Output needed at every step, or very short runs | `stormer-verlet` at a smaller step, or `yoshida4`; count the four evaluations per output before choosing (paper Section 4.5) |
| One model for several step sizes, or a step that changes during the run | Classical force matching with a standard integrator. A MEAL checkpoint is specific to its $h$: in the paper, using a checkpoint at another step raised the error by a factor of 2.0 to 451 |
| Adaptive steps or output at arbitrary times | `dormand-prince-rk45` over short runs; otherwise a fixed step with the output times on the step grid |
| Friction, thermostats, Langevin or other stochastic dynamics | A splitting designed for those equations (not in this library). The derivation does not cover them; any new splitting must be analysed and tested separately |
| Holonomic constraints (rigid water, fixed bond lengths) | RATTLE, SHAKE or SETTLE (not in this library) |
| Non-separable Hamiltonian or position-dependent mass | `implicit-midpoint` |
| Non-diagonal constant mass matrix | Not covered by the paper or the reference; the paper assumes $M = \operatorname{diag}(m_i)$ |
| Your model predicts forces directly, without an energy (a non-conservative force head) | Not applicable: the correction acts on a scalar potential. Train an energy model whose forces are its gradient first, or run your model with `stormer-verlet` |
| You learn the full vector field, not a potential | The general MEAL objective with an automatic-differentiation modified field (paper Section 3), for example with RK2; not this skill |
| You need sixth order | Not available with this processor: an $h^4$ velocity term remains for any potential (paper Appendix A.5) |
| Fast modes you want to step over, or close encounters | Multiple time stepping, regularization or adaptive time transformations (not in this library). The leapfrog stability limit still applies |

## 4. Algorithm

Notation: $v = M^{-1}p$, $\mathcal C[V] = \nabla V^\top v$, $\mathcal P[V] = v^\top\nabla^2 V\,v$, $\mathcal S[V] = \nabla V^\top M^{-1}\nabla V$ (Eq. (30)). Drift $D_t(q,p) = (q + tM^{-1}p,\ p)$ and kick $K_t(q,p) = (q,\ p - t\nabla V(q))$ (Eq. (28)).

**Why plain leapfrog is not enough.** The modified Hamiltonians are (Lemma 4.1, Eqs. (31)–(32))

$$
\tilde H_{\rm KDK} = T + V + \tfrac{h^2}{24}(2\mathcal P - \mathcal S) + O(h^4),\qquad
\tilde H_{\rm DKD} = T + V + \tfrac{h^2}{24}(2\mathcal S - \mathcal P) + O(h^4).
$$

$\mathcal P$ depends on momenta, so its gradient enters $\dot q$ and no change of $V$ removes it (Proposition 4.2, Remark A.4).

**Processing.** With a near-identity symplectic map $\chi_h = \varphi^{\mathcal C}_{-h^2/24} + O(h^4)$, the processed DKD has $\tilde H_{\rm proc} = T + V + \tfrac{h^2}{24}\mathcal S[V] + O(h^4)$ (Lemma 4.3, Eq. (37)). For the target potential $V^\star_h = V_0 - \tfrac{h^2}{24}\mathcal S[V_0]$ (Proposition 4.4, Eq. (39)) the processed map has one-step error $O(h^5)$ and global error $O(h^4)$ in the physical $(q, p)$ on bounded intervals with bounded derivatives. Both ingredients are needed: processing with $V_0$, or $V^\star_h$ without processing, stays second order (paper Table 7, reproduced in `verify/check_paper.py`).

**Training** (Section 4.4, Algorithm 3). Fit $V_\theta$ to labels $F_i$ by minimizing

$$
\tilde g_{\theta,h}(q) = \nabla V_\theta + \tfrac{h^2}{12}\,\nabla^2 V_\theta\,M^{-1}\nabla V_\theta
= \nabla\Big(V_\theta + \tfrac{h^2}{24}\,\nabla V_\theta^\top M^{-1}\nabla V_\theta\Big),
\qquad
\mathcal L(\theta) = \operatorname{mean}_i \big\| \tilde g_{\theta,h}(q_i) + F_i \big\|^2
$$

(Eqs. (40)–(42)). In an autodiff framework: $g = \nabla_q V_\theta$ with the graph kept, $\mathcal S = g^\top M^{-1} g$, $\tilde g = g + \tfrac{h^2}{24}\nabla_q \mathcal S$, then backpropagate through both copies of $g$. The minimizer approximates $V^\star_h$. Start from a classically trained checkpoint.

**Simulation** (Section 4.3, Algorithm 2). Use the **ordinary** gradient $\nabla V_\theta$ in every kick; never $\tilde g$.

1. Set $s = |h|/\sqrt{48}$. The postprocessor $\chi_h^{-1}$ applies the eight shears (Appendix A.4, Eq. (68))
   $$D_s,\ K_s,\ D_{-s},\ K_{-s},\ D_{-s},\ K_{-s},\ D_s,\ K_s$$
   in this order. The preprocessor $\chi_h$ is its exact inverse: the same shears in reverse order with every duration negated.
2. Preprocess the physical initial state once to get the auxiliary state.
3. Advance the auxiliary state with ordinary DKD, $D_{h/2}\,K_h\,D_{h/2}$, one force per step.
4. At each output step (every $k$ steps and at the final step), postprocess a **copy** of the auxiliary state and emit it. Never write the output back.

Cost for $N$ steps with output every $k$ steps and at the end (Eq. (43)):
$$N_F = N + 4 + 4\lceil N/k\rceil,$$
so $N + 8$ with output only at the end. The processor depends on $|h|$, so running with $-h$ integrates backwards exactly ($\Psi_{-h} = \Psi_h^{-1}$).

## 5. Parameters

| Parameter | How to choose it |
| --- | --- |
| Step size $h$ | Train one checkpoint per candidate $h$ and check accuracy and stability on short runs against a reference at a much smaller step. The leapfrog stability limit applies ($h\omega < 2$ for the fastest harmonic mode, with margin). The paper used 0.25 to 2 fs for small organic molecules. Keep checkpoint, processor and core tied to the same $h$. |
| Output interval $k$ | As large as your analysis allows; each output costs four forces. Step $n$ is time $t_0 + nh$. Changing $k$ does not change the trajectory. |
| Masses and units | One positive mass per coordinate, canonical momentum $p = Mv$, consistent units for positions, energies, forces, masses and time (the paper uses atomic units). |
| Loss weighting | The basic loss is Eq. (42). For several molecules, the paper divided each configuration's mean squared component error by a per-molecule force scale squared and by $(h/0.5\,\mathrm{fs})^4$ (Eq. (69)); the second factor does not change the minimizer. |
| Model and optimizer | Initialize from a classically trained checkpoint and fine-tune with Adam; choose learning rate and stopping from held-out loss and short rollouts. No transferable defaults. |

## 6. Applying it to your own code

- **Training.** Wrap your scalar energy model: `g = grad(V(q).sum(), q, create_graph=True)`, `S = (g * g / m).sum()` (per configuration, `m` the per-coordinate masses), `g_mod = g + h**2/24 * grad(S, q, create_graph=True)`, loss `mean over configurations of ((g_mod + F)**2).sum()`. Summing $\mathcal S$ over a batch before differentiating is fine for independent configurations. Do not detach either copy of `g`; the labels may be detached. Use the same splits and metrics for a classical control with `g + F`.
- **Simulation.** Only first derivatives of the trained potential are needed. Keep the auxiliary state (carried forward) separate from the physical output (a postprocessed copy). For a restart, save the auxiliary state, step index, checkpoint and $h$, and resume the core steps directly; if you only saved a physical state, preprocess it again.
- **Analytic check.** For a known smooth potential, $V^\star_h = V_0 - \tfrac{h^2}{24}\nabla V_0^\top M^{-1}\nabla V_0$ stands in for a perfectly trained model; use it to test your simulation code for order 4 before training anything.
- `reference/processed_dkd.py` shows the loss and the exact shear order in a few lines with hand-written gradients and Hessian-vector products; translate the arithmetic to NumPy, JAX or PyTorch and take the derivatives from your autodiff. Nothing else in the file is essential.
- When you write code using this method, add the comment `processed-dkd-meal v0.1.0, Jiang, Guo, Zhu & Li (2026)`.

### Using a model other than the paper's

The method does not depend on the architecture: training needs a scalar energy $V_\theta(q)$, simulation needs only its gradient. The paper demonstrates processed-leapfrog MEAL with one model, a MACE potential on rMD17 (paper Section 5). Any other model is untested until you validate it. Check these before training:

1. **Energy model.** Forces must be $-\nabla_q V_\theta$. Models with a separate force output cannot be used (see section 3 of this skill).
2. **Smooth to second order in positions.** The loss differentiates the gradient once more. Use smooth activations (SiLU, tanh, softplus; not ReLU, whose second derivative is zero or jumps) and a cutoff envelope that is at least twice continuously differentiable, so neighbours crossing the cutoff do not cause jumps.
3. **Double backward works.** `create_graph=True` (PyTorch) or nested `jax.grad` must run through the whole model. Custom or fused GPU kernels sometimes lack second derivatives; this shows up as an error or as silently zero gradients. Test it as in step 1 below. Expect training to cost roughly two to three times ordinary force matching; simulation costs the same as before.
4. **The paper's setting.** Constant masses, energy-conserving dynamics, no thermostat, no constraints. Periodic boundary conditions were not tested in the paper: keep drift steps on unwrapped coordinates (or wrap consistently with the neighbour list) and validate.
5. **One checkpoint per step size.** Start from your ordinary force-matched checkpoint and train a separate model for each $h$.
6. **Your MD code needs the processed integrator.** A standard velocity-Verlet loop (LAMMPS, OpenMM, ASE) cannot be used unchanged: add the preprocessing step at the start and a postprocessing step on a copy of the state at each saved frame, four force calls each. Saving every step removes the speed-up.

Two quick tests on your model before a full training run:

1. **Loss gradient.** On a few configurations in float64, compare the autodiff derivative of the loss with respect to a few parameters against central finite differences. A mismatch, or a derivative of exactly zero, means the second derivative is not flowing through the model.
2. **Order.** On a small system, train (or fine-tune briefly) at $h$ and $h/2$, simulate the same initial states to the same physical time, and compare with a fine reference. The error ratio should clearly exceed the classical value of about 4 (order 2); the paper's MACE models reached a fitted order of about 3.6, an error ratio of about 12.

## 7. Verification

**Step 1: check your implementation against this skill.** Do this after porting and before training or production runs. Show the output to the user.

- Get the files: put `checks/check_port.py` and `checks/cases.json` **in the same folder** (the script reads `cases.json` from beside itself). Through MCP, fetch both with `get_file`; or download and unpack the skill's zip.
- Python: create `port_adapter.py` in your working directory with `PARTS = ("training", "simulation")` (or the part you implemented) and the functions described at the top of `check_port.py`: `modified_gradient` and `loss_and_derivative` for a fixed two-coordinate polynomial potential $V_\theta = \theta V_1$ that you write in your framework, and `process` and `rollout`, which receive the gradient as a plain function. Then run it **from the directory that contains `port_adapter.py`**, with the Python environment in which your code works:

  ```sh
  python <folder-with-the-check-files>/check_port.py
  ```

  It compares your results with fixed cases computed by the reference implementation (only rounding differences are allowed), checks that your $d\mathcal L/d\theta$ is the derivative of your own loss, and checks order 4 on the quartic double well with $V^\star_h$, the processor round trip, returning to the start with $-h$, output-interval independence and the force count $N + 4 + 4\lceil N/k\rceil$.
- Other languages: run each case in `checks/cases.json` with your code (problem, inputs and interface are described there) and compare with `expected` within `tol`.

A failed fixed case almost always means a porting mistake: $1/24$ and $1/12$ mixed up, a detached gradient copy in the loss, pre- and postprocessor swapped or shears in the wrong order, $s \ne |h|/\sqrt{48}$, momentum used as velocity, a force sign error, the corrected gradient used in simulation kicks, or the output written back into the auxiliary state.

**Step 2: check the method on your own problem.**

1. **Convergence order of the simulation code.** With an analytic $V^\star_h$ (or a small model trained separately for $h$, $h/2$, $h/4$), integrate to a fixed time and compare with a much finer reference. Processed leapfrog with $V^\star_h$ should give errors falling about 16× per halving; plain DKD with $V_0$ about 4×.
2. **Trained model against classical training.** Same initial states, horizon, output times and error metric; record the step size and force calls of each. Expect the gain to shrink at small $h$, where the fitting error of the potential dominates, and with frequent output.
3. **Step specificity.** Evaluate the checkpoint at its training step and at a neighbouring one; it should be best at its own step.
4. **Energy and stability.** Over long runs the energy error should stay bounded without drift; watch failure rates at the largest $h$, checked on a fine enough output grid.

## 8. Failure signatures

| Symptom | Likely cause |
| --- | --- |
| Only order 2 with an analytic $V^\star_h$ | Output not postprocessed, processor shears in the wrong order or with the wrong $s$, or $1/24$ and $1/12$ confused. `verify/check_method.py` shows unpostprocessed output and a checkpoint trained for $2h$ both at order 2. |
| Good training loss, poor trajectories | Checkpoint used at a step it was not trained for; units or mass mismatch between training and simulation; corrected gradient $\tilde g$ used in the kicks; configurations outside the training data. |
| Results change with the output interval | The postprocessed output is written back into the auxiliary state. |
| Round trip pre then post does not return the input | The preprocessor is not the exact inverse: reverse the order **and** negate every duration. |
| Blow-ups at larger $h$ | Leapfrog stability limit for the fastest modes, or out-of-domain configurations. Reduce $h$ or extend the training data. |
| Expected speed-up disappears | Output too frequent (four forces per output), or the run is too short for the eight processor forces to pay off. |
| Momentum-flip round trip misses by a small amount | Expected: the method is symmetric ($\Psi_{-h} = \Psi_h^{-1}$) but not reversible under momentum flip, because the processor is not; the round trip agrees only to the processor error. Test with $-h$ instead, which is exact. |

## 9. Files and commands

Run from this folder with [uv](https://docs.astral.sh/uv/) and Python 3.11 or newer; only the standard library is used.

```sh
uv run examples/fit_harmonic.py
uv run examples/double_well.py
uv run verify/check_method.py
uv run verify/check_paper.py
uv run verify/check_cases.py
```

- `reference/processed_dkd.py`: corrected gradient and loss, drift, kick, DKD step, processors and the rollout of Algorithm 2.
- `examples/`: fitting a spring from four force labels and simulating it (MEAL versus classical training with leapfrog), and the quartic double well of the paper's Table 7; expected output in `*.expected.txt`.
- `checks/`: for checking **your** implementation. `cases.json` holds fixed cases; `check_port.py` runs them and the property checks through `port_adapter.py`; `make_cases.py` regenerates `cases.json` from the reference implementation.
- `verify/`: evidence for the claims in this file, run on the reference implementation: order 4 and the documented order-2 failures, symplecticity, symmetry, processor inversion, output independence and cost (`check_method.py`); reproduction of the paper's Table 7, the $h^2$ coefficients of Lemmas 4.1 and 4.3 and Remark A.4, the sixth-order obstruction and the force counts (`check_paper.py`); and that the fixed cases catch nine typical porting mistakes (`check_cases.py`).

## 10. Sources

- H. Jiang, Y. Guo, A. Zhu, Q. Li. Accelerating Dynamical Systems Simulation via Modified-Equation-Aware Learning. 2026. [arXiv:2612.01280v1](https://arxiv.org/abs/2612.01280v1). Equation, lemma, proposition, section and table numbers in this file refer to arXiv v1.
- E. Hairer, C. Lubich, G. Wanner. *Geometric Numerical Integration*, 2nd ed. Springer, 2006. https://doi.org/10.1007/3-540-30666-8
- E. Hairer, R. I. McLachlan, R. D. Skeel. On energy conservation of the simplified Takahashi–Imada method. *ESAIM: Mathematical Modelling and Numerical Analysis* 43(4) (2009) 631–644.
- S. A. Chin. Quantum statistical calculations and symplectic corrector algorithms. *Physical Review E* 69 (2004) 046118.
