---
name: permutation-invariant-macrodynamics
description: Learn extra state coordinates and forecast an intensive observable from timed particle sets with arbitrary indexing. Fit deterministic or stochastic dynamics to the augmented state.
---

# Learning Permutation-invariant Macroscopic Dynamics

## 1. What this solves

Two particle configurations can give the same bulk observable and have different futures. Learn extra coordinates from the distribution of particles in each frame, then fit a law for the observable and those coordinates. The coordinates are invariant to reordering particles within a frame.

Fit an ODE when the augmented state determines its rate or an Itô diffusion when process fluctuations persist. The paper uses these branches for interacting-particle energy and binary mixing, respectively. [Paper, §§3.3, 4.2 and 4.3](https://arxiv.org/html/2605.30812v1#S3.SS3)

## 2. When to use

Use time-ordered frames with known elapsed times. Choose an intensive observable, such as mean energy per pair, whose magnitude does not scale with particle count. Each frame may contain a different number of particles. Keep features and labels attached to their particles. The augmented state should explain the evolution without needing earlier frames. Check that observed lags are short enough for the one-step Euler approximation. The stochastic fit also assumes positive definite covariance. [Paper, §§3.1 and 3.3](https://arxiv.org/html/2605.30812v1#S3.SS1)

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

| Situation | Use instead |
| --- | --- |
| Only independent frames with no time intervals | Use the set encoder for static density reconstruction. Collect timed pairs to learn the evolution. |
| Particle identity or temporal correspondences are themselves needed for prediction | Include the relevant history or persistent particle attributes in a model that uses them. |
| The observable is already a resolved stochastic state | Fit a transition law directly. Use DynGMA when the one-step Gaussian misses the shape of finite-lag increments. |
| Counts or density affect the dynamics even for the same normalized particle distribution | Include those quantities explicitly in the macroscopic state or as invariant inputs. Use held-out counts and densities to check the forecast. |
| The observable already resolves the deterministic dynamics | Fit a vector field directly. Use deterministic OnsagerNet when its energy structure describes the system. |
| Small changes in the observed microstates accompany large macroscopic changes, as in the stiff regime in §5 of the paper | Collect denser measurements of the microstate distribution or include features that resolve the macroscopic changes. Check whether the resulting closure can distinguish states with different futures. [Paper, §5](https://arxiv.org/html/2605.30812v1#S5) |

## 4. Algorithm

1. Split trajectories before fitting preprocessing. For a frame $X=(x_1,\dots,x_n)$, compute the retained observable $o=Q(X)$ using a permutation-invariant extractor. Learn an additional vector $h=\rho(\tfrac{1}{n}\sum_i\phi(x_i))$. The point map $\phi$ is shared across particles and $\rho$ acts on the pooled vector. A portable choice is $\phi(x)=\tanh(Wx+b)$ and $\rho(v)=Cv+d$, with $\tanh$ applied elementwise. Keep units and coordinate origins consistent. Equation (1) states the invariance condition. Appendix B.1 specifies mean pooling. With labels, the pinned mixing code applies the same encoder separately to each species and concatenates the embeddings for the dynamics fit. Keep species order fixed and ensure each required group has points. [Paper, Eq. (1) and Appendices A.4 and B.1](https://arxiv.org/html/2605.30812v1) · [Pinned species encoder](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/blob/754187d8486c785853cff1a9d42797731577e1db/mixing/train_nflow_arqs.py#L477-L499) · [Pinned state construction](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/blob/754187d8486c785853cff1a9d42797731577e1db/mixing/learn_sde/learn_mixing_dynamics.py#L65-L69)
2. In a $d$-dimensional particle-feature space, define the target density $q_X(y)=\frac{1}{n}\sum_i \mathcal{N}(y; x_i, \varepsilon^2 I)$, where $\varepsilon>0$ is the kernel standard deviation. Draw each reconstruction query by choosing $i$ uniformly and setting $y=x_i+\varepsilon\xi$ with independent standard normal entries in $\xi$. Write $\ell_i=-\|y-x_i\|^2/(2\varepsilon^2)$. With $L=\operatorname{logsumexp}_i(\ell_i)$, the log density is $\log q_X(y)=L-\log n-d\log(2\pi)/2-d\log\varepsilon$. Evaluate logsumexp with a shift by the largest $\ell_i$. For species-specific densities, use the count within each species. [Paper, Eq. (2)](https://arxiv.org/html/2605.30812v1#S3.SS2)
3. Train $\phi$, $\rho$ and a conditional density $p(y\mid h)$ on the reconstruction loss. Average $\log q_X(y)-\log p(y\mid h)$ over queries within each frame, then over frames. Draw and hold each query fixed for differentiation. Because $\log q_X(y)$ is independent of these parameters, minimizing mean $-\log p(y\mid h)$ gives the same gradient. In the pinned mixing code, score each species' queries with the shared decoder conditioned on that species' embedding $h_g$ and give both species equal weight. The CPU decoder is a conditional Gaussian. With $\mu=\mu(h)$, positive standard deviations $\sigma_j=\exp(\eta_j(h))$ and independent outputs, its negative log density is $\sum_j[\log(2\pi)/2+\log\sigma_j+(y_j-\mu_j)^2/(2\sigma_j^2)]$. This is an affine normalizing flow from independent unit normals. The published decoder uses a more expressive flow with conditional autoregressive spline layers. [Paper, Eq. (3) and Appendix B.2](https://arxiv.org/html/2605.30812v1) · [Pinned reconstruction loss](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/blob/754187d8486c785853cff1a9d42797731577e1db/mixing/train_nflow_arqs.py#L488-L515)
4. Freeze the encoder. For each pair encode the start and end as $z=[o,h]$ and $z'$ with the observable first. At elapsed time $\tau>0$, set $r=z+\tau g(z)-z'$.
   - **Deterministic.** Fit the drift $g$ by minimizing the mean of $\|r\|_2^2$ across pairs. Sum over state components. The per-pair derivative with respect to the drift output is $2\tau r$. Use the recorded lag for each pair. A fit to squared errors in rates would weight these endpoint errors by $1/\tau^2$.
   - **Stochastic.** Learn a noise factor $\Sigma(z)$ at the starting state and let $A=\Sigma\Sigma^\top$. Minimize the mean of $[d_z\log(2\pi\tau)+\log\det A+r^\top A^{-1}r/\tau]/2$, where $d_z$ is the state dimension. With a lower triangular factor $L=\Sigma$ of positive diagonal, solve $Lu=r$ and use $\log\det A=2\sum_i\log L_{ii}$ and $r^\top A^{-1}r=u^\top u$. [Paper, Eqs. (4)–(5) and Algorithm 1](https://arxiv.org/html/2605.30812v1#S3.SS3)
5. Encode the initial particle frame once. In the deterministic branch, advance $z\gets z+\tau g(z)$ at every forecast step. In the stochastic branch add $\sqrt{\tau}\Sigma(z)\xi$ using a fresh standard normal vector per step. Read the observable components at each forecast time. Compare predictions with held-out observations at matching horizons. [Paper, Algorithm 2](https://arxiv.org/html/2605.30812v1)

## 5. Parameters

| Parameter | Choice |
| --- | --- |
| Kernel width $\varepsilon$ | Use the scale of particle features. Larger $\varepsilon$ smooths fine structure. Smaller $\varepsilon$ asks the decoder to represent sharper modes. Inspect reconstructed densities and downstream forecasts at several widths. |
| Latent dimension | Start small. Check held-out predictions and whether past frames improve the forecasts at matched states and lags. |
| Species | Keep group order fixed and test independent reordering within every group. Handle absent groups explicitly before applying mean pooling. |
| Observation lag | Use the actual elapsed time. Check deterministic endpoint errors or stochastic one-step covariance when the available lags are shortened. |

## 6. Applying it to your own code

Use a shared point map and divide by each frame or species count. As written, mean pooling and the normalized target density preserve an empirical distribution when each particle is replicated equally. They can still distinguish different distributions. A new particle count can change the physical law, so validate transfer separately. For periodic positions, choose features or a density appropriate for the geometry before using the Euclidean Gaussian formulas.

The small reference uses scalar point clouds with closure $h=\beta\operatorname{mean}(2x)$. Its decoder uses mean $h$ and learns a common standard deviation $\sigma_{\mathrm{dec}}$. In stage I the Gaussian cross-entropy integrates exactly over the target mixture. For frame means $\mu_k$ and $m_k=\operatorname{mean}(2x)$, fit $\beta=\sum_k m_k\mu_k/\sum_k m_k^2$. Then $\sigma_{\mathrm{dec}}^2$ is the frame average of $(\mu_k-\beta m_k)^2+\operatorname{var}(X_k)+\varepsilon^2$, using population variance. The synthetic stochastic observable is the log of the population standard deviation. The deterministic example adds one to that value.

In stage II fit an affine drift by regressing each endpoint displacement on $\tau[1,z^\top]$. Use unit weights for deterministic least squares or weights $1/\tau$ for the constant-covariance stochastic likelihood. For the latter, estimate the covariance rate as the mean of $rr^\top/\tau$ and take its lower Cholesky factor. Use enough independent starting states to identify the affine coefficients.

For the energy observable in §4.2, let $u_{ij}=1-\|x_i-x_j\|_2$. Average $\log\cosh(4u_{ij})/4+0.1u_{ij}$ over the $n(n-1)/2$ pairs $i<j$. Stable evaluation uses $\log\cosh(v)=|v|+\log(1+\exp(-2|v|))-\log 2$, with `log1p` for the middle term. [Paper, Appendix A.3](https://arxiv.org/html/2605.30812v1) · [Pinned observable implementation](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/blob/754187d8486c785853cff1a9d42797731577e1db/interacting_particle/generate_dataset/generate_macro_obs_data.py)

Record `permutation-invariant-macrodynamics v0.2.0, Han et al. (2026)` when applying the skill.

## 7. Verification

**Step 1.** Implement the eight functions in `checks/cases.json` and export them from `port_adapter.py`. Run `python3 /path/to/permutation-invariant-macrodynamics/checks/check_port.py` from the adapter directory and show its output. The cases check species pooling, normalized densities, reconstruction derivatives, both transition losses and their drift derivatives, both forecast scores, and mean pair energy.

**Step 2.** Reindex each frame independently and check that the encoded state and forecast agree to numerical tolerance. Hold the innovations fixed for stochastic forecasts. Evaluate on unseen configurations and particle counts.

For stochastic forecasts, at each time and kernel scale $\lambda$ in $\{0.01, 0.05, 0.25, 1.25\}$, calculate $k_\lambda(u,v)=\exp(-\|u-v\|^2/(2\lambda^2))$. Take the mean kernel over all predicted pairs plus the mean over all observed pairs minus twice the mean over all predicted–observed pairs. Include self-pairs in the within-ensemble terms. Average over scales and forecast times. This is the biased squared MMD estimator, called MMD in the paper. Appendix A.2 averages over the $T$ forecast steps. The pinned evaluator also includes the shared initial frame. This contributes zero MMD in exact arithmetic and multiplies the forecast-only average by $T/(T+1)$. [Paper, Appendix A.2](https://arxiv.org/html/2605.30812v1) · [Pinned metric](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/blob/754187d8486c785853cff1a9d42797731577e1db/mixing/learn_sde/mmd.py) · [Pinned evaluator](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/blob/754187d8486c785853cff1a9d42797731577e1db/mixing/learn_sde/cmpt_mmd.py)

For deterministic forecasts, divide each trajectory's sum of squared observable errors over forecast times and coordinates by its sum of squared observed values. Average the ratios across trajectories. This is the paper's mean relative error (MRE). Omit the initial frame. For a trajectory with zero observed norm, report its root mean squared error over forecast times and coordinates separately. Average relative scores over trajectories with nonzero observed norm. The pinned ODE evaluator uses RK4 and scores only the first coordinate, the scaled energy. It includes the initial frame in the denominator and adds a small denominator offset. The checks use Appendix A.2's forecast-only convention. [Paper, Appendix A.2](https://arxiv.org/html/2605.30812v1) · [Pinned ODE evaluator](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/blob/754187d8486c785853cff1a9d42797731577e1db/interacting_particle/learn_ode/test_ode.py#L193-L215)

Both CPU examples fit shuffled four- and six-particle observations. The checks compare forecasts at nine and eleven particles with an observable-only fit. The cloud generator preserves the closure-relevant statistics by construction. The deterministic check uses exact samples from a linear ODE and verifies the pair-energy formula separately. The published interacting-particle forecast errors in Table 1 have not yet been reproduced here. [Paper, §4.2 and Table 1](https://arxiv.org/html/2605.30812v1#S4.SS2)

The pinned benchmark maps mean pair energy $E$ to $2(E-E_{\min})/(E_{\max}-E_{\min})-1$. It gets the extrema from the training dataset and reuses them on the test sets. To compare scores with the pinned evaluator, use this scaled energy because adding an offset changes MRE. The pinned trainer fits rates $(z'-z)/\tau$ with a constant time step that defaults to $0.002$. The pinned generator uses $0.02$. For the reference fit, use the actual elapsed time of each pair in the endpoint loss. [Pinned energy preprocessing](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/blob/754187d8486c785853cff1a9d42797731577e1db/interacting_particle/generate_dataset/generate_macro_obs_data.py#L121-L148) · [Pinned rate fit](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/blob/754187d8486c785853cff1a9d42797731577e1db/interacting_particle/learn_ode/train_example.py#L130-L135) · [Pinned trainer defaults](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/blob/754187d8486c785853cff1a9d42797731577e1db/interacting_particle/learn_ode/train_example.py#L250-L261) · [Pinned generator](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/blob/754187d8486c785853cff1a9d42797731577e1db/interacting_particle/generate_dataset/generate_simulation.py#L400-L415)

The pinned mixing pipeline fits two separate SDEs to $[R_{AB},h_A,h_B]$ and $[R_{BA},h_B,h_A]$ using state-dependent diagonal diffusion and the configured step 0.01. Its evaluator concatenates the two predicted mixing ratios before scoring them. The pinned reconstruction script imports local `models.py` and `utils/` files absent from the `mixing/` directory, so running it requires resolving those imports. [Pinned dynamics script](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/blob/754187d8486c785853cff1a9d42797731577e1db/mixing/learn_sde/learn_mixing_dynamics.py) · [Pinned configuration](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/blob/754187d8486c785853cff1a9d42797731577e1db/mixing/learn_sde/config/mixing_dynamics.yaml) · [Pinned mixing directory](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/tree/754187d8486c785853cff1a9d42797731577e1db/mixing)

The mixing setup check reproduces the published counts of 529 and 437. The pinned LAMMPS inputs specify boxes of size 32 × 32 and 32 × 26 and a square-lattice density parameter of 0.50. Dividing the finite-box counts by their areas gives number densities of about 0.517 and 0.525, respectively. **The reported Table 2 score of 0.00964 at the shifted count remains unverified.** [Paper, §4.3 and Table 2](https://arxiv.org/html/2605.30812v1#S4.SS3) · [Pinned shifted-count input](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/blob/754187d8486c785853cff1a9d42797731577e1db/mixing/generate_data/lmp_sim_files/sim_same_particle_number_diffN.in)

## 8. Failure signatures

| Symptom | Check |
| --- | --- |
| Reordering changes the closure | Inspect pointwise parameter sharing, species handling and pooling. |
| A forecast of an empirical-distribution observable changes under uniform particle replication | Check the per-group mean, the $1/n$ density factor and any intentional count feature. Pair observables that exclude self-pairs can change under replication. |
| Reconstruction looks good while observable forecasts retain systematic memory | Increase or change the closure representation and check the Markov assumption with past frames. |
| The covariance is singular | Inspect the state for redundant coordinates or use a likelihood on its actual support. |
| Deterministic forecasts drift or oscillate as the interval grows | Check the Euler step and compare rollouts at smaller steps. Check whether starting states with similar augmented coordinates still have distinct futures. |
| A port disagrees with the published distribution score | Check kernel widths, self-pairs, scale averaging and whether a square root was applied. Check whether the benchmark average includes the initial frame. |

## 9. Files and commands

Run `python3 examples/fit_clouds.py` or `python3 examples/fit_deterministic_clouds.py` in this skill directory. The shared numerical operations are in `reference/particle.py`. The fit examples use `reference/fit.py` and `reference/deterministic.py`.

Run `python3 checks/make_cases.py` to emit fixtures. Run `verify/check_cases.py`, `verify/check_fit.py`, `verify/check_deterministic.py` and `verify/check_mixing_setup.py` with Python 3 for offline evidence.

## 10. Sources

Z. Han, M. Chen and Q. Li, *Learning Permutation-invariant Macroscopic Dynamics*, ICML 2026, PMLR 306, 39655–39671. [Proceedings](https://proceedings.mlr.press/v306/han26f.html) · [Open manuscript](https://arxiv.org/abs/2605.30812v1) · [Pinned author implementation](https://github.com/MLDS-NUS/learn-permutation-invariant-macro/tree/754187d8486c785853cff1a9d42797731577e1db)
