Metadata-Version: 2.4
Name: So3krates-torch
Version: 0.4.0
Summary: PyTorch implementation of So3krates neural network potential for atomistic simulations
Author-email: Tobias Henkes <tobias.henkes@uni.lu>
Maintainer-email: Tobias Henkes <tobias.henkes@uni.lu>
License-Expression: MIT AND CC-BY-NC-4.0 AND Apache-2.0
Project-URL: homepage, https://github.com/TCPUniLU/So3krates-torch
Project-URL: repository, https://github.com/TCPUniLU/So3krates-torch
Project-URL: documentation, https://github.com/TCPUniLU/So3krates-torch#readme
Project-URL: issues, https://github.com/TCPUniLU/So3krates-torch/issues
Project-URL: Bug Reports, https://github.com/TCPUniLU/So3krates-torch/issues
Project-URL: Source Code, https://github.com/TCPUniLU/So3krates-torch
Keywords: machine-learning,molecular-dynamics,neural-networks,pytorch,atomistic-simulations,equivariant-networks,interatomic-potentials
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Chemistry
Classifier: Topic :: Scientific/Engineering :: Physics
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Operating System :: POSIX :: Linux
Classifier: Environment :: GPU :: NVIDIA CUDA
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE.md
License-File: NOTICE.md
License-File: licenses/LICENSE.CC-BY-NC-4.0
License-File: licenses/LICENSE.MACE-MIT
License-File: licenses/LICENSE.PYG-MIT
License-File: licenses/LICENSE.ROBUST-LOSS-APACHE-2.0
Requires-Dist: ase>=3.26.0
Requires-Dist: h5py>=3.14.0
Requires-Dist: matscipy>=0.8.0
Requires-Dist: numpy>=1.26.4
Requires-Dist: prettytable>=3.0.0
Requires-Dist: pydantic>=2.0
Requires-Dist: pyyaml>=6.0.2
Requires-Dist: torch>=2.6.0
Requires-Dist: torch-ema>=0.3.0
Requires-Dist: torch-geometric==2.7.0
Requires-Dist: torchmetrics>=1.0.0
Provides-Extra: dev
Requires-Dist: pre-commit; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Provides-Extra: pme
Requires-Dist: torch-pme>=0.5; extra == "pme"
Provides-Extra: slurm
Requires-Dist: python-hostlist; extra == "slurm"
Provides-Extra: jax
Requires-Dist: jax; extra == "jax"
Requires-Dist: flax; extra == "jax"
Requires-Dist: ml-collections; extra == "jax"
Provides-Extra: vis
Requires-Dist: matplotlib>=3.5.0; extra == "vis"
Requires-Dist: pandas>=1.5.0; extra == "vis"
Provides-Extra: nvalchemi
Requires-Dist: nvalchemi-toolkit[ase]<0.4,>=0.2; python_version >= "3.11" and extra == "nvalchemi"
Dynamic: license-file

# So3krates-torch

Implementation of the So3krates + SO3LR model in pytorch.

#### Installation

**From PyPI:**

1. activate your environment
2. `pip install so3krates-torch`
3. (Optional) PME electrostatics/dispersion support: `pip install "so3krates-torch[pme]"` (installs `torch-pme>=0.5`)
4. (Optional) GPU-native MD with NVAlchemi: `pip install "so3krates-torch[nvalchemi]"` (Python ≥ 3.11)

**From source (development):**

1. activate your environment
2. clone this repository
3. move to the clone repository
4. `pip install -r requirements.txt`
5. `pip install .`
6. (Optional) PME electrostatics/dispersion support: `pip install ".[pme]"` (installs `torch-pme>=0.5`)
7. (Optional) GPU-native MD with NVAlchemi: `pip install ".[nvalchemi]"` (Python ≥ 3.11)

Upgrading from 0.2.x? See the breaking changes in [CHANGELOG.md](CHANGELOG.md).

