Metadata-Version: 2.5
Name: substrax
Version: 0.1.34
Summary: Training, testing and CI infrastructure for JAX/Flax NNX: JAX runtime setup, device meshes and SPMD sharding, optax optimizers, Orbax checkpoints, early stopping, experiment logging, GPU compute jobs, test tools and reusable CI gates
Project-URL: Changelog, https://github.com/avitai/substrax/blob/main/CHANGELOG.md
Project-URL: Documentation, https://substrax.readthedocs.io
Project-URL: Repository, https://github.com/avitai/substrax
Author-email: Mahdi Shafiei <mahdi@avitai.bio>
License: MIT License
        
        Copyright (c) 2026 Mahdi Shafiei
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: checkpointing,distributed,flax,infrastructure,jax,sharding
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: English
Classifier: Operating System :: MacOS
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.12
Requires-Dist: etils[epath]>=1.14.0
Requires-Dist: flax>=0.12.9
Requires-Dist: jax<0.11.2,>=0.11.1
Requires-Dist: jaxlib<0.11.2,>=0.11.1
Requires-Dist: numpy<2.6.0,>=1.24
Requires-Dist: optax>=0.2.8
Requires-Dist: orbax-checkpoint>=0.11.33
Requires-Dist: pydantic>=2.10
Provides-Extra: all
Requires-Dist: bandit[toml]>=1.8.6; extra == 'all'
Requires-Dist: build>=1.0.3; extra == 'all'
Requires-Dist: coverage>=7; extra == 'all'
Requires-Dist: deptry>=0.23; extra == 'all'
Requires-Dist: diff-cover>=10.6.0; extra == 'all'
Requires-Dist: griffe>=1.7.3; extra == 'all'
Requires-Dist: hypothesis>=6.100; extra == 'all'
Requires-Dist: import-linter>=2.0; extra == 'all'
Requires-Dist: interrogate>=1.5; extra == 'all'
Requires-Dist: ipykernel>=7.4.0; extra == 'all'
Requires-Dist: jax[cuda12]<0.11.2,>=0.11.1; extra == 'all'
Requires-Dist: jupyter-client>=8.10.0; extra == 'all'
Requires-Dist: jupyter-core>=5.9.1; extra == 'all'
Requires-Dist: jupytext>=1.19.6; extra == 'all'
Requires-Dist: markdown-it-py>=4.2.0; extra == 'all'
Requires-Dist: matplotlib>=3.8; extra == 'all'
Requires-Dist: mkdocs-material>=9.7.7; extra == 'all'
Requires-Dist: mkdocs<2.0,>=1.6.1; extra == 'all'
Requires-Dist: mkdocstrings-python>=1.1.2; extra == 'all'
Requires-Dist: mkdocstrings>=0.28.3; extra == 'all'
Requires-Dist: mlflow>=2; extra == 'all'
Requires-Dist: modal>=1.5.5; extra == 'all'
Requires-Dist: nbclient>=0.11.0; extra == 'all'
Requires-Dist: nbconvert>=7.17.2; extra == 'all'
Requires-Dist: nbformat>=5.11.1; extra == 'all'
Requires-Dist: pip-audit>=2.7; extra == 'all'
Requires-Dist: pre-commit>=4.2; extra == 'all'
Requires-Dist: pydoclint>=0.5; extra == 'all'
Requires-Dist: pygments<3.0,>=2.20; extra == 'all'
Requires-Dist: pylint>=3.3; extra == 'all'
Requires-Dist: pymdown-extensions>=11.0.1; extra == 'all'
Requires-Dist: pyright>=1.1.403; extra == 'all'
Requires-Dist: pytest-cov>=6.1.1; extra == 'all'
Requires-Dist: pytest-env>=1.0.1; extra == 'all'
Requires-Dist: pytest-json-report>=1.5.0; extra == 'all'
Requires-Dist: pytest-randomly>=3.15; extra == 'all'
Requires-Dist: pytest-split>=0.11.0; extra == 'all'
Requires-Dist: pytest-timeout>=2.1; extra == 'all'
Requires-Dist: pytest-xdist>=3.6; extra == 'all'
Requires-Dist: pytest>=9.0.3; extra == 'all'
Requires-Dist: pyyaml>=6.0; extra == 'all'
Requires-Dist: radon>=6.0; extra == 'all'
Requires-Dist: ruff>=0.15.2; extra == 'all'
Requires-Dist: toml-sort>=0.23.1; extra == 'all'
Requires-Dist: traitlets>=5.16.1; extra == 'all'
Requires-Dist: twine>=6.1; extra == 'all'
Requires-Dist: validate-pyproject>=0.23; extra == 'all'
Requires-Dist: vulture>=2.14; extra == 'all'
Requires-Dist: wandb>=0.18; extra == 'all'
Requires-Dist: xenon>=0.9; extra == 'all'
Provides-Extra: all-cpu
Requires-Dist: bandit[toml]>=1.8.6; extra == 'all-cpu'
Requires-Dist: build>=1.0.3; extra == 'all-cpu'
Requires-Dist: coverage>=7; extra == 'all-cpu'
Requires-Dist: deptry>=0.23; extra == 'all-cpu'
Requires-Dist: diff-cover>=10.6.0; extra == 'all-cpu'
Requires-Dist: griffe>=1.7.3; extra == 'all-cpu'
Requires-Dist: hypothesis>=6.100; extra == 'all-cpu'
Requires-Dist: import-linter>=2.0; extra == 'all-cpu'
Requires-Dist: interrogate>=1.5; extra == 'all-cpu'
Requires-Dist: ipykernel>=7.4.0; extra == 'all-cpu'
Requires-Dist: jupyter-client>=8.10.0; extra == 'all-cpu'
Requires-Dist: jupyter-core>=5.9.1; extra == 'all-cpu'
Requires-Dist: jupytext>=1.19.6; extra == 'all-cpu'
Requires-Dist: markdown-it-py>=4.2.0; extra == 'all-cpu'
Requires-Dist: matplotlib>=3.8; extra == 'all-cpu'
Requires-Dist: mkdocs-material>=9.7.7; extra == 'all-cpu'
Requires-Dist: mkdocs<2.0,>=1.6.1; extra == 'all-cpu'
Requires-Dist: mkdocstrings-python>=1.1.2; extra == 'all-cpu'
Requires-Dist: mkdocstrings>=0.28.3; extra == 'all-cpu'
Requires-Dist: mlflow>=2; extra == 'all-cpu'
Requires-Dist: modal>=1.5.5; extra == 'all-cpu'
Requires-Dist: nbclient>=0.11.0; extra == 'all-cpu'
Requires-Dist: nbconvert>=7.17.2; extra == 'all-cpu'
Requires-Dist: nbformat>=5.11.1; extra == 'all-cpu'
Requires-Dist: pip-audit>=2.7; extra == 'all-cpu'
Requires-Dist: pre-commit>=4.2; extra == 'all-cpu'
Requires-Dist: pydoclint>=0.5; extra == 'all-cpu'
Requires-Dist: pygments<3.0,>=2.20; extra == 'all-cpu'
Requires-Dist: pylint>=3.3; extra == 'all-cpu'
Requires-Dist: pymdown-extensions>=11.0.1; extra == 'all-cpu'
Requires-Dist: pyright>=1.1.403; extra == 'all-cpu'
Requires-Dist: pytest-cov>=6.1.1; extra == 'all-cpu'
Requires-Dist: pytest-env>=1.0.1; extra == 'all-cpu'
Requires-Dist: pytest-json-report>=1.5.0; extra == 'all-cpu'
Requires-Dist: pytest-randomly>=3.15; extra == 'all-cpu'
Requires-Dist: pytest-split>=0.11.0; extra == 'all-cpu'
Requires-Dist: pytest-timeout>=2.1; extra == 'all-cpu'
Requires-Dist: pytest-xdist>=3.6; extra == 'all-cpu'
Requires-Dist: pytest>=9.0.3; extra == 'all-cpu'
Requires-Dist: pyyaml>=6.0; extra == 'all-cpu'
Requires-Dist: radon>=6.0; extra == 'all-cpu'
Requires-Dist: ruff>=0.15.2; extra == 'all-cpu'
Requires-Dist: toml-sort>=0.23.1; extra == 'all-cpu'
Requires-Dist: traitlets>=5.16.1; extra == 'all-cpu'
Requires-Dist: twine>=6.1; extra == 'all-cpu'
Requires-Dist: validate-pyproject>=0.23; extra == 'all-cpu'
Requires-Dist: vulture>=2.14; extra == 'all-cpu'
Requires-Dist: wandb>=0.18; extra == 'all-cpu'
Requires-Dist: xenon>=0.9; extra == 'all-cpu'
Provides-Extra: all-macos
Requires-Dist: bandit[toml]>=1.8.6; extra == 'all-macos'
Requires-Dist: build>=1.0.3; extra == 'all-macos'
Requires-Dist: coverage>=7; extra == 'all-macos'
Requires-Dist: deptry>=0.23; extra == 'all-macos'
Requires-Dist: diff-cover>=10.6.0; extra == 'all-macos'
Requires-Dist: griffe>=1.7.3; extra == 'all-macos'
Requires-Dist: hypothesis>=6.100; extra == 'all-macos'
Requires-Dist: import-linter>=2.0; extra == 'all-macos'
Requires-Dist: interrogate>=1.5; extra == 'all-macos'
Requires-Dist: ipykernel>=7.4.0; extra == 'all-macos'
Requires-Dist: jax-metal>=0.1.0; extra == 'all-macos'
Requires-Dist: jupyter-client>=8.10.0; extra == 'all-macos'
Requires-Dist: jupyter-core>=5.9.1; extra == 'all-macos'
Requires-Dist: jupytext>=1.19.6; extra == 'all-macos'
Requires-Dist: markdown-it-py>=4.2.0; extra == 'all-macos'
Requires-Dist: matplotlib>=3.8; extra == 'all-macos'
Requires-Dist: mkdocs-material>=9.7.7; extra == 'all-macos'
Requires-Dist: mkdocs<2.0,>=1.6.1; extra == 'all-macos'
Requires-Dist: mkdocstrings-python>=1.1.2; extra == 'all-macos'
Requires-Dist: mkdocstrings>=0.28.3; extra == 'all-macos'
Requires-Dist: mlflow>=2; extra == 'all-macos'
Requires-Dist: modal>=1.5.5; extra == 'all-macos'
Requires-Dist: nbclient>=0.11.0; extra == 'all-macos'
Requires-Dist: nbconvert>=7.17.2; extra == 'all-macos'
Requires-Dist: nbformat>=5.11.1; extra == 'all-macos'
Requires-Dist: pip-audit>=2.7; extra == 'all-macos'
Requires-Dist: pre-commit>=4.2; extra == 'all-macos'
Requires-Dist: pydoclint>=0.5; extra == 'all-macos'
Requires-Dist: pygments<3.0,>=2.20; extra == 'all-macos'
Requires-Dist: pylint>=3.3; extra == 'all-macos'
Requires-Dist: pymdown-extensions>=11.0.1; extra == 'all-macos'
Requires-Dist: pyright>=1.1.403; extra == 'all-macos'
Requires-Dist: pytest-cov>=6.1.1; extra == 'all-macos'
Requires-Dist: pytest-env>=1.0.1; extra == 'all-macos'
Requires-Dist: pytest-json-report>=1.5.0; extra == 'all-macos'
Requires-Dist: pytest-randomly>=3.15; extra == 'all-macos'
Requires-Dist: pytest-split>=0.11.0; extra == 'all-macos'
Requires-Dist: pytest-timeout>=2.1; extra == 'all-macos'
Requires-Dist: pytest-xdist>=3.6; extra == 'all-macos'
Requires-Dist: pytest>=9.0.3; extra == 'all-macos'
Requires-Dist: pyyaml>=6.0; extra == 'all-macos'
Requires-Dist: radon>=6.0; extra == 'all-macos'
Requires-Dist: ruff>=0.15.2; extra == 'all-macos'
Requires-Dist: toml-sort>=0.23.1; extra == 'all-macos'
Requires-Dist: traitlets>=5.16.1; extra == 'all-macos'
Requires-Dist: twine>=6.1; extra == 'all-macos'
Requires-Dist: validate-pyproject>=0.23; extra == 'all-macos'
Requires-Dist: vulture>=2.14; extra == 'all-macos'
Requires-Dist: wandb>=0.18; extra == 'all-macos'
Requires-Dist: xenon>=0.9; extra == 'all-macos'
Provides-Extra: cuda-dev
Requires-Dist: bandit[toml]>=1.8.6; extra == 'cuda-dev'
Requires-Dist: build>=1.0.3; extra == 'cuda-dev'
Requires-Dist: coverage>=7; extra == 'cuda-dev'
Requires-Dist: deptry>=0.23; extra == 'cuda-dev'
Requires-Dist: import-linter>=2.0; extra == 'cuda-dev'
Requires-Dist: interrogate>=1.5; extra == 'cuda-dev'
Requires-Dist: jax[cuda12]<0.11.2,>=0.11.1; extra == 'cuda-dev'
Requires-Dist: modal>=1.5.5; extra == 'cuda-dev'
Requires-Dist: pip-audit>=2.7; extra == 'cuda-dev'
Requires-Dist: pre-commit>=4.2; extra == 'cuda-dev'
Requires-Dist: pydoclint>=0.5; extra == 'cuda-dev'
Requires-Dist: pylint>=3.3; extra == 'cuda-dev'
Requires-Dist: pyright>=1.1.403; extra == 'cuda-dev'
Requires-Dist: pyyaml>=6.0; extra == 'cuda-dev'
Requires-Dist: radon>=6.0; extra == 'cuda-dev'
Requires-Dist: ruff>=0.15.2; extra == 'cuda-dev'
Requires-Dist: toml-sort>=0.23.1; extra == 'cuda-dev'
Requires-Dist: twine>=6.1; extra == 'cuda-dev'
Requires-Dist: validate-pyproject>=0.23; extra == 'cuda-dev'
Requires-Dist: vulture>=2.14; extra == 'cuda-dev'
Requires-Dist: xenon>=0.9; extra == 'cuda-dev'
Provides-Extra: cuda12
Requires-Dist: jax[cuda12]<0.11.2,>=0.11.1; extra == 'cuda12'
Provides-Extra: dev
Requires-Dist: bandit[toml]>=1.8.6; extra == 'dev'
Requires-Dist: build>=1.0.3; extra == 'dev'
Requires-Dist: coverage>=7; extra == 'dev'
Requires-Dist: deptry>=0.23; extra == 'dev'
Requires-Dist: import-linter>=2.0; extra == 'dev'
Requires-Dist: interrogate>=1.5; extra == 'dev'
Requires-Dist: modal>=1.5.5; extra == 'dev'
Requires-Dist: pip-audit>=2.7; extra == 'dev'
Requires-Dist: pre-commit>=4.2; extra == 'dev'
Requires-Dist: pydoclint>=0.5; extra == 'dev'
Requires-Dist: pylint>=3.3; extra == 'dev'
Requires-Dist: pyright>=1.1.403; extra == 'dev'
Requires-Dist: pyyaml>=6.0; extra == 'dev'
Requires-Dist: radon>=6.0; extra == 'dev'
Requires-Dist: ruff>=0.15.2; extra == 'dev'
Requires-Dist: toml-sort>=0.23.1; extra == 'dev'
Requires-Dist: twine>=6.1; extra == 'dev'
Requires-Dist: validate-pyproject>=0.23; extra == 'dev'
Requires-Dist: vulture>=2.14; extra == 'dev'
Requires-Dist: xenon>=0.9; extra == 'dev'
Provides-Extra: docs
Requires-Dist: griffe>=1.7.3; extra == 'docs'
Requires-Dist: mkdocs-material>=9.7.7; extra == 'docs'
Requires-Dist: mkdocs<2.0,>=1.6.1; extra == 'docs'
Requires-Dist: mkdocstrings-python>=1.1.2; extra == 'docs'
Requires-Dist: mkdocstrings>=0.28.3; extra == 'docs'
Requires-Dist: pygments<3.0,>=2.20; extra == 'docs'
Requires-Dist: pymdown-extensions>=11.0.1; extra == 'docs'
Provides-Extra: metal
Requires-Dist: jax-metal>=0.1.0; extra == 'metal'
Provides-Extra: mlflow
Requires-Dist: mlflow>=2; extra == 'mlflow'
Provides-Extra: modal
Requires-Dist: modal>=1.5.5; extra == 'modal'
Provides-Extra: notebooks
Requires-Dist: ipykernel>=7.4.0; extra == 'notebooks'
Requires-Dist: jupyter-client>=8.10.0; extra == 'notebooks'
Requires-Dist: jupyter-core>=5.9.1; extra == 'notebooks'
Requires-Dist: jupytext>=1.19.6; extra == 'notebooks'
Requires-Dist: markdown-it-py>=4.2.0; extra == 'notebooks'
Requires-Dist: nbclient>=0.11.0; extra == 'notebooks'
Requires-Dist: nbconvert>=7.17.2; extra == 'notebooks'
Requires-Dist: nbformat>=5.11.1; extra == 'notebooks'
Requires-Dist: pyyaml>=6.0; extra == 'notebooks'
Requires-Dist: traitlets>=5.16.1; extra == 'notebooks'
Provides-Extra: plots
Requires-Dist: matplotlib>=3.8; extra == 'plots'
Provides-Extra: test
Requires-Dist: coverage>=7; extra == 'test'
Requires-Dist: diff-cover>=10.6.0; extra == 'test'
Requires-Dist: hypothesis>=6.100; extra == 'test'
Requires-Dist: ipykernel>=7.4.0; extra == 'test'
Requires-Dist: jupyter-client>=8.10.0; extra == 'test'
Requires-Dist: jupyter-core>=5.9.1; extra == 'test'
Requires-Dist: jupytext>=1.19.6; extra == 'test'
Requires-Dist: markdown-it-py>=4.2.0; extra == 'test'
Requires-Dist: matplotlib>=3.8; extra == 'test'
Requires-Dist: nbclient>=0.11.0; extra == 'test'
Requires-Dist: nbconvert>=7.17.2; extra == 'test'
Requires-Dist: nbformat>=5.11.1; extra == 'test'
Requires-Dist: pytest-cov>=6.1.1; extra == 'test'
Requires-Dist: pytest-env>=1.0.1; extra == 'test'
Requires-Dist: pytest-json-report>=1.5.0; extra == 'test'
Requires-Dist: pytest-randomly>=3.15; extra == 'test'
Requires-Dist: pytest-split>=0.11.0; extra == 'test'
Requires-Dist: pytest-timeout>=2.1; extra == 'test'
Requires-Dist: pytest-xdist>=3.6; extra == 'test'
Requires-Dist: pytest>=9.0.3; extra == 'test'
Requires-Dist: pyyaml>=6.0; extra == 'test'
Requires-Dist: traitlets>=5.16.1; extra == 'test'
Provides-Extra: testing
Requires-Dist: pytest>=9.0.3; extra == 'testing'
Provides-Extra: wandb
Requires-Dist: wandb>=0.18; extra == 'wandb'
Description-Content-Type: text/markdown

