pet-jax 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. pet_jax-0.1.0/.claude/commands/release.md +53 -0
  2. pet_jax-0.1.0/.github/workflows/ci.yml +46 -0
  3. pet_jax-0.1.0/.github/workflows/release.yml +36 -0
  4. pet_jax-0.1.0/.gitignore +49 -0
  5. pet_jax-0.1.0/CHANGELOG.md +13 -0
  6. pet_jax-0.1.0/CLAUDE.md +18 -0
  7. pet_jax-0.1.0/LICENSE +21 -0
  8. pet_jax-0.1.0/PKG-INFO +271 -0
  9. pet_jax-0.1.0/README.md +235 -0
  10. pet_jax-0.1.0/examples/i-pi/.gitignore +6 -0
  11. pet_jax-0.1.0/examples/i-pi/README.md +103 -0
  12. pet_jax-0.1.0/examples/i-pi/input.xml +43 -0
  13. pet_jax-0.1.0/examples/i-pi/petjax_driver.py +63 -0
  14. pet_jax-0.1.0/examples/i-pi/si-diamond.xyz +10 -0
  15. pet_jax-0.1.0/pyproject.toml +89 -0
  16. pet_jax-0.1.0/src/petjax/README.md +66 -0
  17. pet_jax-0.1.0/src/petjax/__init__.py +46 -0
  18. pet_jax-0.1.0/src/petjax/calculator.py +458 -0
  19. pet_jax-0.1.0/src/petjax/cli.py +161 -0
  20. pet_jax-0.1.0/src/petjax/convert.py +563 -0
  21. pet_jax-0.1.0/src/petjax/model.py +511 -0
  22. pet_jax-0.1.0/src/petjax/predict.py +159 -0
  23. pet_jax-0.1.0/src/petjax/select.py +516 -0
  24. pet_jax-0.1.0/src/petjax/structure.py +240 -0
  25. pet_jax-0.1.0/src/petjax/utils.py +41 -0
  26. pet_jax-0.1.0/tests/assets/predictions/test_mini_conditioned_pet-omol-s.npz +0 -0
  27. pet_jax-0.1.0/tests/assets/predictions/test_mini_conditioned_pet-omol-s_direct.npz +0 -0
  28. pet_jax-0.1.0/tests/assets/predictions/test_mini_pet-mad-xs-v1.6.npz +0 -0
  29. pet_jax-0.1.0/tests/assets/predictions/test_mini_pet-mad-xs-v1.6_direct.npz +0 -0
  30. pet_jax-0.1.0/tests/assets/predictions/test_mini_pet-mad-xs.npz +0 -0
  31. pet_jax-0.1.0/tests/assets/predictions/test_mini_pet-mad-xs_direct.npz +0 -0
  32. pet_jax-0.1.0/tests/assets/test_mini.xyz +308 -0
  33. pet_jax-0.1.0/tests/assets/test_mini_conditioned.xyz +308 -0
  34. pet_jax-0.1.0/tests/conftest.py +129 -0
  35. pet_jax-0.1.0/tests/generate_references.py +94 -0
  36. pet_jax-0.1.0/tests/test_calculator.py +457 -0
  37. pet_jax-0.1.0/tests/test_conditioning.py +188 -0
  38. pet_jax-0.1.0/tests/test_convert.py +125 -0
  39. pet_jax-0.1.0/tests/test_predictions.py +237 -0
  40. pet_jax-0.1.0/tests/test_select.py +177 -0
  41. pet_jax-0.1.0/tests/test_shard_map.py +81 -0
  42. pet_jax-0.1.0/tox.ini +40 -0