#### Implemented features:
1. ASE calculator for MD (including pre-trained SO3LR v1 and SO3LR tauri — see [Pretrained SO3LR Models](#pretrained-so3lr-models-ase-calculator) below)
2. GPU-native batched MD (NVT/NPT) with NVAlchemi: `torchkrates-md-nvalchemi` (see [below](#torchkrates-md-nvalchemi--gpu-native-md-with-nvalchemi))
3. Inference over ase readable datasets: `torchkrates-eval`
4. Error metrics over ase readable datasets: `torchkrates-metric`
5. Transforming pyTorch and JAX parameter formates: `torchkrates-jax2torch` or `torchkrates-torch2jax`, with a built-in JAX↔PyTorch parity check (for these you need to install jax, flax, and the `so3lr_dev` package (this repo's JAX v2 reference implementation))
6. Training: `torchkrates-train --config config.yaml` (see example), including:
   - multi-theory-level (multi-fidelity) training (`num_theory_levels`)
   - multi-head fine-tuning with data replay (`convert_to_multihead`, `replay_*`)
   - the SO3LR-tauri loss: fixed or adaptive robust loss, per-structure loss reduction, two-stage loss weights, Hirshfeld (a0) and C6 ratio losses
   - LoRA/DoRA/VeRA fine-tuning
7. SO3LR physics: ZBL or NHL repulsion, electrostatics, dispersion (Hirshfeld or C6 ratios), optional PME for electrostatics and dispersion
8. Data preprocessing: `torchkrates-preprocess`
9. HDF5 file merging: `torchkrates-merge`
10. LAMMPS model export: `torchkrates-create-lammps-model`
11. PME parameter tuning (electrostatics and dispersion): `torchkrates-tune-pme`
12. Multi-head ⇄ single-head conversion: `torchkrates-convert-heads`
13. *Experimental:* `torch.compile` for inference and MD (`--compile`; see [Experimental: torch.compile](#experimental-torchcompile))


> [!IMPORTANT]
> Number 4 means that you can transform the weights from this pytorch version into the JAX version and vice versa. Inference and training is much faster (*at least 1 order of magnitude at the moment*) in the JAX version. This implementation is mostly for prototyping and compatability with other packages.

---

## Pretrained SO3LR Models (ASE Calculator)

Bundled, converted checkpoints live under `src/so3krates_torch/pretrained/so3lr/`:

```
pretrained/so3lr/
├── v1/
│   ├── so3lr.pt              # state_dict
│   └── so3lr_settings.yaml   # ARCHITECTURE block used to rebuild the model
└── tauri/                    # released SO3LR tauri models (converted from so3lr_dev)
    ├── so3lr-tauri-{s,m,l}-2602.pt / ..._settings.yaml
    └── so3lr-tauri-{s,m,l}-2606.pt / ..._settings.yaml
```

Each `<stem>.pt` is a plain `torch.save`d `state_dict` (**not** a pickled whole-model object) with a sibling `<stem>_settings.yaml` holding the `ARCHITECTURE` block needed to reconstruct the model before its weights are loaded. The older pickled `pretrained/so3lr/so3lr.model` has been removed entirely — use one of the keywords below instead.

| Keyword | Checkpoint | Notes |
|---------|------------|-------|
| `v1` | `v1/so3lr.pt` | original SO3LR, single theory level |
| `tauri-s-2602`, `tauri-m-2602`, `tauri-l-2602` | `tauri/so3lr-tauri-{s,m,l}-2602.pt` | tauri generation 2602, 16 theory-level heads |
| `tauri-s-2606`, `tauri-m-2606`, `tauri-l-2606` | `tauri/so3lr-tauri-{s,m,l}-2606.pt` | tauri generation 2606 (newer; trained with `dispersion_energy_scale` 1.0), 16 theory-level heads |
| `v2-s`, `v2-m`, `v2-l` | same files as `tauri-{s,m,l}-2602` | older names, kept as aliases of the 2602 generation |

The tauri checkpoints were converted with `torchkrates-jax2torch --so3lr_dev_checkpoint {s,m,l} --so3lr_dev_generation {2602,2606}`; the converter's JAX↔Torch parity check passes for all six (energy within 6e-6 eV, force differences below 1e-5 eV/Å on its bundled example structure).

> [!WARNING]
> **License of the bundled weights.** The SO3LR tauri weights (`tauri-*` and the `v2-*` aliases) are licensed under [CC BY-NC 4.0](licenses/LICENSE.CC-BY-NC-4.0): non-commercial use only, with attribution. Models fine-tuned from them are adaptations and fall under the same license. The original SO3LR weights (`v1`) and the code are MIT. See [NOTICE.md](NOTICE.md) for details.

### `SO3LRCalculator` — ASE calculator

```python
from ase.build import molecule
from so3krates_torch.calculator.so3 import SO3LRCalculator

atoms = molecule("H2O")
atoms.calc = SO3LRCalculator(
    model="tauri-s-2606",  # any keyword from the table above
    theory_level=5,        # required for the tauri models (16 heads); so3lr_dev uses 5
    device="cpu",
    r_max_lr=12.0,
    dispersion_energy_cutoff_lr_damping=2.0,
)
print(atoms.get_potential_energy())
print(atoms.get_forces())
```

`model` is a required keyword selecting which bundled checkpoint to load. The remaining constructor keywords cover general calculator settings (`r_max_lr` (default `12.0`, long-range cutoff for electrostatics/dispersion), `dispersion_energy_cutoff_lr_damping` (default `2.0`, damping cutoff for the TS dispersion damping function), `compute_stress`, `device`, `energy_units_to_eV`, `length_units_to_A`, `default_dtype`, `charges_key`, `key_specification`, `theory_level` (required for the tauri models (`tauri-*`, and the `v2-*` aliases), which have 16 theory-level heads; `so3lr_dev` uses 5. The single-head `v1` model needs none)) plus PME electrostatics/dispersion (`use_pme`, `pme_smearing`, `pme_mesh_spacing`, `use_pme_dispersion`, `pme_dispersion_smearing`, `pme_dispersion_mesh_spacing` — all `None`/off by default; see [PME Electrostatics](#pme-electrostatics-particle-mesh-ewald) below for what each one does). For example, to enable PME on a periodic system:

```python
from ase.build import bulk
from so3krates_torch.calculator.so3 import SO3LRCalculator

atoms = bulk("NaCl", "rocksalt", a=5.64) * (2, 2, 2)
atoms.calc = SO3LRCalculator(
    model="v2-s",
    theory_level=5,
    device="cpu",
    use_pme=True,
    pme_smearing=1.18,
    pme_mesh_spacing=0.59,
)
print(atoms.get_potential_energy())
```

See [`examples/md/simple_md.py`](examples/md/simple_md.py) for a full MD example driven by `SO3LRCalculator`; it exposes `--so3lr_model` (any keyword from the table above) and `--use_pme` flags directly (e.g. `python examples/md/simple_md.py --so3lr --so3lr_model tauri-s-2606 --use_pme --device cpu`).

### `load_pretrained_so3lr` — for fine-tuning/scripting

For use cases that need the raw `torch.nn.Module` rather than an ASE calculator (e.g. fine-tuning), use `load_pretrained_so3lr` directly:

```python
from so3krates_torch.calculator.so3 import load_pretrained_so3lr

model = load_pretrained_so3lr(
    "v2-s",
    device="cpu",
    r_max_lr=12.0,
    dispersion_energy_cutoff_lr_damping=2.0,
)
```

Any extra keyword arguments are merged into the checkpoint's saved `ARCHITECTURE` settings before construction, e.g. to enable PME the same way as above (`use_pme=True, pme_smearing=..., pme_mesh_spacing=...`). See [`examples/finetuning/finetune_pretrained_so3lr.py`](examples/finetuning/finetune_pretrained_so3lr.py) for a full LoRA fine-tuning example built on this function:

```bash
python examples/finetuning/finetune_pretrained_so3lr.py --model v1
python examples/finetuning/finetune_pretrained_so3lr.py --model tauri-s-2606 --use_pme
```

To warm-start plain (non-LoRA) training from one of these checkpoints instead of fine-tuning, see the `pretrained_weights` option under [Pre-trained Models](#pre-trained-models) below, and its documented example in [`examples/training/train_settings_example.yaml`](examples/training/train_settings_example.yaml).

---

## CLI Reference

### `torchkrates-train` — Training

Train an SO3LR (or multi-head SO3LR) model from a YAML configuration file.

```bash
torchkrates-train --config config.yaml
```

| Flag | Description |
|------|-------------|
| `--config` | Path to the YAML training configuration file |
| `--dry-run` | Validates the config, builds the model, runs one forward pass, prints parameter count, then exits. Use this to check a config before submitting a long HPC job. |

See the **[Training Configuration](#training-configuration)** section below for detailed documentation of all configuration options.

---

### `torchkrates-preprocess` — Data Preprocessing

Convert atomic structure data (XYZ or raw HDF5) into preprocessed HDF5 files with precomputed neighbour lists for faster training.

```bash
# XYZ → preprocessed HDF5
torchkrates-preprocess --input data.xyz --output data.h5 --mode preprocessed --r-max 4.5

# XYZ → raw HDF5 (structures only, no neighbour lists)
torchkrates-preprocess --input data.xyz --output data.h5 --mode raw

# Raw HDF5 → preprocessed HDF5
torchkrates-preprocess --input raw.h5 --output preprocessed.h5 --mode preprocessed --r-max 4.5
```

| Flag | Description |
|------|-------------|
| `--input` | Input file path (`.xyz` or `.h5`/`.hdf5`) |
| `--output` | Output HDF5 file path |
| `--mode` | `raw` (structures only) or `preprocessed` (with neighbour lists) |
| `--r-max` | Short-range cutoff (required for `preprocessed` mode) |
| `--r-max-lr` | Long-range cutoff (optional) |
| `--energy-key` | Key for energy in the input file (default: `REF_energy`) |
| `--forces-key` | Key for forces (default: `REF_forces`) |
| `--stress-key` | Key for stress (default: `REF_stress`) |
| `--dipole-key` | Key for dipole (default: `REF_dipole`) |
| `--charges-key` | Key for charges (default: `REF_charges`) |
| `--hirshfeld-ratios-key` | Key for Hirshfeld (a0) ratios (default: `REF_hirsh_ratios`) |
| `--c6-ratios-key` | Key for C6 ratios (default: `REF_c6_ratios`; `c6_ratios` is accepted as fallback) |
| `--total-charge-key` | Key for the total charge in `atoms.info` (default: `total_charge`) |
| `--total-spin-key` | Key for the total spin in `atoms.info` (default: `total_spin`) |
| `--description` | Optional dataset description stored in the HDF5 metadata |
| `--dtype` | Data type: `float32` or `float64` (default: `float64`) |
| `--validate` | Validate the output file after creation |

---

### `torchkrates-merge` — HDF5 File Merging

Merge two or more HDF5 files (raw or preprocessed) into a single file. Both formats are supported; all inputs must be the same type. Raw files are merged with streaming writes to avoid loading everything into memory.

```bash
# Merge raw HDF5 files
torchkrates-merge --inputs train_a.h5 train_b.h5 --output train_merged.h5

# Merge preprocessed HDF5 files
torchkrates-merge --inputs part1.h5 part2.h5 part3.h5 --output all.h5

# With optional metadata and custom batch size
torchkrates-merge --inputs a.h5 b.h5 --output merged.h5 \
    --description "combined dataset" --batch-size 50000
```

| Flag | Description |
|------|-------------|
| `--inputs FILE [FILE ...]` | Two or more input HDF5 files to merge (must be the same format) |
| `--output FILE` | Output HDF5 file path |
| `--description TEXT` | Optional description stored in the merged file metadata (raw format only) |
| `--batch-size N` | Structures processed per write batch (raw format only, default: `100000`) |

---

### `torchkrates-create-lammps-model` — LAMMPS Model Export

> [!IMPORTANT]
> GPU-accelerated LAMMPS (Kokkos) must be built against the same CUDA and PyTorch version as the converted model.

Convert a trained SO3LR model to a format compatible with the LAMMPS ML-IAP interface.

```bash
torchkrates-create-lammps-model model.pt --elements Si O
```

| Flag | Description |
|------|-------------|
| `model_path` | Path to the trained `.pt` model file |
| `--elements` | Element symbols present in the simulation (must match LAMMPS `pair_coeff` type order) |
| `--head` | Head name for multi-head models (interactive selection if omitted) |
| `--dtype` | `float32` or `float64` (default: `float64`) |
| `--r-max-lr` | Override the long-range cutoff radius (Å). Only applicable to LR models. |
| `--electrostatic-energy-scale` | Override the electrostatic energy scaling factor. |
| `--dispersion-energy-scale` | Override the dispersion energy scaling factor. |
| `--dispersion-energy-cutoff-lr-damping` | Override the dispersion long-range damping cutoff. |

#### Output file

The converted model is saved as `<model_path>-mliap_lammps.pt` in the same directory as the input.

#### LAMMPS input script — pair style and pair_coeff

```lammps
pair_style mliap unified so3lr /path/to/model-mliap_lammps.pt
pair_coeff * * C H O
```

The `pair_style` line specifies the converted model file. The `pair_coeff` line maps LAMMPS atom types to elements: it must list exactly one element symbol per atom type defined in the data file, in the same order as the `Masses` block.

> [!IMPORTANT]
> Specifying the wrong number of elements — e.g. `C H N O` when the data file only has 3 atom types (C, H, O) — silently misassigns atom types and produces wrong energies and forces without any error message.

#### Running LAMMPS with GPU (Kokkos)

For compilation and general guidance, see the [NVIDIA blog post on AI-driven MD simulations](https://developer.nvidia.com/blog/enabling-scalable-ai-driven-molecular-dynamics-simulations/).

Example launch command for Kokkos GPU:

```bash
mpirun -np $num_gpus /path/to/lammps/build_cuda/lmp \
    -k on g $num_gpus \
    -sf kk \
    -pk kokkos newton on neigh half \
    -in prod.in
```

where `$num_gpus` is the number of GPU processes and `/path/to/lammps/build_cuda/lmp` is the Kokkos-enabled LAMMPS executable. The model auto-detects the GPU device on the first timestep.

---

### `torchkrates-convert-heads` — Multi-Head Conversion

Turn a trained SO3LR model into a multi-head model with the same backbone and N freshly initialised, independent energy output heads (e.g. as a starting point for ensemble fine-tuning), or keep one head of a multi-head model as a plain single-head model. Everything except the energy head (backbone weights, `r_max_lr`, dtype, long-range settings) is kept.

```bash
# Bundled model -> 4 untrained heads
torchkrates-convert-heads --model v1 --output so3lr_mh.model --to-multihead 4

# tauri models have 16 theory levels; level 5 is kept unless you pass --theory-level
torchkrates-convert-heads --model tauri-m-2606 --output tauri_mh.model --to-multihead 4

# Keep head 2 of a fine-tuned multi-head model
torchkrates-convert-heads --model finetuned.model --output head2.model --select-head 2
```

| Flag | Description |
|------|-------------|
| `--model` | Pickled model file (`torch.save(model)`, e.g. the `.model` written by training) or a bundled model name (`v1`, `tauri-m-2606`, ...) |
| `--output` | Output `.model` file |
| `--to-multihead N` | Make a multi-head model with N new heads (exactly one of `--to-multihead` / `--select-head`) |
| `--select-head K` | Keep head K (0-based) of a multi-head model |
| `--theory-level T` | Theory level to keep for multi-theory-level models such as tauri (default: `5`, so3lr_dev's level; only with `--to-multihead`) |
| `--seed` | Seed for the new heads' weights (default: `42`) |
| `--device` | Torch device (default: `cpu`) |
| `--force` | Overwrite an existing output file |

From Python: `to_multihead_model`, `to_single_head_model` and `select_theory_level` in `so3krates_torch.tools.multihead_utils`.

### `torchkrates-eval` — Inference

Run inference over an ASE-readable dataset.

```bash
torchkrates-eval --model_path my_model.model --data_path test_set.xyz
```

`--model_path` also accepts, in addition to the `.model`-file/directory form above:
- one of the bundled pretrained keywords directly (`v1`, `tauri-{s,m,l}-{2602,2606}`, or the aliases `v2-{s,m,l}`).
- a path ending in `.pt` with a sibling `<stem>_settings.yaml` (the same naming convention used by the bundled checkpoints under `pretrained/so3lr/{v1,tauri}/`) — this is how a checkpoint produced by `torchkrates-jax2torch --save_state_dict_path my_checkpoint.pt --save_settings_path my_checkpoint_settings.yaml` gets loaded here.

```bash
torchkrates-eval --model_path v1 --data_path my_data.xyz \
    --device cpu --dtype float32 --r_max_lr 12.0 \
    --dispersion_energy_cutoff_lr_damping 2.0 \
    --multispecies \
    --output_file results_v1.h5

torchkrates-eval --model_path my_checkpoint.pt \
    --data_path my_data.xyz --device cpu --dtype float32 \
    --r_max_lr 12.0 --dispersion_energy_cutoff_lr_damping 2.0 \
    --multispecies \
    --output_file results_my_checkpoint.h5
```

`--multispecies` is needed whenever the dataset's structures don't all share the same number of atoms (as above) — see the flag table below.

Models with several theory levels (the tauri models and the `v2-*` aliases) need an integer `theory_level` in each structure's `atoms.info` (so3lr_dev's default level is `5`). `torchkrates-eval` and `torchkrates-metric` have no flag to set it for the whole dataset yet.

| Flag | Default | Description |
|------|---------|-------------|
| `--model_path` | *required* | Path to a single `.model` file, a directory of `.model` files (use with `--ensemble_size N` for ensemble inference), a bundled pretrained keyword (`v1`, `tauri-*`, `v2-*`), or a `.pt` state_dict checkpoint with a sibling `<stem>_settings.yaml` |
| `--data_path` | *required* | ASE-readable dataset (xyz, extxyz, HDF5) |
| `--output_file` | `results.h5` | Output HDF5 file |
| `--ensemble_size` | `1` | Number of models to load from a directory |
| `--device` | `cuda` | `cuda` or `cpu` |
| `--batch_size` | `5` | Structures per batch |
| `--dtype` | `float32` | `float32` or `float64` |
| `--multihead_model` | `False` | Enable multi-head model support |
| `--multispecies` | `False` | Required when the dataset's structures don't all share the same atom count (allows batches/results to be ragged instead of stacked into one array) |
| `--compute_dipole` | `False` | Compute dipole predictions |
| `--compute_stress` | `False` | Compute stress predictions |
| `--compute_hirshfeld` | `False` | Compute Hirshfeld ratio predictions |
| `--compute_c6_ratios` | `False` | Compute C6 ratio predictions (needs a model with `c6_ratios_bool: true`, i.e. SO3LR-tauri) |
| `--compute_partial_charges` | `False` | Compute partial charge predictions |
| `--energy_key` | `REF_energy` | Key for reference energies in the dataset |
| `--forces_key` | `REF_forces` | Key for reference forces |
| `--dipole_key` | `REF_dipoles` | Key for reference dipoles |
| `--charges_key` | `REF_charges` | Key for reference partial charges |
| `--hirshfeld_key` | `REF_hirsh_ratios` | Key for reference Hirshfeld ratios |
| `--c6_key` | `REF_c6_ratios` | Key for reference C6 ratios |
| `--total_charge_key` | `charge` | Key for total charge |
| `--total_spin_key` | `total_spin` | Key for total spin |
| `--stress_key` | `REF_stress` | Key for reference stress |
| `--virials_key` | `REF_virials` | Key for reference virials |
| `--head_key` | `head` | `atoms.info` key holding each structure's head name (multi-head models) |
| `--model_type` | `so3lr` | `so3lr` or `so3krates` |
| `--output_prefix` | `SO3` | Prefix for predicted properties in `.xyz` output (`SO3_energy`, `SO3_forces`, …) |
| `--compile` | `False` | *Experimental.* `torch.compile` the model before evaluation (see [Experimental: torch.compile](#experimental-torchcompile)) |
| `--fullgraph` / `--no-fullgraph` | `True` on CUDA, else `False` | `fullgraph` argument to `torch.compile` when `--compile` is set |
| `--return_att` | `False` | Save per-layer attention scores (HDF5 output, group `att_scores`) |
| `--return_inv_descriptors` | `False` | Save invariant (scalar) per-atom descriptors |
| `--return_eqv_descriptors` | `False` | Save equivariant (spherical-harmonic) per-atom descriptors |
| `--return_mean_inv_descriptors` | `False` | Save per-structure means of the invariant descriptors |
| `--return_mean_eqv_descriptors` | `False` | Save per-structure means of the equivariant descriptors |
| `--mean_descriptors_only` | `False` | Write only the mean descriptors, to an uncompressed `.npz` next to `--output_file`, and skip energies/forces. Needs one of the two `--return_mean_*` flags |

---

### `torchkrates-md-nvalchemi` — GPU-native MD with NVAlchemi

Run NVT/NPT molecular dynamics directly on GPU using [NVAlchemi](https://github.com/NVIDIA/nvalchemi)'s integrators and native cell-list neighbor search, without going through LAMMPS. Requires **Python ≥ 3.11** and the `nvalchemi` extra:

```bash
pip install ".[nvalchemi]"
```

This pins `nvalchemi-toolkit[ase]>=0.2,<0.4`; the wrapper (`so3krates_torch.calculator.nvalchemi_so3`) targets the 0.2/0.3 API (the test suite passes on both, on CPU) and is not expected to work with 0.1.x.

NVT example:

```bash
torchkrates-md-nvalchemi \
    --model model.pt \
    --atoms NaCl.xyz \
    --ensemble nvt \
    --temperature 300 \
    --steps 10000
```

NPT example (requires a periodic structure file, e.g. extended-XYZ with a `Lattice=` header, POSCAR, or CIF):

```bash
torchkrates-md-nvalchemi \
    --model model.pt \
    --atoms NaCl.xyz \
    --ensemble npt \
    --temperature 300 \
    --pressure 1.0 \
    --steps 10000
```

| Flag | Default | Description |
|------|---------|-------------|
| `--model` | *required* | Path to a trained model (`.pt`) |
| `--atoms` | *required* | ASE-readable input structure |
| `--index` | `-1` | ASE frame selection; `-1` runs the last frame, `:` runs every frame as an independent system in one batch |
| `--ensemble` | `nvt` | `nvt` (Langevin) or `npt` (MTK barostat) |
| `--temperature` | `300.0` | Temperature [K] |
| `--pressure` | `1.0` | Pressure [bar], NPT only |
| `--dt` | `0.5` | Time step [fs] |
| `--steps` | `10000` | Number of MD steps |
| `--skin` | `0.5` | Verlet skin [Å] for the GPU-native neighbor list |
| `--electrostatics` | `model` | `model`, `nvalchemi`, or `none` (see below) |
| `--pressure-coupling` | `isotropic` | `isotropic`, `anisotropic`, or `triclinic` (NPT only) |
| `--r-max-lr` (alias `--r_max_lr`) | `12.0` | Long-range cutoff [Å] for models with long-range terms (SO3LR's inference default, as in `SO3LRCalculator`). It replaces the stored value (none for `v1`, 1000 for the tauri models); a warning is printed when it replaces a finite trained cutoff, so pass the trained value to keep it |
| `--dispersion-energy-cutoff-lr-damping` | model's own, else `2.0` | Dispersion damping width [Å]; the model's stored value wins, `2.0` only fills in a missing one (`v1`) |
| `--theory-level` | `5` | Theory-level head of multi-head models (the tauri models have 16; `5` is so3lr_dev's default and is announced at start-up). Ignored by single-head models |
| `--model-pme` | off | Use the model's own PME electrostatics (`use_pme`, torch-pme; bundled keywords and `.pt` checkpoints only, periodic cells only; see below) |
| `--model-pme-smearing`, `--model-pme-mesh-spacing` | `r_max / 5`, `smearing / 2` | Ewald width and FFT spacing [Å] for `--model-pme` |
| `--model-pme-dispersion` | off | Add the model's PME dispersion k-space term (`use_pme_dispersion`) |
| `--model-pme-dispersion-smearing`, `--model-pme-dispersion-mesh-spacing` | `r_max_lr / 5`, `smearing / 2` | Width and spacing [Å] for `--model-pme-dispersion` |
| `--pme-alpha` | derived | Ewald splitting [Å⁻¹] for `--electrostatics nvalchemi` (see below) |
| `--pme-mesh-dimensions NX NY NZ` | NVAlchemi's estimate | FFT grid for `--electrostatics nvalchemi` (see below) |
| `--pme-spline-order` | `4` | B-spline order for `--electrostatics nvalchemi` |
| `--pme-accuracy` | `1e-6` | Target accuracy; sets the derived `--pme-alpha` |
| `--skip-vel-init` | `False` | Keep the velocities already stored in the structure file instead of (re-)sampling Maxwell-Boltzmann at `--temperature` |
| `--compile` | `False` | *Experimental.* `torch.compile` the inner model; raises on CPU for long-range models (unsupported Inductor lowering). See [Experimental: torch.compile](#experimental-torchcompile) |
| `--no-compile-fullgraph` | `False` | With `--compile`, allow graph breaks (`fullgraph=False`) instead of the CUDA default `fullgraph=True`; slower to optimise but tolerates constructs Dynamo cannot trace. Currently needed on CUDA with PyTorch 2.15 |
| `--seed` | `42` | Langevin RNG seed (NVT only) |
| `--friction` | `1e-2` | Langevin friction coefficient [1/fs] (NVT only) |
| `--thermostat-time` | `100 * dt` | NPT thermostat time constant [fs] (LAMMPS `tdamp` convention) |
| `--barostat-time` | `1000 * dt` | NPT barostat time constant [fs] (LAMMPS `pdamp` convention) |
| `--log-file` | `md_log.csv` | Output CSV log path |
| `--log-freq` | `100` | Log every N steps |

**Multi-head models.** A model with several independent energy output heads (`MultiHeadSO3LR`, from `convert_to_multihead`, saved by training as a pickled `.model`) runs on the mean over heads of energy, forces and stress, the same as `MultiHeadSO3LRCalculator`. The CSV log then has two extra columns with the spread over heads, a measure of the model's uncertainty:

- `energy_std_eV`: standard deviation of the per-head energies [eV];
- `force_std_max_eV_A`: per atom, the root-mean-square deviation of the head forces from their mean; the largest value in each structure [eV/Å]. It is `nan` with `--electrostatics nvalchemi`, where the model only returns energies and the forces come from the summed pipeline energy.

Forces for all heads come from a single vectorised backward pass (as in the ASE calculator), which costs more than a single-head model's. `--compile` is refused for these models. In Python, `find_so3lr_wrapper(model).head_results` (from `so3krates_torch.calculator.nvalchemi_so3`) holds the per-head values of the last evaluation: `energies`, `energy_var`, `forces_comm` and `stress_var`, named as in the ASE calculator's results. Multi-theory-level models such as tauri are a different mechanism and use `--theory-level`.

**Running a bundled pre-trained model.** `--model` takes a bundled keyword (`v1`, `tauri-{s,m,l}-{2602,2606}`, see [Pretrained SO3LR Models](#pretrained-so3lr-models-ase-calculator)), a `<stem>.pt` state_dict with a sibling `<stem>_settings.yaml`, or a pickled `.model`. The long-range cutoff defaults to 12.0 Å and the dispersion damping to 2.0 Å when the model stores none, the same values `SO3LRCalculator` uses, so NPT on a periodic cell needs no extra flags:

```bash
torchkrates-md-nvalchemi \
    --model tauri-s-2606 \
    --atoms my_cell.xyz \
    --ensemble npt --temperature 300 --pressure 1.0 \
    --steps 10000 --log-freq 100 \
    --device cuda
```

The multi-head tauri models run at theory level 5 unless you pass `--theory-level N`. Models trained with their own `r_max_lr` keep working: the default replaces the stored cutoff, with a warning, so give `--r-max-lr <trained value>` for them.

**The model's own PME.** `--model-pme` (electrostatics) and `--model-pme-dispersion` switch on the PME terms built into SO3LR: a real-space residual plus a torch-pme k-space term, which extends the trained `erf(r/σ)/r` electrostatics to all periodic images instead of cutting it off at the long-range cutoff. They work on bundled keywords and `.pt` checkpoints, need a periodic cell and `pip install ".[pme]"`, and cannot be combined with `--electrostatics nvalchemi` or `none`. They are not NVAlchemi's own PME (`--electrostatics nvalchemi`, the `--pme-*` options), which computes the full `1/r` Coulomb energy and is a different model.

```bash
torchkrates-md-nvalchemi --model tauri-s-2606 --atoms my_cell.xyz --ensemble npt \
    --model-pme --model-pme-smearing 1.18 --model-pme-mesh-spacing 0.59 \
    --model-pme-dispersion
```

A larger cutoff adds neighbor pairs (cost) and more of the long-range tail.

**Electrostatics semantics.** `--electrostatics` selects which long-range Coulomb term is active, and the two non-`none` options are *different, non-interchangeable* electrostatics models:

- `model` (default, **recommended**): the model computes its own electrostatics exactly as trained — damped real-space erf-Coulomb (`use_pme: false`) or the model's own torch-pme (`use_pme: true`). This is the validated path.
- `nvalchemi`: the short-range model instead emits partial charges only, and NVAlchemi's GPU-native PME (full Ewald) supplies the Coulomb energy from those charges. Only meaningful for a model trained with `use_pme: true`, and even then it does **not** reproduce the model's own torch-pme energy numerically — it is a separate backend. Requires a periodic cell (molecules exit with an error). The short-range model and PME run as one autograd pipeline, so forces include the response of the charges to the geometry (`dq/dr`) and the NPT stress includes the Coulomb virial. Checked on CPU against finite differences (forces), the strain derivative of the energy (all six stress components, with geometry-dependent charges) and the analytical Madelung energy of NaCl. **Not yet validated:** GPU runs, and long NPT or NVE runs (see the cluster checklist in the pull request).
  - **Ewald `alpha`.** By default (`--pme-alpha` not given) `alpha = sqrt(-ln(accuracy)) / r_max_lr` (0.31 Å⁻¹ at SO3LR's 12 Å cutoff, 0.62 at 6 Å), so the real-space sum is converged for any cell size. This deliberately replaces NVAlchemi's own estimate, which ignores the cutoff and `--pme-accuracy` and shrinks like N^(-1/6). Relative error of the NaCl Madelung energy (±1 charges, CPU):

    | cutoff | atoms | NVAlchemi auto `alpha` | derived `alpha` |
    |---|---|---|---|
    | 12 Å | 64 | 1e-7 | 2e-7 |
    | 12 Å | 512 | 3e-4 | 2e-7 |
    | 12 Å | 4096 | 1.5e-2 | 4e-7 |
    | 6 Å | 64 | 1.9e-2 | 1.5e-5 |
    | 6 Å | 4096 | 0.34 | 2.6e-4 |

    An explicit `--pme-alpha` is used as given, with a warning if `erfc(alpha · cutoff)` exceeds ten times `--pme-accuracy` (the real-space truncation error). By default NVAlchemi sizes the reciprocal FFT mesh itself, from an accuracy-based estimate that does not see a large `alpha`, so very large alphas lose a little reciprocal accuracy on big cells (the 6 Å row).
  - **`--pme-mesh-dimensions NX NY NZ`** sets the FFT grid points per cell axis (charges are spread onto this grid with B-splines of order `--pme-spline-order`, transformed, and the Coulomb kernel applied on it). A finer grid makes the reciprocal sum more accurate at roughly `NX·NY·NZ·log(NX·NY·NZ)` cost; in a 64-atom NaCl cell a 16³ grid and a 48³ grid differed by 0.17 eV. The grid is fixed, so under NPT the spacing `L/N` follows the cell, and a batch of different cells shares one grid. nvalchemi-toolkit 0.2.0 has no working mesh-*spacing* option (it is stored and never used), so this is the only mesh control.
  - `alpha` is the same for every graph in a batch, so the per-batch averaging NVAlchemi applies to its auto estimate does not occur.

  Use `model` unless you specifically need NVAlchemi-native PME.
- `none`: long-range electrostatics disabled entirely.

**Stress and pressure convention.** The model emits stress in the ASE convention (tensile-positive Cauchy stress); nvalchemi-toolkit 0.2 uses the same convention, so it is passed through unchanged. The reported pressure is `P = N kB T / V − tr(σ)/3`, matching ASE and LAMMPS's `thermo press` so the two engines can be compared directly at the same configuration.

**Charge and spin.** Total charge is read from `atoms.info["charge"]` (an integer, the same key `TorchkratesCalculator` uses); total spin from `atoms.info["total_spin"]` (the total spin *S*, not the multiplicity — again the calculator's key), stored as the `AtomicData` `spin` field. Both default to 0 when absent. (Programmatic users building `AtomicData.from_atoms` themselves must set `spin` explicitly, since nvalchemi does not read it from ASE; `atoms_to_data` in the CLI module does.)

**Logged quantities.** The CSV log always has energy, fmax, temperature and timing; `volume_A3`/`density_g_cm3` are added for periodic structures and `pressure_bar` for NPT. NVT runs request only energy and forces from the model (no stress). All frames selected with `--index` must be either periodic or non-periodic.

See `examples/md/nvalchemi_md.py` for the equivalent programmatic API, including how to configure NVAlchemi-native PME via `build_nvalchemi_pme_model(...)`.

---

### `torchkrates-metric` — Error Metrics

Compute error metrics over an ASE-readable dataset. Prints a table with MAE and RMSE per atom for each property.

```bash
torchkrates-metric --models my_model.model --data test_set.xyz
```

`--models` accepts the same two additional forms as `torchkrates-eval`'s `--model_path` above (a pretrained keyword, or a `.pt` + sibling `<stem>_settings.yaml`), on top of the original `.model`-file/directory form:

```bash
torchkrates-metric --models v1 --data test_set.xyz \
    --device cpu --r_max_lr 12.0 \
    --dispersion_energy_cutoff_lr_damping 2.0 \
    --batch_size 1 --output_args energy forces

torchkrates-metric --models my_checkpoint.pt --data test_set.xyz \
    --device cpu --r_max_lr 12.0 \
    --dispersion_energy_cutoff_lr_damping 2.0 \
    --batch_size 1 --output_args energy forces
```

Note there is no `--multispecies` flag here (unlike `torchkrates-eval`); use `--batch_size 1` instead if the dataset's structures don't all share the same atom count.

| Flag | Default | Description |
|------|---------|-------------|
| `--models` | *required* | Path to a model file or a directory of model files, a bundled pretrained keyword (`v1`, `tauri-*`, `v2-*`), or a `.pt` state_dict checkpoint with a sibling `<stem>_settings.yaml` |
| `--data` | *required* | Dataset path (must contain reference values) |
| `--output_args` | `energy forces` | Properties to evaluate. Can include `stress`, `virials`, `dipole`, `hirshfeld_ratios`, `c6_ratios`. |
| `--batch_size` | `16` | Structures per batch |
| `--device` | `cpu` | `cuda` or `cpu` |
| `--save` | `./` | Directory for output files |
| `--results_file` | `ensemble_test_results.npz` | `.npz` file with raw error arrays |
| `--r_max_lr` | `None` | Long-range cutoff when model uses electrostatics/dispersion |
| `--multihead_model` | `False` | Enable multi-head model support |
| `--multihead_return_mean` | `False` | Return mean prediction across heads |
| `--energy_key` | `REF_energy` | Key for reference energies |
| `--forces_key` | `REF_forces` | Key for reference forces |
| `--dipole_key` | `REF_dipoles` | Key for reference dipoles |
| `--charges_key` | `REF_charges` | Key for reference partial charges |
| `--hirshfeld_key` | `REF_hirsh_ratios` | Key for reference Hirshfeld ratios |
| `--c6_key` | `REF_c6_ratios` | Key for reference C6 ratios |
| `--total_charge_key` | `charge` | Key for total charge |
| `--total_spin_key` | `total_spin` | Key for total spin |
| `--stress_key` | `REF_stress` | Key for reference stress |
| `--virials_key` | `REF_virials` | Key for reference virials |
| `--head_key` | `head` | `atoms.info` key holding each structure's head name (multi-head models) |
| `--head_name` | `head` | Head name assigned to the loaded structures |
| `--log_file` | `test_ensemble.log` | Log file path |
| `--return_predictions` | `False` | Keep the energy and force predictions in the returned metrics. Parsed as `type=bool`, so any non-empty value (even `False`) turns it on; omit the flag to keep it off |

#### End-to-End Workflow

```bash
# Validate config before submitting a long training job
torchkrates-train --config config.yaml --dry-run

# Run inference on a test set
torchkrates-eval \
  --model_path my_model.model \
  --data_path test_set.xyz \
  --output_file predictions.h5

# Compute error metrics
torchkrates-metric \
  --models my_model.model \
  --data test_set.xyz \
  --output_args energy forces
```

### `torchkrates-tune-pme` — PME Parameter Tuning

Find optimal PME parameters (`pme_smearing`, `pme_mesh_spacing`) for a given dataset and SR cutoff. Runs `torchpme.tuning.tune_pme()` on a representative sample of training structures and reports the median values. With `--tune_dispersion`, also scans for optimal PME dispersion parameters (`pme_dispersion_smearing`, `pme_dispersion_mesh_spacing`) by comparing coarser candidates against a tight-PME reference on the same structures. Requires `torch-pme` and `matscipy` to be installed.

```bash
torchkrates-tune-pme \
    --data_path train_data.h5 \
    --r_max 6.0 \
    --n_samples 50 \
    --update_config config.yaml

# Also tune PME dispersion parameters
torchkrates-tune-pme \
    --data_path train_data.h5 \
    --r_max 6.0 \
    --r_max_lr 12.0 \
    --tune_dispersion \
    --update_config config.yaml
```

| Flag | Default | Description |
|------|---------|-------------|
| `--data_path` | *required* | Training dataset (`.xyz`, `.extxyz`, `.h5`/`.hdf5`) |
| `--r_max` | *required* | SR cutoff radius in Å — must match the model's `r_max` |
| `--n_samples` | `50` | Maximum number of periodic structures to use for tuning |
| `--accuracy` | `1e-3` | Target accuracy for the PME error bound |
| `--charges_key` | `None` | Key in `atoms.arrays` for partial charges (default: unit charges) |
| `--device` | `cpu` | Device for torch tensors |
| `--dtype` | `float64` | `float32` or `float64` |
| `--update_config` | `None` | If given, write the tuned parameters to this YAML config |
| `--r_max_lr` | `None` | Long-range cutoff radius in Å. Required when `--tune_dispersion` is given. |
| `--tune_dispersion` | `False` | Also scan PME dispersion parameters (`pme_dispersion_smearing`, `pme_dispersion_mesh_spacing`) against a tight-PME reference. |
| `--dispersion_accuracy` | `1e-3` | Target accuracy (eV/atom) for the dispersion parameter scan. Picks the coarsest grid point within this threshold. |

Example output:
```
PME tuning results (median over structures):
  Electrostatics:
    pme_smearing:     1.1842 Å
    pme_mesh_spacing: 0.5921 Å

  Dispersion (C6, scanned vs tight-PME reference):
    pme_dispersion_smearing:     2.4000 Å
    pme_dispersion_mesh_spacing: 1.2000 Å
```

---

### `torchkrates-jax2torch` / `torchkrates-torch2jax` — Weight Conversion

Convert model weights between the PyTorch and JAX implementations. The `--check_parity` default-on path (see below) and the general JAX-model-building path used for conversion require `jax`, `flax`, and the `so3lr_dev` package (this repo's JAX v2 reference implementation) to be installed — they no longer need `mlff`.

**JAX to PyTorch:**

```bash
torchkrates-jax2torch \
    --path_to_params params.pkl \
    --path_to_hyperparams hyperparameters.json \
    --save_model_path so3lr_torch.model
```

This writes a loadable torch `SO3LR` model (via `torch.save`) to `--save_model_path`.

Instead of `--path_to_params`/`--path_to_hyperparams`, you can point at one of the bundled `so3lr_dev` checkpoints (`so3lr-tauri-{s,m,l}-{2602,2606}`) by size via `--so3lr_dev_checkpoint {s,m,l}` and, optionally, generation via `--so3lr_dev_generation {2602,2606}` (default `2606`; requires `so3lr_dev` to be installed):

```bash
torchkrates-jax2torch \
    --so3lr_dev_checkpoint s \
    --save_model_path so3lr_s_torch.model
```

**PyTorch to JAX:**

```bash
torchkrates-torch2jax \
    --path_to_state_dict checkpoint.pt \
    --path_to_hyperparams config.yaml \
    --save_settings_path ./jax_settings \
    --save_params_path ./jax_params
```

This writes `hyperparameters.json` and `params.pkl` into the two given directories, matching mlff's expected JAX checkpoint layout.

**Precision:** `--dtype float32` rounds the weights to float32 in the saved file, which costs about 4e-6 eV in total energy even when you later evaluate in float64. For parity work convert with `--dtype float64`.

**Parity check:** by default, both CLIs verify after conversion that the JAX and PyTorch model representations produce the same energy/forces on a real structure (the bundled `tests/data/aqm_small.xyz` unless `--parity_structure` is given). The converted model/params are saved regardless of the check's outcome, but the CLI exits with status `1` if the check fails, so the failure isn't silently missed.

| Flag | Default | Description |
|------|---------|-------------|
| `--check_parity` / `--no-check_parity` | `True` | After conversion, verify the two model representations agree on a real structure's energy/forces. |
| `--parity_structure` | bundled `aqm_small.xyz` | ASE-readable structure file to check parity on. |
| `--parity_atol` | `1e-5` | Absolute tolerance for the parity check. |
| `--parity_rtol` | `1e-4` | Relative tolerance for the parity check. |
| `--trainable_rbf` | `False` | The model has trainable radial-basis centres and widths; their parameters are converted too. |
| `--use_defined_shifts` | `False` | `jax2torch` only: take the per-element energy shifts from the JAX config (`data.energy_shifts`). `torch2jax` accepts the flag but ignores it. |

The check behind these flags is `so3krates_torch.tools.model_parity.check_model_parity`. Besides energy and forces it can also compare the stress (`compare_stress=True`, periodic structures only), the partial charges, dipole, Hirshfeld and C6 ratios (`compare_observables=(...)`), and any theory-level head (`theory_level=<int>`; the default is so3lr_dev's level 5). See `src/so3krates_torch/tests/test_v2_parity.py` for the tolerances the test suite uses.

---

## Experimental: torch.compile

`torchkrates-eval --compile` and `torchkrates-md-nvalchemi --compile` wrap the model in `torch.compile(dynamic=True)`. This is **experimental and not recommended for production runs yet**; use the eager default.

- **No measured speedup.** Compilation adds roughly 30–60 s to the first step, and a steady-state speedup over eager on GPU has not been measured yet.
- **`fullgraph=True` (the CUDA default) fails with PyTorch 2.15**, for forces alone (NVT) and with stress (NPT). Dynamo rejects `torch.autograd.grad` inside the compiled region and the strain tensor created there. Pass `--no-compile-fullgraph` (MD) or `--no-fullgraph` (eval) to allow graph breaks; that path matched eager energies, forces and stress in a CPU check with the `aot_eager` backend.
- **CPU:** long-range SO3LR models are refused, because PyTorch's Inductor CPU backend crashes on the ZBL/electrostatics/dispersion scatter operations. Short-range-only models compile on CPU.
- **NVAlchemi PME** (`--electrostatics nvalchemi`) runs outside the compiled module.

---

## Training Configuration

Training is configured via a YAML file with four sections: `GENERAL`, `ARCHITECTURE`, `TRAINING`, and `MISC`. Launch training with:

```bash
torchkrates-train --config config.yaml
```

A full example is provided in [examples/training/train_settings_example.yaml](examples/training/train_settings_example.yaml).


### Model Architecture (`ARCHITECTURE`)

These settings define the SO3LR neural network architecture.

#### Core Transformer

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `degrees` | `list[int]` | *required* | Spherical harmonic degrees included in the equivariant features, e.g. `[1,2,3,4]`. Higher degrees capture more angular information but increase cost. |
| `num_features` | `int` | `128` | Hidden feature dimension of invariant and equivariant representations. |
| `num_heads` | `int` | `4` | Number of attention heads in each Euclidean transformer layer. |
| `num_layers` | `int` | `3` | Number of stacked Euclidean transformer layers. |
| `num_radial_basis_fn` | `int` | `32` | Number of radial basis functions used to expand interatomic distances. |
| `energy_regression_dim` | `int` | `128` | Hidden dimension of the MLP in the atomic energy output head. |
| `input_convention` | `str` | `"positions"` | Convention for atomic positions in the data. Options: `positions` (Cartesian coordinates). |
| `layers_behave_like_identity_fn_at_init` | `bool` | `False` | JAX option kept for config compatibility; `true` is not implemented and raises. |
| `output_is_zero_at_init` | `bool` | `False` | JAX option kept for config compatibility; `true` is not implemented and raises. |

#### Cutoffs and Basis Functions

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `r_max` | `float` | `4.5` | Short-range cutoff radius in Angstrom. Atoms beyond this distance do not interact through the neural network. |
| `r_max_lr` | `float` | `None` | Long-range cutoff for electrostatics and dispersion. Required when `electrostatic_energy_bool: true` (unless `use_pme: true`) or `dispersion_energy_bool: true`. |
| `radial_basis_fn` | `str` | `"bernstein"` | Radial basis function type. Options: `bernstein`, `gaussian`, `bessel`. |
| `cutoff_fn` | `str` | `"cosine"` | Envelope function that smoothly decays interactions to zero at the cutoff. Options: `cosine`, `phys`, `polynomial`, `exponential`. |
| `trainable_rbf` | `bool` | `False` | Whether radial basis function parameters are trainable. |

#### Activation Functions

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `activation_fn` | `str` | `"silu"` | Activation function in transformer layers. Options: `silu`, `relu`, `gelu`, `tanh`, `identity`. |
| `energy_activation_fn` | `str` | `"silu"` | Activation function in the energy output head MLP. Same options as above. |
| `qk_non_linearity` | `str` | `"identity"` | Non-linearity applied to query and key projections in attention. `identity` means linear attention. |

#### Normalization and Residual Connections

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `message_normalization` | `str` | `"avg_num_neighbors"` | How messages are normalized after aggregation. Options: `avg_num_neighbors` (divide by mean neighbor count), `sqrt_num_features`, `identity`. |
| `layer_normalization_1` | `bool` | `False` | Apply layer normalization after the first MLP in each transformer layer. |
| `layer_normalization_2` | `bool` | `False` | Apply layer normalization after the second MLP in each transformer layer. |
| `residual_mlp_1` | `bool` | `False` | Add a residual connection around the first MLP. |
| `residual_mlp_2` | `bool` | `False` | Add a residual connection around the second MLP. |
| `use_rms_norm` | `bool` | `False` | Use RMSNorm without a learnable scale instead of LayerNorm for `layer_normalization_1`/`_2` (SO3LR-tauri). |
| `qk_norm` | `bool` | `False` | RMS-normalise queries and keys (no parameters) before the attention product (SO3LR-tauri). |
| `use_residual_scalars` | `bool` | `False` | Before every layer, mix the initial embedding into the invariant features with learnable per-layer scalars (init 1.0 for the features, 0.1 for the embedding) (SO3LR-tauri). |
| `compute_avg_num_neighbors` | `bool` | `True` | Compute the average number of neighbors from the training data (used for `avg_num_neighbors` normalization). |

#### Embeddings and Energy Output

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `use_charge_embed` | `bool` | `False` | Include total charge as an input embedding. Required when training on charged systems. |
| `use_spin_embed` | `bool` | `False` | Include total spin as an input embedding. Required for spin-polarized systems. |
| `energy_learn_atomic_type_shifts` | `bool` | `False` | Learn per-element energy shifts as trainable parameters. When `False`, shifts are fixed from the training data E0s. |
| `energy_learn_atomic_type_scales` | `bool` | `False` | Learn per-element energy scales as trainable parameters. |
| `atomic_energy_shifts` | `dict` | `None` | Manually specify per-element energy shifts, e.g. `{1: -13.6, 6: -1029.5}`. Overrides the values computed from training data. |

#### SO3LR Physical Potentials

These enable the physics-based long-range interactions that distinguish SO3LR from the base So3krates model.

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `zbl_repulsion_bool` | `bool` | `True` | Enable the ZBL repulsion potential for short-range nuclear repulsion. |
| `nhl_repulsion_bool` | `bool` | `False` | Use the NHL short-range repulsion (fixed, tabulated element-pair coefficients) instead of ZBL. Takes precedence over `zbl_repulsion_bool`; a warning is logged if both are `true`. |
| `electrostatic_energy_bool` | `bool` | `True` | Enable electrostatic interactions via learned partial charges. Requires `r_max_lr` to be set. |
| `electrostatic_energy_scale` | `float` | `4.0` | Scaling factor for the electrostatic energy contribution. |
| `dispersion_energy_bool` | `bool` | `True` | Enable van der Waals dispersion interactions via learned Hirshfeld ratios. Requires `r_max_lr`. |
| `dispersion_energy_scale` | `float` | `1.2` | Scaling factor for the dispersion energy contribution. |
| `dispersion_energy_cutoff_lr_damping` | `float` | `None` | Damping cutoff (Å) for the TS dispersion damping function. Required when `dispersion_energy_bool: true`. |
| `c6_ratios_bool` | `bool` | `False` | Add a separate C6-ratio output head, so dispersion uses predicted C6 ratios instead of deriving them from the Hirshfeld (a0) ratios (SO3LR-tauri). Requires `dispersion_energy_bool: true`; needed for `c6_ratios_weight`. |
| `use_simple_hirshfeld` | `bool` | `False` | Use the simplified Hirshfeld head of the newer JAX `HirshfeldSparse` (SO3LR-tauri) instead of the original attention-based head. Requires `dispersion_energy_bool: true`. |
| `num_theory_levels` | `int` | `1` | Number of theory levels the energy output predicts (16 for the tauri models). Each structure's level is read from `atoms.info["theory_level"]` (integer `0 … num_theory_levels-1`). |
| `legacy_dispersion_bool` | `bool` | `True` | Selects the free-atom alpha/C6 reference table used for dispersion (legacy: elements Z=1–102; refitted: Z=1–86). Also used for PME dispersion's pseudo-charges. See [PME Dispersion](#pme-dispersion-particle-mesh-ewald). |
| `neighborlist_format_lr` | `str` | `"sparse"` | Storage format for the long-range neighbor list. |
| `use_pme` | `bool` | `False` | Enable PME electrostatics for periodic systems. See [PME Electrostatics](#pme-electrostatics-particle-mesh-ewald). |
| `pme_smearing` | `float` | `r_max / 5` | Ewald splitting width (Å) for PME electrostatics. |
| `pme_mesh_spacing` | `float` | `smearing / 2` | FFT grid spacing (Å) for PME electrostatics. |
| `use_pme_dispersion` | `bool` | `False` | Enable PME dispersion for periodic systems. See [PME Dispersion](#pme-dispersion-particle-mesh-ewald). |
| `pme_dispersion_smearing` | `float` | `r_max_lr / 5` | Ewald splitting width (Å) for PME dispersion. |
| `pme_dispersion_mesh_spacing` | `float` | `smearing / 2` | FFT grid spacing (Å) for PME dispersion. |
| `pme_mesh_rule` | `str` | `"jax"` | How the PME mesh size is rounded for a given spacing, for both PME terms: `"jax"` matches so3lr_dev (`jax-pme`), `"torchpme"` is stock torch-pme. See [PME Electrostatics](#pme-electrostatics-particle-mesh-ewald). |

#### PME Electrostatics (Particle Mesh Ewald)

For periodic systems, the direct-space Coulomb sum is conditionally convergent and a cutoff scheme introduces systematic errors that worsen with smaller boxes. PME splits the 1/r sum into a real-space part (using the SR neighbor list) and a reciprocal-space FFT part that captures the long-range tail exactly. When `use_pme: true`, `r_max_lr` is no longer required for electrostatics.

**Requires `torch-pme>=0.5` to be installed.** (Versions before 0.5 silently produce wrong dispersion energies for `exponent>3` potentials — see [PME Dispersion](#pme-dispersion-particle-mesh-ewald) below — so this is not just a routine minimum-version bump.) Use `torchkrates-tune-pme` to find optimal parameter values for your dataset.

**Limitations:**
- PME requires **periodic boundary conditions** (`pbc=True` on all axes). Calling a PME model on a non-periodic system raises a `ValueError`.
- The PME sum assumes **charge neutrality** (total charge ≈ 0). Non-neutral systems produce a conditionally-convergent result that depends on the background charge convention.
- PME models are **incompatible with the LAMMPS ML-IAP interface** (LAMMPS passes edge vectors, not absolute positions). Use the ASE calculator for PME production runs.

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `use_pme` | `bool` | `False` | Enable PME electrostatics. Replaces the direct cutoff scheme (`ElectrostaticInteraction`) with `PMEElectrostaticInteraction`. When `True`, `r_max_lr` is not required for the electrostatic contribution. |
| `pme_smearing` | `float` | `r_max / 5` | Ewald splitting width in Å. Controls the split between real- and reciprocal-space contributions. Smaller values shift more work to the mesh but reduce real-space accuracy. Run `torchkrates-tune-pme` to find the optimal value. |
| `pme_mesh_spacing` | `float` | `smearing / 2` | FFT grid spacing in Å. Finer grids improve reciprocal-space accuracy at higher computational cost. |
| `pme_mesh_rule` | `str` | `"jax"` | Mesh-size rounding rule, also used by PME dispersion. `jax-pme` (so3lr_dev) picks `2**ceil(log2(2*ceil(L/h)+1))` points per cell axis, stock torch-pme `2**ceil(log2(2*L/h+1))`; near power-of-two boundaries these differ (e.g. a 7.85 Å cell at `h=0.25` Å: 128 vs 64 points, ~0.2 eV). The JAX rule is the default so energies match so3lr_dev; its mesh is never smaller, so accuracy does not drop. Use `"torchpme"` for the previous behavior. |

Example config with PME enabled:
```yaml
ARCHITECTURE:
  r_max: 6.0
  # r_max_lr can be omitted when use_pme is true (not needed for electrostatics)
  use_pme: true
  pme_smearing: 1.18       # from torchkrates-tune-pme
  pme_mesh_spacing: 0.59
  electrostatic_energy_bool: true
  electrostatic_energy_scale: 4.0
```

#### PME Dispersion (Particle Mesh Ewald)

`DispersionInteraction`'s direct-space C6 sum is truncated at a cutoff with a smooth switching function; for periodic systems this truncation is a source of systematic error, the same kind of issue (though smaller in magnitude, since the C6 term decays as 1/r⁶) that PME electrostatics addresses for the 1/r Coulomb sum. `PMEDispersionInteraction` adds the missing reciprocal-space (k-space) contribution on top of the existing real-space calculation. Unlike PME electrostatics, this is **additive, not a replacement**: `DispersionInteraction`'s real-space C6 residual and its C8/C10 terms are still computed even when `use_pme_dispersion: true`, so `r_max_lr` remains required.

**Requires `torch-pme>=0.5` to be installed.** (Versions before 0.5 silently produce dispersion energies wrong by O(1) eV/atom for this `exponent=6` potential — the reciprocal-space k=0 term is only supplied correctly by torch-pme's own code starting at 0.5.0.) Use `torchkrates-tune-pme --tune_dispersion` to find optimal parameter values for your dataset.

**Limitations:**
- PME dispersion requires **periodic boundary conditions** (`pbc=True` on all axes). Calling it on a non-periodic system raises a `ValueError`.
- Unlike `use_pme`, `use_pme_dispersion` does **not** make `r_max_lr` optional — the real-space residual and C8/C10 terms are always computed alongside the k-space term.
- PME dispersion, like PME electrostatics, operates on absolute positions and the cell matrix and is **incompatible with the LAMMPS ML-IAP interface**. Use the ASE calculator for PME dispersion production runs.

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `use_pme_dispersion` | `bool` | `False` | Enable PME dispersion. Adds `PMEDispersionInteraction`'s k-space term on top of `DispersionInteraction`'s real-space residual + C8/C10 terms (does not replace them). |
| `pme_dispersion_smearing` | `float` | `r_max_lr / 5` | Ewald splitting width in Å. Run `torchkrates-tune-pme --tune_dispersion` to find the optimal value. |
| `pme_dispersion_mesh_spacing` | `float` | `smearing / 2` | FFT grid spacing in Å. |
| `legacy_dispersion_bool` | `bool` | `True` | Selects the free-atom alpha/C6 reference table used for dispersion mixing rules and (when `use_pme_dispersion: true`) pseudo-charges. `True` (default) uses the legacy table (elements Z=1–102); `False` uses the refitted table (Z=1–86). |

Example config with PME dispersion enabled:
```yaml
ARCHITECTURE:
  r_max: 6.0
  r_max_lr: 12.0            # still required — PME dispersion adds to, not replaces, the real-space term
  dispersion_energy_bool: true
  dispersion_energy_scale: 1.2
  dispersion_energy_cutoff_lr_damping: 2.0
  use_pme_dispersion: true
  pme_dispersion_smearing: 2.40        # from torchkrates-tune-pme --tune_dispersion
  pme_dispersion_mesh_spacing: 1.20
```

#### Multi-Head Ensemble

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `convert_to_multihead` | `bool` | `False` | Convert the single energy output head to multiple independent heads for ensemble predictions. |
| `num_output_heads` | `int` | `None` | Number of output heads. Required when `convert_to_multihead: true`. |
| `convert_theory_level` | `int` | `None` | Theory level to keep when converting a multi-theory-level model (e.g. the bundled `tauri-*` models) to multiple heads. Unset means level `5` (so3lr_dev's level). |
| `use_multihead` | `bool` | `False` | Enable head selection during multi-head training (each sample is assigned to a specific head). |


### Training Procedure (`TRAINING`)

#### Data

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `path_to_train_data` | `str` | *required* | Path to training data. Accepts `.xyz` files (ASE-readable) or `.h5`/`.hdf5` files. Preprocessed HDF5 files with pre-computed neighbor lists are auto-detected and loaded directly, which is significantly faster. |
| `path_to_val_data` | `str` | `None` | Path to a separate validation dataset. If not provided, validation data is split from the training set using `valid_ratio`. |
| `valid_ratio` | `float` | `0.1` | Fraction of training data to use for validation when `path_to_val_data` is not specified. |
| `num_train` | `int` | `None` | Limit the number of training samples. Useful for debugging or ablation studies. |
| `num_valid` | `int` | `None` | Limit the number of validation samples. |
| `batch_size` | `int` | *required* | Number of structures per training batch. |
| `valid_batch_size` | `int` | *required* | Number of structures per validation batch. Can be larger than `batch_size` since no gradients are computed. |
| `lazy_loading` | `bool` | `False` | Enable on-the-fly data loading and preprocessing from raw HDF5 files. Instead of loading all structures into memory upfront, each structure is read and its neighbor list computed on the fly by DataLoader worker processes. Only supported for raw HDF5 files (not XYZ). |
| `num_workers` | `int` | `4` | Number of DataLoader worker processes for parallel preprocessing. Only used when `lazy_loading: true`. Each worker reads structures from HDF5 and computes neighbor lists concurrently. |
| `prefetch_factor` | `int` | `2` | Number of batches each worker prefetches ahead of time. With `num_workers=4` and `prefetch_factor=2`, up to 8 batches are prepared in the background while the GPU trains. Only used when `lazy_loading: true`. |
| `data_preprocessed` | `bool` | `None` | Whether the training file is a preprocessed HDF5. `None` auto-detects; `true` additionally checks the file is HDF5 and that its stored cutoffs match `r_max`/`r_max_lr`. |
| `config_type_weights` | `dict` | `None` | Loss-weight multiplier per `atoms.info["config_type"]` (structures without one are `Default`), e.g. `{Default: 1.0, md: 0.5}`. Multiplies any per-structure `config_weight`. |
| `num_neighbor_samples` | `int` | `1000` | Number of structures randomly sampled to estimate the average number of neighbors (used for message normalization). Only used when `lazy_loading: true`. |

For multi-head models, data can be specified per head with the `heads` dict instead of using `path_to_train_data`:

```yaml
TRAINING:
  heads:
    head_0:
      path_to_train_data: /path/to/head0_train.xyz
      path_to_val_data: /path/to/head0_val.xyz  # optional
      valid_ratio: 0.1  # used if path_to_val_data not given
    head_1:
      path_to_train_data: /path/to/head1_train.xyz
      # Opt this head out of a globally-required loss property whose
      # data it genuinely doesn't have (e.g. an energy/forces-only
      # ensemble member) -- without this, a property with a non-zero
      # loss weight that's missing from any single head's data raises
      # an error.
      exclude_loss_properties: [hirshfeld_ratios]
```

#### Data Key Mapping

By default, the trainer reads reference properties using these keys from the ASE `atoms.info` / `atoms.arrays` dictionaries:

| Property | Default Key |
|----------|-------------|
| Energy | `REF_energy` |
| Forces | `REF_forces` |
| Stress | `REF_stress` |
| Virials | `REF_virials` |
| Dipole | `dipole` |
| Charges | `REF_charges` |
| Hirshfeld (a0) ratios | `REF_hirsh_ratios` (fallbacks: `hirshfeld_ratios`, `hirsh_ratios`, `a0_ratios`) |
| C6 ratios | `REF_c6_ratios` (fallback: `c6_ratios`) |
| Total charge | `total_charge` |
| Total spin | `total_spin` |

Override any of these via the `keys` dict:

```yaml
TRAINING:
  keys:
    energy_key: "energy"
    forces_key: "forces"
```

#### Optimizer

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `optimizer` | `str` | `"adam"` | Optimizer. Options: `adam`, `adamw`. |
| `lr` | `float` | *required* | Initial learning rate. |
| `weight_decay` | `float` | `0.0` | L2 regularization weight. Applied to all parameters. |
| `amsgrad` | `bool` | `False` | Use the AMSGrad variant of Adam, which keeps a running maximum of the second moment to prevent learning rate from increasing. |
| `betas` | `list[float]` | `[0.9, 0.999]` | Adam/AdamW beta coefficients for the first and second moment estimates. |
| `eps` | `float` | `1e-8` | Term added to the denominator for numerical stability in Adam/AdamW. |

#### Learning Rate Scheduler

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `scheduler` | `str` | `"exponential_decay"` | Learning rate scheduler. Options: `exponential_decay`, `reduce_on_plateau`, `cosine_annealing`, `warmup_cosine`. |
| `lr_scheduler_gamma` | `float` | `0.9993` | Multiplicative decay factor applied every epoch (for `exponential_decay`). An effective learning rate after *N* epochs is `lr * gamma^N`. |
| `scheduler_patience` | `int` | `5` | Number of epochs with no improvement before reducing the learning rate (for `reduce_on_plateau`). |
| `lr_factor` | `float` | `0.85` | Factor by which the learning rate is reduced when the plateau is reached (for `reduce_on_plateau`). |
| `scheduler_args` | `dict` | `{}` | Additional keyword arguments passed to the scheduler (e.g. `T_max`, `eta_min` for `cosine_annealing`). |
| `warmup_steps` | `int` | `0` | Number of warmup epochs for the `warmup_cosine` scheduler. During warmup, the learning rate increases linearly from 0 to `lr`. |

Scheduler options:
- `exponential_decay` — multiplies learning rate by `lr_scheduler_gamma` every epoch.
- `reduce_on_plateau` — reduces learning rate by `lr_factor` after `scheduler_patience` epochs without improvement.
- `cosine_annealing` — cosine decay to `eta_min` over `T_max` epochs (configurable via `scheduler_args`).
- `warmup_cosine` — linear warmup for `warmup_steps` epochs, then cosine annealing.

#### Loss Function

The loss function is automatically determined based on which weights are non-zero, or can be set explicitly via `loss_type`.

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `energy_weight` | `float` | `1.0` | Weight of the energy MSE loss term. Energy loss is normalized per atom. |
| `forces_weight` | `float` | `1000.0` | Weight of the forces MSE loss term. Typically much larger than `energy_weight` since force errors are smaller in magnitude. |
| `dipole_weight` | `float` | `0.0` | Weight of the dipole loss term. Set > 0 to train dipole predictions (requires dipole labels in training data). |
| `hirshfeld_weight` | `float` | `0.0` | Weight of the Hirshfeld (polarizability, a0) ratios loss term. Also accepted as `a0_ratios_weight`. |
| `c6_ratios_weight` | `float` | `0.0` | Weight of the per-atom C6 ratios loss term. Requires `ARCHITECTURE.c6_ratios_bool: true` (SO3LR-tauri). |
| `loss_type` | `str` | `"auto"` | `auto`/`properties`: one weighted term per non-zero weight (`WeightedPropertiesLoss`). Legacy explicit options: `energy_forces`, `energy_forces_dipole`, `energy_forces_hirshfeld`, `energy_forces_dipole_hirshfeld`, `energy_forces_charges`, `energy_forces_charges_hirshfeld`. |

Per-atom ratio labels (Hirshfeld/a0 and C6) may be missing for part of the training data: atoms with a NaN or absent label, or a zero structure weight, are excluded from the ratio losses and validation metrics (numerator and denominator), mirroring the JAX `so3lr` trainer. The SO3LR-tauri paper trains with forces 1.0, energy 0.01, dipole 0.1, a0 ratios 0.1 and C6 ratios 0.1 (SI Eq. S13); these weights transfer to torch only with `loss_reduction: per_graph`.

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `loss_reduction` | `str` | `"flat"` | `flat`: one mean over every element of the batch, so larger structures weigh more (MACE-style). `per_graph`: JAX `so3lr` reduction — per-atom terms are averaged per structure, then over structures that carry the label (a structure with any missing per-atom label is skipped); energy and dipole are divided by the number of atoms and averaged over labelled structures. Counts are summed across GPUs, so multi-GPU training weighs every structure equally. Only with `loss_type` `auto`/`properties`. |

**Robust loss.** Instead of the squared error, each term can use Barron's general robust loss ρ(x; α, c) ("A General and Adaptive Robust Loss Function", 2019), as the SO3LR-tauri paper does (SI Eq. S13). α sets how strongly large residuals still pull: 2 = squared error, 1 = Charbonnier/pseudo-Huber (L1-like for large errors), 0 = Cauchy. c sets where "large" starts, in the target's units.

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `use_robust_loss` | `bool` | `False` | Fixed robust loss: per-element penalty `2·ρ(x, robust_loss_alpha, 1)`. |
| `robust_loss_alpha` | `float` | `1.0` | α of the fixed robust loss. |
| `use_adaptive_robust_loss` | `bool` | `False` | Adaptive robust loss: α ∈ [0, 2] and c > 0 are learned per property through the negative log-likelihood `2·(ρ + log c + log Z(α))`. Loss values can be negative. α and c are logged during validation. |
| `adaptive_robust_loss_init_alpha` | `float` | `1.0` | Initial α (clipped to [0.01, 1.99]). |
| `adaptive_robust_loss_init_scale` | `float` | `1.0` | Initial c (at least 0.1). |

The two robust options are mutually exclusive and require `loss_type` `auto`/`properties`. To reproduce the JAX `so3lr` loss, combine `use_adaptive_robust_loss: true` with `loss_reduction: per_graph`.

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `use_robust_loss_validation` | `bool` | same as `use_robust_loss` | Use the fixed robust loss for the validation loss (which picks the best checkpoint and drives early stopping). Ignored with the adaptive loss: validation then always uses the training loss, as in JAX. |
| `robust_loss_alpha_validation` | `float` | same as `robust_loss_alpha` | α of the fixed robust validation loss. |

Settings that have no effect (any validation setting with the adaptive loss, or `robust_loss_alpha_validation` while validation uses the squared error) are logged as warnings.

**Two-stage loss weights.** As in the JAX trainer (and the SO3LR-tauri paper, which raises the energy weight from 0.001 to 0.01), the loss weights can change during training:

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `stage_two_start_epoch` | `int` | `None` | Epoch (≥ 1) from which the stage-two weights apply, to training and validation. At the switch the best-loss, early-stopping and `reduce_on_plateau` trackers reset; the current learning rate is kept. Early stopping during stage one ends the run, as in JAX. |
| `stage_two_loss_weights` | `dict` | `None` | Weights for stage two, with the same keys as the `*_weight` options (`energy_weight`, `forces_weight`, `dipole_weight`, `hirshfeld_weight`/`a0_ratios_weight`, `c6_ratios_weight`, `charges_weight`). Keys not listed keep their stage-one value. Labels needed by either stage must be in the data. |

Set both or neither; requires `loss_type` `auto`/`properties`. The adaptive robust-loss α/c are shared between the stages. Not combinable with SWA. A `stage_two_start_epoch` at or beyond `num_epochs` is accepted (you may extend `num_epochs` on a restart) but logged as a warning.

The JAX trainer's per-target loss `scales` and per-element `atom_loss_weights` are not exposed: JAX training never sets them (all 1), so there is nothing to match.

#### Training Loop

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `num_epochs` | `int` | *required* | Maximum number of training epochs. |
| `eval_interval` | `int` | `1` | Run validation every N epochs. |
| `patience` | `int` | `50` | Early stopping patience: training stops after this many consecutive epochs without improvement on the validation loss. |
| `early_stopping_min_delta` | `float` | `0.0` | Minimum loss improvement required to reset the patience counter. |
| `early_stopping_warmup` | `int` | `0` | Number of epochs before early stopping becomes active. |
| `clip_grad` | `float` | `10.0` | Maximum gradient norm for gradient clipping. Set to `null` to disable. |

#### Exponential Moving Average (EMA)

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `ema` | `bool` | `False` | Maintain an exponential moving average of model weights. The EMA weights are used for validation and the final saved model. |
| `ema_decay` | `float` | `0.99` | EMA decay factor. Values closer to 1.0 average over more history. |

#### Pre-trained Models

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `pretrained_model` | `str` | `None` | Path to a complete pre-trained model (`.model` file). The full model object is loaded, including architecture and weights. Cannot be combined with `pretrained_weights`. |
| `pretrained_weights` | `str` | `None` | Path to pre-trained weights (state dict). Weights are loaded into the model defined by the `ARCHITECTURE` section. Cannot be combined with `pretrained_model`. |
| `ft_update_avg_num_neighbors` | `bool` | `False` | Recompute the average number of neighbors from the new training data instead of keeping the value from the pre-trained model. |
| `force_use_average_shifts` | `bool` | `False` | Use E0 shifts computed from the new training data instead of the pre-trained model's shifts. |

`pretrained_weights` also accepts a converted checkpoint's `.pt` state_dict directly, e.g. `pretrained/so3lr/tauri/so3lr-tauri-s-2606.pt` (one of the bundled checkpoints described in [Pretrained SO3LR Models](#pretrained-so3lr-models-ase-calculator) above) or your own `torchkrates-jax2torch`-converted checkpoint following the same `<stem>.pt` + `<stem>_settings.yaml` naming convention. `ARCHITECTURE` in this config must match the checkpoint's architecture (copy from its sibling `*_settings.yaml`) — see the annotated example and caveats in [`examples/training/train_settings_example.yaml`](examples/training/train_settings_example.yaml) (near `TRAINING.patience`). This is plain warm-started training; for LoRA/DoRA/VeRA fine-tuning of a bundled checkpoint instead, see [`examples/finetuning/finetune_pretrained_so3lr.py`](examples/finetuning/finetune_pretrained_so3lr.py).

#### Fine-Tuning Strategy

When loading a pre-trained model, `finetune_choice` controls which parameters remain trainable.

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `finetune_choice` | `str` | `None` | Fine-tuning strategy. Options: `naive` (all parameters trainable), `last_layer` (only last transformer layer), `mlp` (only MLP weights), `qkv` (only query/key/value projections), `lora` (low-rank adaptation), `dora` (weight-decomposed LoRA), `vera` (vector-based random matrix adaptation). Combinations with `+mlp` are also supported: `last_layer+mlp`, `qkv+mlp`, `lora+mlp`. |
| `freeze_embedding` | `bool` | `True` | Freeze the atomic embedding layers during fine-tuning. |
| `freeze_zbl` | `bool` | `True` | Freeze ZBL repulsion parameters. |
| `freeze_partial_charges` | `bool` | `True` | Freeze the partial charges output head. |
| `freeze_hirshfeld` | `bool` | `True` | Freeze the Hirshfeld ratios output head (in SO3LR-tauri this is the polarizability/a0 ratio head). Also accepted as `freeze_a0_ratios`. |
| `freeze_c6_ratios` | `bool` | `True` | Freeze the C6 ratio output head (SO3LR-tauri, `c6_ratios_bool: true`). A warning is logged if a ratio loss weight is > 0 while its head is frozen. |
| `freeze_shifts` | `bool` | `False` | Freeze learned atomic energy shifts. |
| `freeze_scales` | `bool` | `False` | Freeze learned atomic energy scales. |

#### LoRA / DoRA / VeRA Parameters

These apply when `finetune_choice` is one of `lora`, `dora`, `vera`, or their `+mlp` variants.

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `lora_rank` | `int` | `4` | Rank of the low-rank adaptation matrices. Lower rank means fewer trainable parameters. |
| `lora_alpha` | `float` | `8.0` | Scaling factor. The effective adaptation is scaled by `alpha / rank`. |
| `lora_freeze_A` | `bool` | `False` | Freeze the A (down-projection) matrices and only train B. Reduces trainable parameters by half. |
| `dora_scaling_to_one` | `bool` | `True` | Initialize DoRA magnitude vectors to normalize columns to unit norm. |
| `use_lora_plus` | `bool` | `False` | Use LoRA+ optimizer: apply a separate (higher) learning rate to the B matrices. |
| `lora_B_lr` | `float` | `None` | Learning rate for the B matrices when `use_lora_plus` is enabled. Typically set to a multiple of the base `lr`. |

#### Data Replay

When fine-tuning, data replay prevents catastrophic forgetting by mixing a subset of pre-training data into each training epoch. The replay data is combined with the fine-tuning data at an approximate 1:1 ratio (when oversampling is enabled).

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `replay_datasets` | `list[str]` | `None` | Paths to replay datasets (XYZ, raw HDF5, or preprocessed HDF5). |
| `replay_fractions` | `list[float]` | `None` | Fraction of `replay_total` to draw from each dataset. Must sum to 1.0. |
| `replay_total` | `int` | `None` | Total number of replay structures to sample across all replay datasets. |
| `replay_oversample_finetune` | `bool` | `True` | When the fine-tune set is smaller than the replay set, oversample (repeat) fine-tune data to maintain ~1:1 ratio. When `False`, fine-tune and replay data are combined as-is without balancing. |
| `replay_resample_per_epoch` | `bool` | `False` | Re-draw a fresh random replay subset each epoch. When `False`, the subset is fixed at the start of training. |

**Example:**

```yaml
TRAINING:
  path_to_train_data: finetune.xyz
  finetune_choice: lora
  replay_datasets:
    - /data/pretrain_A.xyz
    - /data/pretrain_B.h5
  replay_fractions: [0.7, 0.3]
  replay_total: 5000
  replay_oversample_finetune: true
  replay_resample_per_epoch: false
```

This samples 3500 structures from `pretrain_A.xyz` and 1500 from `pretrain_B.h5`, then combines them with the fine-tuning data (oversampled to ~5000) for a total of ~10000 training structures per epoch.


### General Settings (`GENERAL`)

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `name_exp` | `str` | *required* | Experiment name. Used for checkpoint filenames, log files, and the final saved model. |
| `checkpoints_dir` | `str` | *required* | Directory where training checkpoints are saved. |
| `model_dir` | `str` | *required* | Directory for the final trained model. |
| `log_dir` | `str` | *required* | Directory for training and validation log files. |
| `default_dtype` | `str` | `"float64"` | Default floating-point precision. Options: `float32`, `float64`, `float16`, `bfloat16`. Training typically uses `float64` for numerical stability. |
| `seed` | `int` | `42` | Random seed for reproducibility (weight initialization, data shuffling). |
| `compute_stress` | `bool` | `False` | Compute stress tensors during training. Required when training with stress/virial labels. |


### Runtime and Logging (`MISC`)

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `device` | `str` | `"cpu"` | Device for training: `cpu`, `cuda`, `cuda:0`, etc. Ignored when `distributed: true`. |
| `distributed` | `bool` | `False` | Enable multi-GPU training with DistributedDataParallel (DDP). |
| `launcher` | `str` | `None` | Distributed launcher. Required when `distributed: true`. Options: `torchrun`, `slurm`, `mpi`. |
| `log_level` | `str` | `"INFO"` | Python logging level: `DEBUG`, `INFO`, `WARNING`, `ERROR`. |
| `error_table` | `str` | `"PerAtomMAE"` | Format for validation error reporting. Options: `PerAtomMAE`, `TotalMAE`, `PerAtomRMSE`, `TotalRMSE`, `PerAtomMAEstressvirials`, `PerAtomRMSEstressvirials`, `EnergyForceDipoleMAE`, `EnergyForceHirshfeldMAE`, `EnergyForceDipoleHirshfeldMAE`. |
| `log_wandb` | `bool` | `False` | Enable [Weights & Biases](https://wandb.ai) logging. Requires `wandb` to be installed and configured. |
| `restart_latest` | `bool` | `True` | Automatically resume from the latest checkpoint in `checkpoints_dir` if one exists. |
| `keep_checkpoints` | `bool` | `False` | Keep all checkpoints. When `False`, only the best checkpoint (lowest validation loss) is kept. |
| `no_checkpoint` | `bool` | `False` | Disable checkpoint loading entirely (overrides `restart_latest`). Useful for forcing a fresh start. |
| `deterministic_seed` | `bool` | `False` | Enable `cudnn.deterministic` for full reproducibility (slower). See [Reproducibility](#reproducibility) below. |


## Reproducibility

Set `seed` in the `GENERAL` section to fix random weight initialization and data shuffling. For full determinism (at the cost of ~10–20% slower training), also set `deterministic_seed: true` in `MISC`. The training config is automatically saved to `{checkpoints_dir}/config.yaml` at the start of each run and embedded in each checkpoint file.

---

## Cite
If you are using the models implemented here please cite:

```bibtex
@article{doi:10.1021/jacs.5c09558,
author = {Kabylda, Adil and Frank, J. Thorben and Suárez-Dou, Sergio and Khabibrakhmanov, Almaz and Medrano Sandonas, Leonardo and Unke, Oliver T. and Chmiela, Stefan and M{\"u}ller, Klaus-Robert and Tkatchenko, Alexandre},
title = {Molecular Simulations with a Pretrained Neural Network and Universal Pairwise Force Fields},
journal = {Journal of the American Chemical Society},
volume = {0},
number = {0},
pages = {null},
year = {0},
doi = {10.1021/jacs.5c09558},
    note ={PMID: 40886167},
URL = { 
    
        https://doi.org/10.1021/jacs.5c09558
},
eprint = { 
    
        https://doi.org/10.1021/jacs.5c09558
}
}

@article{frank2024euclidean,
  title={A Euclidean transformer for fast and stable machine learned force fields},
  author={Frank, Thorben and Unke, Oliver and M{\"u}ller, Klaus-Robert and Chmiela, Stefan},
  journal={Nature Communications},
  volume={15},
  number={1},
  pages={6539},
  year={2024}
}
```

Also consider citing MACE, as this software heavily leans on or uses its code:


```bibtex
@inproceedings{Batatia2022mace,
  title={{MACE}: Higher Order Equivariant Message Passing Neural Networks for Fast and Accurate Force Fields},
  author={Ilyes Batatia and David Peter Kovacs and Gregor N. C. Simm and Christoph Ortner and Gabor Csanyi},
  booktitle={Advances in Neural Information Processing Systems},
  editor={Alice H. Oh and Alekh Agarwal and Danielle Belgrave and Kyunghyun Cho},
  year={2022},
  url={https://openreview.net/forum?id=YPpSngE-ZU}
}

@misc{Batatia2022Design,
  title = {The Design Space of E(3)-Equivariant Atom-Centered Interatomic Potentials},
  author = {Batatia, Ilyes and Batzner, Simon and Kov{\'a}cs, D{\'a}vid P{\'e}ter and Musaelian, Albert and Simm, Gregor N. C. and Drautz, Ralf and Ortner, Christoph and Kozinsky, Boris and Cs{\'a}nyi, G{\'a}bor},
  year = {2022},
  number = {arXiv:2205.06643},
  eprint = {2205.06643},
  eprinttype = {arxiv},
  doi = {10.48550/arXiv.2205.06643},
  archiveprefix = {arXiv}
 }
```

## Contact

If you have questions you can reach me at: tobias.henkes@uni.lu

For bugs or feature requests, please use [GitHub Issues](https://github.com/TCPUniLU/So3krates-torch/issues).

## License

The code is published and distributed under the [MIT License](LICENSE.md), except for the robust loss module (`modules/robust_loss/`, Apache-2.0).

The bundled pretrained weights have their own licenses:

- **SO3LR tauri** (`pretrained/so3lr/tauri/`, keywords `tauri-*` and `v2-*`): [CC BY-NC 4.0](licenses/LICENSE.CC-BY-NC-4.0), non-commercial use only. Models fine-tuned from these weights fall under the same license.
- **Original SO3LR** (`pretrained/so3lr/v1/`, keyword `v1`): MIT.

Parts of the code are adapted from MACE and PyTorch Geometric (both MIT). [NOTICE.md](NOTICE.md) has the full attribution; the license texts are in [`licenses/`](licenses/) and ship with the package.