# Substrax

<!-- --8<-- [start:summary] -->
**Training, testing and CI infrastructure for JAX/Flax NNX, so a project does not write its
own.** It configures the JAX process, lays arrays out across devices, builds optimizers, saves and
restores state, decides when to stop, logs the run and sends it to a GPU. In tests it runs code in
fresh interpreters, counts compiles and checks gradients. Its CI gates, composite actions and
pre-commit hooks can be reused from any repository.

Every Avitai JAX package imports this layer instead of carrying its own copy, so each concern has
one implementation and one test suite. Substrax imports none of those packages, so it works on its
own.
<!-- --8<-- [end:summary] -->

[![CI](https://github.com/avitai/substrax/actions/workflows/ci.yml/badge.svg)](https://github.com/avitai/substrax/actions/workflows/ci.yml)
[![Docs](https://readthedocs.org/projects/substrax/badge/?version=latest)](https://substrax.readthedocs.io)
[![PyPI](https://img.shields.io/pypi/v/substrax.svg)](https://pypi.org/project/substrax/)

[Documentation](https://substrax.readthedocs.io) · [Changelog](CHANGELOG.md) · [Issues](https://github.com/avitai/substrax/issues)

> **Research preview.** The API changes between releases while the stack is under active
> development. Pin a version.

## Where it sits

The Avitai dependency chain:

```text
substrax → calibrax → datarax → artifex → opifex
```

The domain packages built on them (DiffBio, DiffAV, cellifex, fluctifex, seismifex, pertrax)
depend on it too.

Each concern has one home and one test suite:

<!-- --8<-- [start:subpackages] -->
| Subpackage | What it owns |
| --- | --- |
| `substrax.runtime` | `JaxRuntime` process settings rendered as the environment of a process that has not imported jax, or applied to the current one; XLA flags merged by name; test-run device emulation; entry-point logging |
| `substrax.artifacts` | Output directories resolved from an argument, `AVITAI_OUTPUT_DIR` or a per-run temporary directory, never the working tree |
| `substrax.rng` | Keys from an explicit owner (`key_from`, no default seed), streams derived from a seed by name (`rngs_from_seed`), `split_key` and the interpreter-stable `fold_in_name` |
| `substrax.optim` | `OptimizerConfig` in optax's terms, `create_transformation` and `create_optimizer` over optax with the schedule as the base learning rate and the weight-decay filter as a static mask, `current_learning_rate` read on device, `switch_at` from one transformation to another at a step, `update_with_line_search` for L-BFGS-style optimizers, `with_strong_state_types` |
| `substrax.testing` | Opt-in test infrastructure: fresh-interpreter runs with a chosen JAX configuration and typed reports (`report`, `report_as`), trace, compile and work counters (`TraceCounter`, `substrax.testing.compiles`, `counted_calls`), value-asserting NNX gradient checks (`substrax.testing.gradients`), the shared example tests a repository configures in pyproject and runs with `substrax-notebooks test` (`substrax.testing.example_suite`, with the `notebooks` extra), and a pytest plugin with `x64`, `devices` and `accelerator` markers and jax configuration isolation |
| `substrax.devices` | `detect_devices()` (platform, device kind, count), `require_gpu()` (raises `GPUUnavailableError` unless the default backend is a GPU), `DeviceLike` and `visible_devices()` for typed device parameters, device placement, the batch-size recommendation table, and the `substrax-devices` command (`--require-gpu` exits 1 unless the default backend is a GPU) |
| `substrax.mesh` | Device meshes with `Auto` axes by default, mesh rules and partition-spec helpers, sharding strategies (data, FSDP, tensor, pipeline, multi-dimensional) on `flax.nnx.spmd` |
| `substrax.spmd` | Data-parallel sharding, batch placement from a sharding or a prefix of the batch, `spmd_train_step`, and metric collectives |
| `substrax.checkpoint` | One `CheckpointStore` protocol and one Orbax implementation, `OrbaxCheckpointStore`, over `CheckpointManager` |
| `substrax.callbacks` | The training-callback protocol, `CallbackList`, `BestMetricTracker`, `EarlyStopping` and `EarlyStoppingCallback` |
| `substrax.tracking` | Step-wise experiment logging with console, file, Weights & Biases and MLflow backends |
| `substrax.compute` | A project's jobs run on a compute backend: the job spec, the worker every backend runs, the `ComputeBackend` protocol with `local`, `modal` and `skypilot` backends found through entry points, the accelerator, CPU and memory a job requests, a manifest recording the devices a run got, and the `substrax-compute` command |
| `substrax.notebooks` | An example script's clean notebook written from it (`convert`) and the read-only check that the committed notebook is exactly the one `convert` writes (`check_pair`); a clean copy executed from the repository root within one budget for the whole run, with its provenance (`substrax.notebooks.run.execute_example`); the repository's settings, read from `[tool.substrax.examples]` (`substrax.notebooks.config`); the example's docs page made from that run, opening with the example's title, then the command that runs it, with every output and figure of the run, its provenance and no local paths (`generate_page`), the checks of a committed page against the script and against a run of it (`check_page`, `compare_with_run`); the example guide's mechanical rules checked on one example (`substrax.notebooks.conformance.check_example`); the `substrax-notebooks` command (`convert`, `check`, `page`, `test`) and the `example-conformance` pre-commit hook, which runs `check` on changed examples; the rules they apply are the shared example guide, `docs/guides/writing-examples.md`, with its template; installed with the `notebooks` extra |
| `substrax.typing`, `substrax.nnx_typing`, `substrax.records`, `substrax.examples` | The shared type aliases (`PyTree`, `JsonValue`, `CheckpointState`; `NnxState` and `PathEntry` over jax and flax), typed reading and writing of JSON records, and a repository's example scripts with each one's path from the root |
<!-- --8<-- [end:subpackages] -->

Not in Substrax: optimizer algorithms and schedules (optax, which Substrax assembles from a
config), loss scaling and gradient accumulation
(`flax.training.dynamic_scale.DynamicScale`, `optax.MultiSteps`), profiling and hardware
spec tables (calibrax), data pipelines (datarax), models and trainers (artifex, opifex).

## Installation

```bash
uv add substrax          # or: pip install substrax
uv add "substrax[wandb]"  # Weights & Biases backend
uv add "substrax[mlflow]" # MLflow backend
uv add "substrax[testing]" # pytest plugin and fresh-interpreter test helpers
uv add "substrax[notebooks]" # convert, check and page examples; with testing, test them
uv add "substrax[modal]"   # the Modal compute backend
```

<!-- --8<-- [start:requirements] -->
Substrax requires Python 3.12 or later (CI runs 3.12 and 3.13), `jax` and `jaxlib` 0.11.1,
`flax>=0.12.9`, `optax>=0.2.8`, `orbax-checkpoint>=0.11.33`, `etils[epath]>=1.14.0`,
`numpy>=1.24,<2.6` and `pydantic>=2.10`. jax is capped below 0.11.2 until a flax release works with it
(`pyproject.toml` records why). The `cuda12` and `metal` extras select the JAX backend.
<!-- --8<-- [end:requirements] -->

## Quick start

One data-parallel step over every visible device, a checkpoint, and an early-stopping
decision. The same code runs on one CPU; on several devices the batch is sharded on its
leading axis and XLA inserts the gradient all-reduce.

```python
import jax
import jax.numpy as jnp
import optax
from flax import nnx

from substrax.callbacks import EarlyStopping
from substrax.checkpoint import OrbaxCheckpointStore
from substrax.devices import detect_devices
from substrax.mesh import DeviceMeshManager
from substrax.spmd import create_data_parallel_sharding, place_batch_on_shards, spmd_train_step

info = detect_devices()  # DeviceInfo(platform='cpu', kind=<DeviceKind.CPU>, count=1, ...)

model = nnx.Linear(8, 1, rngs=nnx.Rngs(0))
optimizer = nnx.Optimizer(model, optax.adam(1e-3), wrt=nnx.Param)

mesh = DeviceMeshManager.create_device_mesh({"data": info.count})
sharding = create_data_parallel_sharding(mesh)
batch = place_batch_on_shards(
    {"x": jnp.ones((32, 8)), "y": jnp.zeros((32, 1))},
    sharding,
)


def loss_fn(model: nnx.Module, batch: dict[str, jax.Array]) -> jax.Array:
    return jnp.mean((model(batch["x"]) - batch["y"]) ** 2)


stopper = EarlyStopping(patience=3, min_delta=1e-4)
with OrbaxCheckpointStore("checkpoints/quick-start", max_to_keep=2) as store:
    for step in range(5):
        with jax.set_mesh(mesh):
            loss = spmd_train_step(model, optimizer, loss_fn, batch)
        store.save(step, {"model": nnx.state(model)}, metrics={"loss": float(loss)})
        stopper.update(float(loss))  # True when the loss improved on the best so far
        if stopper.should_stop:
            break

    latest = store.latest_step()
    checkpoint = store.restore(latest, templates={"model": nnx.state(model)})
    nnx.update(model, checkpoint.items["model"])
    assert checkpoint.metadata.metrics["loss"] == float(loss)
```

## The subpackages

### Runtime

`JaxRuntime` declares the settings a JAX process starts with: backends, CPU device count,
64-bit types, matmul precision, compilation cache, XLA flags and accelerator memory.
`runtime_environment` renders them for a process that has not imported jax, and
`apply_runtime` applies them to the current one, refusing any setting jax would no longer
read.

```python
import os
import subprocess
import sys

from substrax.runtime import JaxRuntime, runtime_environment

runtime = JaxRuntime(platforms=("cpu",), cpu_devices=8)
env = {**os.environ, **runtime_environment(runtime, os.environ)}
program = "import jax; print(jax.device_count())"
subprocess.run([sys.executable, "-c", program], env=env, check=True)  # prints 8
```

XLA flags merge by name: a flag already set to a different value raises
`XlaFlagConflictError` instead of being replaced. `resolve_test_runtime` picks a test run's
backend and emulated CPU devices, and `configure_entry_point_logging` sets up logging from
`main()` without `force=True`.

### Artifacts

`resolve_output_dir` picks where a run writes its outputs: an explicit directory, then
`$AVITAI_OUTPUT_DIR/<name>`, then a directory created once per process under the system
temporary directory. It never defaults into the working tree, so running an example or a
test cannot overwrite tracked files.

```python
from substrax.artifacts import resolve_output_dir

location = resolve_output_dir("darcy_training")
figure_path = location.path / "prediction.png"
print(location.source)  # "argument", "environment" or "run_default"
```

A caller that chooses the directory passes it as `explicit`. An example's figures reach its
docs page as the output its run captures, never as files it writes into `docs/`.

### Testing

`run_python` runs code in a fresh interpreter with the JAX settings a test chooses, and the opt-in
pytest plugin adds device markers and fails a test that changes jax's global configuration, as
jax's own test harness does.
`TraceCounter` asserts how many times a jitted function traced, and
`substrax.testing.compiles.expect_compiles(n)` how many XLA programs a block built, for example
that a second training step compiles nothing. `counted_calls` counts the Python functions a block
and the threads it starts run, and with `substrax.testing.jax_calls` its compiled dispatches and
placements, so a test bounds a code path's work per iteration by count instead of time.
`substrax.testing.gradients` checks a module's
gradient in its parameters or its input against finite differences in float64 and returns it, so
a test asserts the gradient's value, not only that it exists. For Flax NNX libraries,
`substrax.testing.nnx_rules` finds seed literals, `nnx.Rngs` probes and fallbacks, ignored
`trainable=` metadata, salted hashes, modes `.eval()` cannot reach or a call-time flag overrides,
and no-op `super().__init__()` in source; `substrax.testing.nnx_premises` measures the framework
facts those rules rest on; and `substrax.testing.nnx_conformance` checks each module class under
NNX's transforms (tree mode, `.eval()`, `nnx.view`, `nnx.jit`, `nnx.vmap`, gradients). A child sends its result with
`report(value)`, on a channel no library writes to, and `report_as(shape)` reads it validated
against a `TypedDict` or another type. A repository's example tests are
`substrax.testing.example_suite`, configured in its pyproject and run by
`substrax-notebooks test`.

```python
# conftest.py
pytest_plugins = ["substrax.testing.pytest_plugin"]

# test_sharding.py
import pytest

from substrax.runtime import JaxRuntime
from substrax.testing import run_python


@pytest.mark.devices(2)
def test_on_two_devices() -> None: ...


def test_eight_emulated_devices() -> None:
    program = "import jax; from substrax.testing import report; report(jax.device_count())"
    result = run_python(program, runtime=JaxRuntime(cpu_devices=8), timeout=120)
    assert result.check().report_as(int) == 8
```

### Devices

`detect_devices()` is the one reading of the hardware the whole stack shares.

```python
from substrax.devices import DeviceKind, detect_devices

info = detect_devices()
assert info.platform in {"cpu", "gpu", "tpu", "metal"}
if info.kind is DeviceKind.GPU:
    print(f"{info.count} GPU(s): {info.device_kinds}")
```

`place_on_device(pytree, device)` moves a pytree, and `get_batch_size_recommendation()`
reads the per-hardware batch-size table. jaxlib ships no type stubs for `jax.Device`, so
substrax annotates devices with the `DeviceLike` protocol, which a `jax.Device` satisfies, and
`visible_devices()` returns `jax.devices()` typed as it.

`require_gpu()` returns the devices when jax's default backend is a GPU and raises
`GPUUnavailableError`, naming the backend, otherwise, so GPU work stops before it starts rather
than running on the CPU. `substrax-devices` prints the platform, jax's version, the default
backend and each visible device (`--json` for one JSON object), and `--require-gpu` exits 1 unless
the default backend is a GPU, the check a GPU job runs before its work.

### Mesh and SPMD

`DeviceMeshManager.create_device_mesh` takes the mesh shape as a mapping from axis name
to size and builds every axis as `Auto` unless `axis_types` says otherwise: with jax 0.11
that is what lets XLA infer the sharding of the backward pass over a batch sharded on the
`data` axis.

```python
import jax
from substrax.mesh import DeviceMeshManager, data_parallel_rules, create_named_sharding
from substrax.spmd import create_data_parallel_sharding

mesh = DeviceMeshManager.create_device_mesh({"data": jax.device_count()})
print(DeviceMeshManager.get_mesh_info(mesh))  # {'total_devices': 1, 'axes': {'data': 1}} on one device

batch_sharding = create_data_parallel_sharding(mesh)      # leading axis over "data"
replicated = create_named_sharding(mesh, None)             # every device holds a copy
rules = data_parallel_rules()                              # MeshRules for nnx.spmd
```

The strategies in `substrax.mesh.strategies` (`DataParallelStrategy`, `FSDPStrategy`,
`TensorParallelStrategy`, `PipelineParallelStrategy`, `MultiDimensionalStrategy`) build
partition specs for a `ParallelismConfig`; `substrax.spmd` adds `spmd_train_step`, `all_gather`
and the `reduce_*` collectives. A data-parallel gradient is reduced by the compiler under
`jax.jit`, and inside `jax.shard_map` by averaging the loss before differentiating; averaging the
gradient afterwards is wrong by the axis size (see `substrax.spmd`).

### Checkpoint

`OrbaxCheckpointStore` writes a step-addressed store: a checkpoint is a step holding named
items, the things a training loop owns (`model`, `optimizer`, `rng`, `data_iterator`,
`extensions`), each a `PyTreeSave` item, beside one `CheckpointMetadata` record. Restoring
onto templates places every array on its template's device, so a checkpoint written on
`cuda:0` restores in a CPU-only process.

```python
from flax import nnx
from substrax.checkpoint import OrbaxCheckpointStore

model = nnx.Linear(4, 4, rngs=nnx.Rngs(0))
with OrbaxCheckpointStore("checkpoints/demo", max_to_keep=3) as store:
    store.save(100, {"model": nnx.state(model)}, epoch=2, metrics={"loss": 0.25})
    store.save(200, {"model": nnx.state(model)}, metrics={"loss": 0.20})

    assert store.list_steps() == [100, 200]
    assert store.best_step("loss") == 200
    fresh = nnx.Linear(4, 4, rngs=nnx.Rngs(1))
    checkpoint = store.restore(100, templates={"model": nnx.state(fresh)})
    nnx.update(fresh, checkpoint.items["model"])
    assert checkpoint.metadata.epoch == 2

    as_stored = store.restore(200).items["model"]  # no template: the item as it was stored
```

Writes are strict: an existing step is refused unless `overwrite=True`, a step below the
latest is refused, and each refusal is a `CheckpointNotWrittenError` naming the reason. A
template that does not fit the checkpoint's arrays raises `ValueError`, which is how a store
written for another architecture is refused rather than loaded. A checkpoint whose metadata
names another format is refused with `UnsupportedCheckpointError` rather than read as this
one.

### Callbacks

`EarlyStopping` is the plain tracker: `update(value)` records a metric and returns
whether it improved on the best by more than `min_delta`, and `should_stop` is true once
`patience` updates in a row have not. `EarlyStoppingCallback` is the same rule as a
training callback that a trainer drives
through `on_epoch_end`, with `check_finite`, `stopping_threshold` and
`divergence_threshold` from its `EarlyStoppingConfig`.

```python
from substrax.callbacks import EarlyStopping

stopper = EarlyStopping(patience=2, min_delta=0.01, mode="min")
improved = []
for step, loss in enumerate([1.0, 0.5, 0.49, 0.495, 0.5]):
    improved.append(stopper.update(loss))
    if stopper.should_stop:
        break
assert improved == [True, True, False, False]  # 0.49 is not 0.01 better than 0.5
assert step == 3  # two updates in a row without improvement
```

### Tracking

Every logger has the same surface (`log_scalar`, `log_scalars`, `log_hyperparams`,
`log_text`, `log_image`, `log_histogram`, `close`).
`create_logger` gives console output plus a file under `log_dir`; `WandbLogger` and
`MLFlowLogger` need the `wandb` and `mlflow` extras and import their SDK at construction,
so a missing extra fails at the call site, not at import time.

```python
from substrax.tracking import create_logger

logger = create_logger("demo", log_dir="logs")
logger.log_hyperparams({"lr": 1e-3, "batch_size": 32})
for step in range(3):
    logger.log_scalar("loss", 1.0 / (step + 1), step=step)
logger.close()
```

```python
from substrax.tracking import MLFlowLogger, WandbLogger

wandb_logger = WandbLogger("demo", project="my-project", config={"lr": 1e-3})
mlflow_logger = MLFlowLogger("demo", experiment_name="my-experiment")
```

### Compute

A project declares its jobs in `pyproject.toml`, and `substrax-compute` runs them on a backend:
this machine (`local`), Modal (`modal`, with `substrax[modal]`), or any cloud SkyPilot reaches
(`skypilot`, driving the `sky` command of SkyPilot installed as its documentation says). Every
backend runs the same worker. It runs each task from the project root with the job's JAX
settings, writes the task's logs beside whatever it saves through `resolve_output_dir`, and
records a manifest. The outputs come back to this machine, never into the working tree unless
asked.

```toml
[tool.substrax.compute]
backend = "modal"

[tool.substrax.compute.backends.modal]
outputs_volume = "demo-outputs"

[tool.substrax.compute.jobs.examples]
examples = ["examples"]
examples_mode = "page"                   # or "test"
extras = ["cuda12"]
resources = { accelerator = { kind = "L4" }, cpu = 8, memory_mib = 32768 }
timeout_seconds = 1800
runtime = { platforms = ["cuda", "cpu"], xla_flags = ["--xla_gpu_deterministic_ops=true"] }

[tool.substrax.examples]                 # each example's budget, substrax.notebooks.config
source_url = "https://github.com/avitai/demo/blob/main"
budget_seconds = 600
```

An `examples` job runs each example as its clean notebook, one task each, on the project's
interpreter: `examples_mode = "test"` runs `substrax-notebooks test` on it (its run compared with
its committed page), and `"page"` makes its page with `substrax-notebooks page --into-outputs`, so
a page that needs a GPU comes back with the run's files to be committed. The project needs
`substrax[notebooks,testing]` in the extras the job installs.

```bash
uv run substrax-compute run examples                       # follow, wait, fetch
uv run substrax-compute run examples --accelerator H100 --detach
uv run substrax-compute status
```

A job's `resources` are requests: Modal receives them as `gpu`, `cpu` and `memory`, SkyPilot as
minimums. The run's manifest records the JAX platform and the kind of each device the run
actually got, so a substituted GPU shows in the record.

A provider is added by registering a factory in the `substrax.compute.backends` entry-point
group; `substrax.testing.compute.BackendContract` holds the tests every backend must pass.

### Notebooks

An example is written once, as a script in jupytext's percent format under `examples/`. Its clean
notebook is generated from it, and its docs page is made by running a clean copy, so the page
shows what the code does today. A repository configures its examples in its pyproject and runs
the shared checks with one command (`substrax[notebooks,testing]`, and git 2.30 or later):

```toml
[tool.substrax.examples]
source_url = "https://github.com/avitai/<repository>/blob/main"
budget_seconds = 600
```

```bash
uv run substrax-notebooks convert examples/sorting.py  # write its clean notebook
uv run substrax-notebooks check examples/sorting.py    # the guide's rules, without a run
uv run substrax-notebooks page examples/sorting.py     # run it and write its docs page
uv run substrax-notebooks test                         # run and check every example
```

`test` runs pytest with a configuration of substrax's own, so none of the repository's unit-test
settings reach an example's run, and a repository's tests of an example's results, in
`tests/examples`, read the session's one run through the `example_run` fixture. The rules are the
shared example guide, `docs/guides/writing-examples.md`, which starts from
`docs/guides/example_template.py`; the `example-conformance` pre-commit hook runs `check` on the
examples and the recipes (`recipes/<path>.py`, an example's published-scale run) a commit changes.

## Development setup

```bash
git clone https://github.com/avitai/substrax.git
cd substrax
./setup.sh
source ./activate.sh
```

`setup.sh` creates the environment with `uv`, syncs the `dev` and `test` extras plus the
backend extra for this machine, and writes the managed environment file `.substrax.env`
that `activate.sh` loads. A user-owned `.env` is never modified.

| Flag | Effect |
| --- | --- |
| `--backend <auto\|cpu\|cuda12\|metal>` | Choose the backend policy; `auto` resolves to `cuda12` on Linux with a visible NVIDIA GPU, `metal` on Apple Silicon, otherwise `cpu` |
| `--python <version>` | Create the environment with a specific Python version |
| `--extra <name>` | Sync an additional extra (repeatable), e.g. `--extra docs` |
| `--recreate` | Remove the existing `.venv` before syncing |
| `--force-clean` | Remove `.venv`, `.substrax.env` and repo-local test artifacts |
| `--dry-run` | Print the resolved backend and the `uv` commands without changing files |

Run the checks the way CI does:

```bash
uv run --locked pytest
uv run --locked pre-commit run --all-files
uv run --locked mkdocs build --strict --clean
```

CI also requires 80 percent coverage of the lines a pull request changes; CONTRIBUTING.md gives
the local `diff-cover` command. The test suite also runs as a pre-commit hook, so a commit takes a few seconds longer
than a lint pass.

## Documentation

<https://substrax.readthedocs.io> — one page per subpackage under *API Reference*.

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md). Security reports go to the address in
[SECURITY.md](SECURITY.md), not to a public issue.

## License

MIT — see [LICENSE](LICENSE).