@@ -0,0 +1,53 @@
1
+ Create a new release of pet-jax on PyPI. Optional argument: EffVer bump level (`micro`, `meso`, or `macro`).
2
+
3
+ ## Steps
4
+
5
+ ### 1. Pre-flight checks
6
+
7
+ - Work from a clean checkout of `main` at `origin/main`. If the current checkout is on another branch or has changes, do not switch it; create a worktree instead: `git fetch origin main && git worktree add <scratch>/release origin/main`, and run everything below in there. Remove the worktree at the end.
8
+ - Check that CI is passing on the latest commit of `main`: `gh run list --repo lab-cosmo/pet-jax --branch main --limit 3`
9
+ - If CI is not green, do NOT proceed — investigate and fix first
10
+ - Check that `pyproject.toml` has no direct-URL dependencies (`@ git+...`), including in the extras. PyPI rejects them, and the publish job would fail after the tag is already pushed.
11
+ - Check that the README's Installation section matches reality: once the package is on PyPI it should say `pip install pet-jax` (and `pip install "pet-jax[convert]"`). PyPI renders the README of the tagged commit, so fix it before tagging.
12
+
13
+ ### 2. Run full local verification
14
+
15
+ - Run `uvx --with tox-uv tox -e lint` — must pass
16
+ - If `tests/assets/checkpoints/` is missing or stale (the checkpoint list in `tox.ini` or the converter changed since it was populated), run `uvx --with tox-uv tox -e fetch-checkpoints` first; otherwise the checkpoint tests are skipped and prove nothing
17
+ - Run `uvx --with tox-uv tox -e tests` — must pass, with no checkpoint tests skipped
18
+ - Run `uv build` and check that the sdist and wheel in `dist/` carry the expected version and contain only `petjax`; delete `dist/` afterwards
19
+ - Do NOT proceed if any of these fail
20
+
21
+ ### 3. Determine version
22
+
23
+ - Find the latest git tag with `git describe --tags --abbrev=0` (or note if there are no tags yet; the first release is then `0.1.0` unless the user says otherwise)
24
+ - pet-jax uses [EffVer](https://jacobtomlinson.dev/effver/) (`MACRO.MESO.MICRO`), not semver: the bump reflects how much effort users need to upgrade, not whether anything is technically breaking. Micro: little to no effort. Meso: some small effort (e.g. a renamed keyword, a changed default). Macro: significant effort. On `0.x.y`, `x` acts as macro and `y` as meso.
25
+ - If a bump level was given ($ARGUMENTS: `micro`, `meso`, or `macro`), compute the new version accordingly (on `0.x.y`: meso → `0.x.(y+1)`, macro → `0.(x+1).0`; micro is not separately expressible there, so treat it as meso)
26
+ - If NO bump level was given, review the changelog (step 4) first, then discuss with the user what the appropriate level should be, judged by the effort the changes impose on existing users
27
+ - Confirm the new version with the user before proceeding
28
+
29
+ ### 4. Finalise the changelog
30
+
31
+ - PRs add their own entries to the **Unreleased** section of `CHANGELOG.md`, so it should already be mostly complete
32
+ - Run `git log <last-tag>..HEAD --oneline` (or all commits if no prior tag) and cross-check: flag user-visible changes without an entry, and entries that are unclear or in the wrong group
33
+ - Propose fixes to the user, then turn **Unreleased** into `## [<version>] - <YYYY-MM-DD>` and add a fresh, empty `## Unreleased` above it
34
+ - Present the finished section to the user for review and approval
35
+ - Open a PR titled `Release v<version>` containing only the `CHANGELOG.md` change, and wait for the user to merge it. Then fetch and check out the merge commit on `origin/main`: the tag must point at the commit that contains the versioned section. If anything else was merged in the meantime, add it to the section first.
36
+
37
+ ### 5. Tag and push
38
+
39
+ - Create an annotated tag on the release PR's merge commit: `git tag -a v<version> -m "Release v<version>"`
40
+ - Push the tag: `git push origin v<version>`
41
+ - This triggers `.github/workflows/release.yml`, which builds the package and publishes it to PyPI via trusted publishing from the `release` environment
42
+ - Watch it: `gh run watch` (or `gh run list --repo lab-cosmo/pet-jax --workflow release.yml --limit 1`), and confirm the publish job succeeded before continuing
43
+
44
+ ### 6. Create GitHub release
45
+
46
+ - Use `gh release create v<version> --repo lab-cosmo/pet-jax --title "v<version>" --notes-file <file>`, where the file holds the version's `CHANGELOG.md` section without its heading (inline `--notes` with backticks gets mangled by the sandbox)
47
+ - Confirm the new version is visible on PyPI: `curl -s https://pypi.org/pypi/pet-jax/json | python -c "import json,sys; print(json.load(sys.stdin)['info']['version'])"`
48
+
49
+ ## Notes
50
+
51
+ - The version is derived from git tags by `hatch-vcs` (`[tool.hatch.version] source = "vcs"` in `pyproject.toml`). The only file a release modifies is `CHANGELOG.md`.
52
+ - The release workflow uses PyPI trusted publishing (no tokens). The one-time setup is a `release` environment on the GitHub repo and a trusted publisher for `pet-jax` on pypi.org pointing at `lab-cosmo/pet-jax`, `release.yml`, environment `release` (a "pending publisher" until the first upload creates the project).
53
+ - Sandbox: `git fetch`, `git push`, and `gh` must run as bare commands in their own Bash call, with the shell already inside the repo (use a separate `cd` call first). Wrapping them in `cd … &&`, `$(…)`, `;` or a pipe keeps them inside the sandbox, where ssh keys and the gh token are unreachable.
@@ -0,0 +1,46 @@
1
+ name: ci
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ lint:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ - name: Install uv
15
+ uses: astral-sh/setup-uv@v5
16
+ with:
17
+ enable-cache: true
18
+ - name: Install tox
19
+ run: uv tool install --with tox-uv tox
20
+ - name: Lint (ruff)
21
+ run: tox -e lint
22
+
23
+ test:
24
+ runs-on: ubuntu-latest
25
+ steps:
26
+ - uses: actions/checkout@v4
27
+ - name: Install uv
28
+ uses: astral-sh/setup-uv@v5
29
+ with:
30
+ enable-cache: true
31
+ - name: Install tox
32
+ run: uv tool install --with tox-uv tox
33
+ # The converted reference checkpoints depend only on the checkpoint list
34
+ # in tox.ini and on the converter itself; keyed on those, a hit skips the
35
+ # ~180 MB of downloads and the torch-side conversion.
36
+ - name: Cache converted checkpoints
37
+ id: checkpoints
38
+ uses: actions/cache@v4
39
+ with:
40
+ path: tests/assets/checkpoints
41
+ key: checkpoints-${{ hashFiles('tox.ini', 'src/petjax/convert.py', 'src/petjax/cli.py') }}
42
+ - name: Fetch + convert reference checkpoints
43
+ if: steps.checkpoints.outputs.cache-hit != 'true'
44
+ run: tox -e fetch-checkpoints
45
+ - name: Tests (pytest)
46
+ run: tox -e tests
@@ -0,0 +1,36 @@
1
+ name: release
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v*"
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ # Full history: hatch-vcs reads the version from the tag.
13
+ - uses: actions/checkout@v4
14
+ with:
15
+ fetch-depth: 0
16
+ - name: Install uv
17
+ uses: astral-sh/setup-uv@v5
18
+ - name: Build sdist + wheel
19
+ run: uv build
20
+ - uses: actions/upload-artifact@v4
21
+ with:
22
+ name: dist
23
+ path: dist/
24
+
25
+ publish:
26
+ needs: build
27
+ runs-on: ubuntu-latest
28
+ environment: release
29
+ permissions:
30
+ id-token: write
31
+ steps:
32
+ - uses: actions/download-artifact@v4
33
+ with:
34
+ name: dist
35
+ path: dist/
36
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,49 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .venv/
8
+ .tox/
9
+ .pytest_cache/
10
+ .ruff_cache/
11
+
12
+ # Library — consumers resolve their own deps; we don't pin a lockfile.
13
+ uv.lock
14
+
15
+ # Environment
16
+ .envrc
17
+ .direnv/
18
+
19
+ # Editor
20
+ .vscode/
21
+ .idea/
22
+ .DS_Store
23
+
24
+ # Runtime checkpoints at repo root (populated by `petjax-convert`); the leading
25
+ # slash anchors this so it doesn't match tests/assets/checkpoints/.
26
+ /checkpoints/
27
+
28
+ # Local Claude Code overrides
29
+ .claude/settings.local.json
30
+ .claude/*.lock
31
+
32
+ # Converted checkpoint artifacts (fetched on demand by `petjax-convert`).
33
+ # Only the .npz reference fixtures are checked in; the .msgpack is a build
34
+ # artifact reproduced from the upstream metatrain .ckpt.
35
+ tests/assets/checkpoints/pet-mad-xs/model.msgpack
36
+ tests/assets/checkpoints/pet-mad-xs/metadata.yaml
37
+ tests/assets/checkpoints/pet-mad-xs-v1.6/
38
+ tests/assets/checkpoints/pet-mad-s/
39
+ tests/assets/checkpoints/pet-omat-xs/
40
+ tests/assets/checkpoints/pet-omol-s
41
+
42
+ # Extended test assets (fetched/generated locally; CI uses test_mini only)
43
+ tests/assets/test_s.xyz
44
+ tests/assets/test_m.xyz
45
+ tests/assets/test_l.xyz
46
+ tests/assets/*.bak
47
+ tests/assets/predictions/test_s_*.npz
48
+ tests/assets/predictions/test_m_*.npz
49
+ tests/assets/predictions/test_l_*.npz
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ All notable changes to `pet-jax` are listed here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow [effort-based versioning](https://jacobtomlinson.dev/effver/) (EffVer, as used by JAX): the bumped component says how much effort upgrading takes, from none (micro) through some (meso) to significant (macro). While on `0.x`, the second number plays the macro role and the third the meso role.
4
+
5
+ Every PR that changes something a user can see adds a line under **Unreleased**, in the matching group (Added, Changed, Fixed, Removed). At release time, **Unreleased** becomes the new version's section.
6
+
7
+ ## Unreleased
8
+
9
+ ## [0.1.0] - 2026-10-01
10
+
11
+ ### Added
12
+
13
+ - First release. Includes the JAX/Flax reimplementation of uPET, the `UPETCalculator` ASE calculator (energy, forces, stress, adaptive cutoffs), and `petjax-convert` for `metatrain` checkpoints (PET-MAD, PET-OMAT and other bare or LLPR-wrapped PET checkpoints, from format v10 onwards). Also includes charge/spin system conditioning (e.g. PET-OMol).
@@ -0,0 +1,18 @@
1
+ # `pet-jax` — notes for AI agents
2
+
3
+ There are two README files. Read both before editing the code.
4
+
5
+ - [`README.md`](README.md) — user-facing. Quick start, public API, high-level 2-phase architecture sketch, performance knobs, checkpoint format, dev workflow (`tox` / `uv`), dependencies, status.
6
+ - [`src/petjax/README.md`](src/petjax/README.md) — developer-facing. Design intent behind each side of the JIT boundary, the JIT placement rule (`@jax.jit` lives only at two sites), the upstream-faithful `UPET` invariant, internal NL/padding/attention conventions, code style, Markdown soft-wrap rule.
7
+
8
+ Section pointers, so you don't have to grep:
9
+
10
+ - Usage examples + public API → top-level README §Quick start
11
+ - High-level 2-phase architecture → top-level README §Architecture
12
+ - User-facing knobs (`skin`, `default_dtype`, `bucket_strategy`, `cutoff_override`, …) → top-level README §Performance knobs
13
+ - Calculator-level invariants (energy/stress conventions, scaling, adaptive cutoff) → top-level README §Conventions
14
+ - Dev workflow (`tox`, `uv`, lint, tests, fetching the reference checkpoint) → top-level README §Development
15
+ - **Design rationale by JIT phase, the `flax.linen.attention` softmax/dtype caveat, the rectangular-NL layout** → `src/petjax/README.md`
16
+ - **Code conventions (`ruff`, naming, file layout, comment policy, Markdown)** → `src/petjax/README.md`
17
+
18
+ When you learn or decide something that other contributors will need, add it to the relevant section in whichever README is appropriate — do not duplicate it into this file. Keep this file short.
pet_jax-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Marcel Langer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
pet_jax-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,271 @@
1
+ Metadata-Version: 2.5
2
+ Name: pet-jax
3
+ Version: 0.1.0
4
+ Summary: Clean JAX/Flax implementation of uPET interatomic potentials
5
+ Project-URL: Repository, https://github.com/lab-cosmo/pet-jax
6
+ Project-URL: Issues, https://github.com/lab-cosmo/pet-jax/issues
7
+ Project-URL: Changelog, https://github.com/lab-cosmo/pet-jax/blob/main/CHANGELOG.md
8
+ Author-email: Marcel Langer <dev@marcel.science>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: ase,flax,jax,machine-learning-interatomic-potentials,pet,pet-mad
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Scientific/Engineering :: Chemistry
22
+ Classifier: Topic :: Scientific/Engineering :: Physics
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: ase>=3.23
25
+ Requires-Dist: flax>=0.8
26
+ Requires-Dist: jax>=0.10
27
+ Requires-Dist: jaxlib>=0.10
28
+ Requires-Dist: marathon-train>=0.2.2
29
+ Requires-Dist: numpy>=1.26
30
+ Requires-Dist: vesin>=0.5
31
+ Provides-Extra: convert
32
+ Requires-Dist: metatomic-torch; extra == 'convert'
33
+ Requires-Dist: metatrain>=2026.3; extra == 'convert'
34
+ Requires-Dist: torch; extra == 'convert'
35
+ Description-Content-Type: text/markdown
36
+
37
+ # `pet-jax`
38
+
39
+ A clean JAX/Flax reimplementation of the **uPET (Point-Edge Transformer)** family of interatomic potentials, targeting numerical equivalence with the upstream [metatrain](https://github.com/metatensor/metatrain) PyTorch implementation while being efficient enough for production inference and geometry optimisation.
40
+
41
+ `pet-jax` loads `metatrain` checkpoints (e.g. PET-MAD), runs them on JAX, and exposes an ASE calculator (`UPETCalculator`) suitable as a drop-in replacement for the PyTorch reference in molecular dynamics, relaxations, and downstream property calculations.
42
+
43
+ ## What's in the box
44
+
45
+ ```
46
+ src/petjax/
47
+ __init__.py # public API
48
+ model.py # UPET (Flax nn.Module)
49
+ calculator.py # UPETCalculator (ASE)
50
+ convert.py # metatrain .ckpt → Flax msgpack
51
+ cli.py # petjax-convert entrypoint
52
+ structure.py # host-side neighborlist build
53
+ select.py # in-JIT adaptive selection
54
+ predict.py # in-JIT forward + autodiff
55
+ utils.py # shared helpers
56
+ ```
57
+
58
+ ## Installation
59
+
60
+ `pet-jax` needs Python ≥ 3.10. Install it from PyPI:
61
+
62
+ ```bash
63
+ pip install pet-jax
64
+ ```
65
+
66
+ This pulls in the inference stack (`jax`, `flax`, `numpy`, `ase`, `vesin`, `marathon-train`) — everything needed to load a checkpoint and run the calculator.
67
+
68
+ Converting upstream `metatrain` `.ckpt` files needs the optional `convert` extra (`torch`, `metatomic-torch`, `metatrain`), which is **not** required for inference:
69
+
70
+ ```bash
71
+ pip install "pet-jax[convert]"
72
+ ```
73
+
74
+ `pet-jax` is experimental and under active development, and releases lag behind `main`. For the latest state, install from GitHub:
75
+
76
+ ```bash
77
+ pip install "git+https://github.com/lab-cosmo/pet-jax"
78
+ pip install "pet-jax[convert] @ git+https://github.com/lab-cosmo/pet-jax" # with the convert extra
79
+ ```
80
+
81
+ Or from a checkout, which is the easiest way to also get the examples and tests:
82
+
83
+ ```bash
84
+ git clone https://github.com/lab-cosmo/pet-jax
85
+ cd pet-jax
86
+ pip install -e ".[convert]" # drop [convert] for an inference-only install
87
+ ```
88
+
89
+ Any environment manager works (`pip`, `uv`, `conda`, ...); the examples below use plain console scripts, and the `uv` + `tox` development workflow is in [Development](#development) (`uv sync --extra convert` for the editable install).
90
+
91
+ ## Quick start
92
+
93
+ ### Fetch a PET-MAD checkpoint
94
+
95
+ ```bash
96
+ petjax-convert pet-mad-xs --out checkpoints/pet-mad-xs
97
+ ```
98
+
99
+ This downloads the current PET-MAD release (v1.6.0) from Hugging Face (`lab-cosmo/upet`) and converts it directly to `pet-jax`'s Flax msgpack layout — no TorchScript intermediate. Pass `--version` for an older release (`--version 1.5.0`). The `convert` extra pulls in `torch`, `metatomic-torch`, and `metatrain` (needed only for conversion; not for inference).
100
+
101
+ `petjax-convert` also accepts arbitrary URLs or local `.ckpt` paths:
102
+
103
+ ```bash
104
+ petjax-convert https://example.com/my-pet.ckpt --out checkpoints/my-pet
105
+ petjax-convert ~/runs/best.ckpt --out checkpoints/my-pet
106
+ ```
107
+
108
+ ### Inference on a single structure
109
+
110
+ ```python
111
+ from ase.io import read
112
+ from petjax import UPETCalculator
113
+
114
+ calc = UPETCalculator.from_checkpoint("checkpoints/pet-mad-xs", stress=True)
115
+
116
+ atoms = read("my_structure.xyz")
117
+ atoms.calc = calc
118
+
119
+ energy = atoms.get_potential_energy() # eV
120
+ forces = atoms.get_forces() # eV/Å
121
+ stress = atoms.get_stress() # voigt, eV/ų
122
+ ```
123
+
124
+ Relaxations and so on can be done with the same calculator!
125
+
126
+ ## Architecture: how the calculator handles adaptive cutoffs
127
+
128
+ The PET model itself operates on a "rectangular"-style neighborlist, i.e., shaped as `[n_atoms, n_neighbors]`, since its main operation is edge-to-edge attention which (naively) requires an intermediate `[n_atoms, n_neighbors, n_neighbors]` attention matrix.[^flat-nl]
129
+
130
+ [^flat-nl]: Internally, the neighborlist is stored in flattened `[n_atoms*n_neighbors]` form, but this is not relevant here.
131
+
132
+ The universal PET models wrap an *adaptive cutoff* procedure around the model, which selects a per-atom cutoff such that only an approximately fixed number of neighbors are considered for each atom. This avoids spikes in memory usage for dense systems, improves batching efficiency for diverse dataset during training, and also lets the model predict dimer curves better. At a high level, the procedure works as follows:
133
+
134
+ 1. Compute an initial large neighborlist with a big cutoff,
135
+ 2. Determine a cutoff for each atom that fits approximately the target number of neighbors,
136
+ 3. Compute per-pair cutoffs as average of both per-atom cutoffs,
137
+ 4. Apply a per-pair boolean mask — keep pair `(i, j)` iff `r_ij` is at most `pair_cutoff_ij`.
138
+
139
+ Step 2 involves the two cutoff widths of the model, which are easy to confuse. To keep the procedure differentiable, neighbors are counted *softly*, with the usual smooth bump function: `n_i(r) = sum_j bump(d_ij; r, cutoff_width_adaptive) + N_target * (r / cutoff)^3`. The per-atom cutoff is the radius where this count crosses the target; the cubic baseline makes sure there is exactly one crossing. So `cutoff_width_adaptive` is the blur radius of the neighbor counting, and nothing else — the separate `cutoff_width` is used later, to taper edge features to zero at the selected pair cutoffs. The blur is not cosmetic: a blurrier count crosses the target further out and selects more neighbors, so the model has to be run with the width it was trained with. The crossing itself is found either on a probe grid with Gaussian weighting (`adaptive_cutoff_method: grid`) or by Newton-bisection root finding (`solver`), again matching the checkpoint.
140
+
141
+ The subtlety here is that since the cutoffs depend on the position of atoms *outside* the cutoff, gradients have to flow through the procedure to some extent and it therefore has to be done inside the model's forward pass. So we need to make the procedure compatible with `jax`, so we can `jit` it and transform it with `grad`. The constraints: No data-dependent shapes, and few shape changes to avoid costly recompilations. This is made more complicated by the fact that smoothness dictates that the procedure is not exact: We can only *target* a certain number of neighbors, but we can't guarantee it.
142
+
143
+ The solution to this is a two-phase design: Outside of `jax`, we compute the initial big neighborlist and determine the final number, `k_sel`, of neighbors. We can round `k_sel` to something larger to avoid recompiles. We also have to pad the initial big neighborlist to a fixed shape, but this is easy to achieve. Inside `jax` (i.e., the `jax.jit` boundary), we then re-run the procedure and pack into `k_sel`, which we already know ahead of time due to step one. If we exceed `k_sel`, we return an `overflow` signal to tell the calculator that `k_sel` needs to be recomputed.
144
+
145
+ For neighbor lists already trimmed to a fixed neighbor count upstream, `pack_edges` is the selection-free sibling of `truncate_edges`: it packs to the same fixed-width layout, skipping the adaptive-cutoff selection (`pair_cutoffs=None`).
146
+
147
+ `select_edges` runs the adaptive selection on a structure dict host-side and returns what it produced: per-atom and per-pair cutoffs, the selected-pair mask, and the selected count per atom. The calculator sizes `k_sel` from it; consumers that need the model's actual adjacency rather than the raw neighbor ball (the Hessian sparsity pattern, graph-distance analyses) read the mask.
148
+
149
+ For the design rationale and more details, see [`src/petjax/README.md`](src/petjax/README.md).
150
+
151
+ ## Performance knobs
152
+
153
+ `UPETCalculator` exposes a few keyword arguments that trade off accuracy, memory, JIT recompile frequency, and per-step cost. Maximum efficiency requires tuning them for your particular problem.
154
+
155
+ - `default_dtype` (default `"float32"`): set to `"float64"` for demanding relaxations or precision-sensitive comparisons. fp32 is ~2× faster; PET-MAD checkpoints ship fp32, so fp64 just promotes the cached params. For most inference fp32 is fine.
156
+ - `matmul_precision` (default `"high"`): JAX fp32 matmul accumulation precision on accelerators (`"default"` / `"high"` / `"highest"`); a no-op on CPU. The `"default"` mode uses reduced-precision (TF32-style) accumulation that noticeably degrades NVE energy conservation; `"high"` restores it at essentially no extra cost, while `"highest"` (full fp32) is slower when compute-bound. Set to `None` to leave JAX's global config untouched (for callers managing it themselves). Like `default_dtype`'s fp64 switch, this mutates global JAX state.
157
+ - `skin` (default `0.5` Å): Verlet-skin radius. Larger skin → fewer raw-NL rebuilds (good for long MD with small step sizes) at the cost of more padded pairs per step. Shrink if `vesin`/raw-NL build dominates; grow if you see frequent skin-triggered rebuilds.
158
+ - `stress` (default `True`): set to `False` to skip the strain-derivative virial. Drops one `value_and_grad` argument; very slightly faster, no `stress` key in `results`.
159
+ - `no_shadow` (default `False`): cut gradients through the adaptive-cutoff function. Slightly faster, slightly different forces (drops the "shadow" contribution from the cutoff procedure). Energy is unchanged.
160
+ - `direct_forces` / `direct_stress` (default `False`, passed via `from_checkpoint`): read forces/stress straight from the checkpoint's non-conservative heads instead of differentiating the energy — skips the autodiff pass entirely (no double-backward), so cheaper, especially together. Trades accuracy and energy-conservation for speed (the net force is removed to avoid drift); see [Conventions](#conventions).
161
+ - `bucket_strategy` (default `"multiples"`) and axis-specific overrides `n_atoms_bucket_strategy`, `n_pair_bucket_strategy`, `k_sel_bucket_strategy`: how shapes are rounded up to bucket sizes. Coarser bucketing → fewer JIT recompiles but more padded compute; finer → tighter shapes but more recompiles when shapes drift. The default is a reasonable compromise.
162
+ - `extra_neighbors` (default `4`): slack added to `k_sel_actual` so a step or two of neighbour growth doesn't trigger an overflow rebuild. Increase if you see frequent overflow retries during MD; decrease to save padded edge work.
163
+ - `num_neighbors_adaptive` (default `None`): override how many neighbours per atom the adaptive cutoff aims to select; `None` uses the value the model was trained with. Raising it lets the model see more neighbours per atom — accuracy tends to improve (models are robust to this) for a modest increase in per-step cost. If you also set a tight `cutoff_override`, the wider reach makes its warning below more likely to fire.
164
+ - `cutoff_override` (default `None`): narrow the `vesin` raw-NL query radius below the trained `config["cutoff"]`. ⚠ **Correctness risk**: must stay above the largest per-atom adaptive cutoff that selection ever reaches, otherwise surviving pairs are silently dropped. Only set this when you know your system's adaptive cutoffs don't approach `config["cutoff"]`. The calculator measures the actual reach each rebuild (`debug_stats["max_selected_cutoff"]`) and emits a `warnings.warn` if your override falls below it — use that to find a safe value.
165
+ - `debug` (default `False`): emit a per-rebuild summary to `stderr` (padding waste on each axis, `k_sel_actual → k_sel_padded`, the measured `max_selected_cutoff` vs the raw-NL/trained cutoff, and whether `predict_fn` will retrace). Keyed to NL rebuilds and overflow events, not per MD step, so long trajectories stay quiet. The same numbers are always available on `calc.debug_stats` regardless of this flag; the too-small-`cutoff_override` warning above also fires independently of it.
166
+
167
+
168
+ ## Conventions
169
+
170
+ - **Energy** is total energy (eV), not per-atom.
171
+ - **Stress** returned by the calculator is in ASE's Voigt convention (eV/ų); internally the virial is the strain derivative `dU/dε` in eV.
172
+ - **Scaling/shifting**: raw model output is multiplied by `energy_scale` inside JIT (at params dtype). Per-element composition shifts are added post-JIT on the calculator side in Python fp64; they contribute zero to forces.
173
+ - **Adaptive cutoff**: per-atom, recomputed inside the autograd graph each step (required for force correctness). The selection runs at the checkpoint's `cutoff_width_adaptive` — recent `metatrain` versions split it off the final-taper `cutoff_width`; checkpoints converted before the split fall back to the shared value, matching upstream's own migration rule. Both upstream selection algorithms are implemented and picked via the checkpoint's `adaptive_cutoff_method`: `grid` (probe grid + Gaussian weights, what pre-split checkpoints trained with) and `solver` (Newton-bisection root find, the upstream default for new trainings; gradients attach via an implicit-function-theorem step).
174
+ - **Charge and spin conditioning**: a checkpoint trained with `system_conditioning` embeds the total charge and the spin multiplicity of each structure and adds them to the node features after every GNN layer, so the same geometry can give different predictions for different electronic states. The calculator reads them from `atoms.info["charge"]` and `atoms.info["spin_multiplicity"]`, the keys `metatrain`'s readers use; a missing key means neutral (0) or singlet (1), as upstream defaults, and a change in either invalidates the cached results like a change in positions would. Values must be integers within the checkpoint's `max_charge` / `max_spin_multiplicity` range, checked host-side. Unconditioned checkpoints ignore both keys.
175
+ - **Non-conservative forces/stress**: PET-MAD checkpoints also carry direct force/stress heads. Pass `direct_forces=True` / `direct_stress=True` to `from_checkpoint` to read forces/stress straight from those heads (skipping autodiff — cheaper, no double-backward) instead of differentiating the energy. The default stays conservative (autodiff). Both reproduce the metatrain reference to fp32; for forces the per-structure mean is subtracted to remove the spurious net force the direct head would otherwise leave (matching metatrain's calculator).
176
+
177
+ ## Checkpoint format
178
+
179
+ `pet-jax` checkpoints are a directory with two files:
180
+
181
+ ```
182
+ <ckpt_dir>/
183
+ model.msgpack # Flax parameter tree (nested dict of arrays)
184
+ metadata.yaml # config (architecture hypers), shifts
185
+ ```
186
+
187
+ Use `UPETCalculator.from_checkpoint("<ckpt_dir>")` to load. Conversion from the upstream `metatrain` `.ckpt` format goes through `petjax-convert`, which reads the checkpoint directly (no TorchScript intermediate). Both published layouts are accepted: bare PET checkpoints (the pet-omat / pet-omad / … lines) and LLPR-wrapped ones (the PET-MAD releases), with PET checkpoint versions 10 through 16 — the between-version differences (including the v15 charge/spin conditioning hypers) are absorbed during conversion, mirroring `metatrain`'s own upgrade rules. Older versions are rejected (run `mtt upgrade` on the source); newer ones are rejected until `pet-jax` catches up.
188
+
189
+ Not everything upstream changes is versioned, though: PET-MAD v1.6 renamed the direct-force readout target from `non_conservative_forces` to `non_conservative_force` while leaving the checkpoint version alone. Conversion therefore dispatches readout weights on the head name rather than the version, accepts both spellings, and refuses (rather than guesses) a head name it does not know.
190
+
191
+ ## Validation
192
+
193
+ `tests/test_predictions.py` compares the calculator's output against saved `metatrain` reference predictions on the mini CI dataset (and the larger `test_s/m/l` datasets under `--run-extended`). The mini suite runs against every release in `conftest.MINI_RELEASES` — currently `pet-mad-xs` at v1.5 and v1.6, one checkpoint per readout-head naming scheme, and the charge/spin conditioned `pet-omol-s`, scored on a copy of the mini set with a (charge, multiplicity) pair in each frame's `atoms.info` — in both conservative and non-conservative mode. References are `.npz` arrays — energies, forces, stresses, and the per-structure atom counts that tie them to the dataset — never geometry, which lives in the dataset file. Regenerate them with `tests/generate_references.py` (see its docstring; needs `metatrain >= 2026.4` to read a v16 checkpoint through `metatrain`'s own model classes).
194
+
195
+ `tests/test_calculator.py` additionally covers:
196
+
197
+ - **Shift plumbing**: composition shifts are added exactly once, in fp64, with zero leakage into forces.
198
+ - **no_shadow**: optional cut of adaptive-cutoff gradients preserves energy and produces finite, slightly shifted forces.
199
+ - **Position-only update**: small geometry changes do not trigger a re-JIT.
200
+ - **Cell relaxation**: BFGS + FrechetCellFilter over 30 steps on a small periodic structure — energy doesn't increase, forces stay finite, NL rebuilds stay below half the step count (the whole point of the Verlet-skin + bucketed-shapes machinery).
201
+
202
+ ## Working with the upstream PyTorch implementation
203
+
204
+ To run the original `metatrain`/`metatomic-torch` code without polluting the `pet-jax` environment:
205
+
206
+ ```bash
207
+ uv run --with metatrain --with metatomic-torch python ...
208
+ ```
209
+
210
+ Useful for cross-checks against ground truth.
211
+
212
+ ## Development
213
+
214
+ The canonical task runner is `tox` (with the `tox-uv` plugin so environments are created via `uv`). Envs declared in `tox.ini`:
215
+
216
+ - `tox -e lint` — `ruff check` + `ruff format --check`
217
+ - `tox -e tests` — `pytest` mini suite (pass `--run-extended` after `--` for the extended local suite)
218
+ - `tox -e fetch-checkpoints` — converts the reference checkpoints the tests need into `tests/assets/checkpoints/` (one-off; uses the `convert` extra)
219
+
220
+ Bootstrap:
221
+
222
+ ```bash
223
+ uv tool install --with tox-uv tox
224
+ tox -e fetch-checkpoints # first time only
225
+ tox -e lint
226
+ tox -e tests
227
+
228
+ # extended local suite (test_s, test_m, test_l × pet-mad-xs, pet-mad-s; needs
229
+ # extra assets + the pet-mad-s checkpoint, all gitignored)
230
+ tox -e tests -- --run-extended
231
+ ```
232
+
233
+ Extended tests skip individually when their input files are missing.
234
+
235
+ For tight inner-loop work you can bypass `tox`:
236
+
237
+ ```bash
238
+ uv sync # install core + dev
239
+ uv run pytest tests/ -x
240
+ uv run ruff check src/ tests/
241
+ uv run ruff format src/ tests/
242
+ ```
243
+
244
+ ## Dependencies
245
+
246
+ Core (`pyproject.toml`):
247
+
248
+ - `jax`, `jaxlib`, `flax` — neural net + autodiff
249
+ - `numpy`, `ase` — data structures
250
+ - `vesin` — fast neighbourlist construction
251
+ - `marathon-train` — checkpoint I/O (msgpack/yaml) and bucket-size helpers
252
+
253
+ Optional (the `convert` extra — see [Installation](#installation)):
254
+
255
+ - `torch`, `metatomic-torch`, `metatrain` — only needed when converting `metatrain` `.ckpt` files. Inference itself runs on the JAX stack alone.
256
+
257
+ ## Contributing
258
+
259
+ Code conventions (`ruff` config, naming patterns, file layout, JIT placement rule, Markdown soft-wrap, internal NL/attention conventions) and the architecture deep-dive live in [`src/petjax/README.md`](src/petjax/README.md). Read it before submitting non-trivial PRs.
260
+
261
+ PRs that change anything user-visible add a line to the **Unreleased** section of [`CHANGELOG.md`](CHANGELOG.md).
262
+
263
+ ## Status
264
+
265
+ Working: inference, forces, stress, BFGS/FIRE relaxations, cell optimization, `metatrain` checkpoint conversion, charge/spin conditioning, parity with upstream PET.
266
+
267
+ Not yet: training (use `metatrain` directly), batched multi-structure inference in the calculator (single-structure only), GPU performance tuning.
268
+
269
+ ## License
270
+
271
+ MIT. See [LICENSE](LICENSE).