Ravex
Checkpoint and resume for PyTorch training, from one decorator on the function
that trains. Inside that function nothing changes: Ravex notices the model, the
optimizer, the LR scheduler, the AMP scaler and the dataloader as they are
built, counts every optimizer.step(), and writes a checkpoint on the cadence
you configured. If the process dies, running the same command again picks up
where it stopped.
Install
pip install ravex
Ravex is pure Python and needs Python 3.11 or later. It does not depend on torch, so that it attaches to whatever build you already have (CUDA, ROCm, CPU) instead of pulling another one in. On a machine without torch, install it first, the build for your hardware from pytorch.org, or for a quick try on a CPU:
pip install torch --index-url https://download.pytorch.org/whl/cpu
On Python 3.10 or older pip install ravex stops with "No matching
distribution found for ravex": every release that said it ran there is yanked.
Check python --version.
torch's CPU wheels do not bring NumPy, and torch says so on import with a
UserWarning: Failed to initialize NumPy. It is torch's and harmless, and
pip install numpy silences it; with NumPy installed Ravex also restores its
RNG on a resume.
Its default checkpoint engine is Moonclip,
installed with pip install "ravex[moonclip]". Moonclip publishes wheels for
Linux on x86_64 and aarch64 and for macOS on Apple silicon; elsewhere it has
to be built from source, and where it is not installed Ravex says so and falls
back to torch_save.
Use
This runs as it is, on a CPU, in a few seconds. Save it as train.py:
import torch
import ravex
@ravex.train_loop(max_steps=2000)
def train():
torch.manual_seed(0)
model = torch.nn.Sequential(torch.nn.Linear(16, 64), torch.nn.ReLU(), torch.nn.Linear(64, 1))
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
x = torch.randn(4096, 16)
data = torch.utils.data.TensorDataset(x, x.sum(dim=1, keepdim=True))
loader = torch.utils.data.DataLoader(data, batch_size=32, shuffle=True)
for epoch in range(100):
for x, y in loader:
loss = torch.nn.functional.mse_loss(model(x), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if ravex.step() % 200 == 0:
print(f"step {ravex.step()} loss {loss.item():.4f}")
train()
python train.py # press Ctrl-C after a few lines
python train.py # the first line is past where you stopped, not step 200
Ctrl-C ends in Python's traceback for KeyboardInterrupt, as in any script;
the line just above it says the run was not lost:
ravex: stopped; step 600 is saved in ./checkpoints, and the same command resumes from it
The checkpoints are in ./checkpoints; delete it to start over. Ravex says
two things on stderr, whatever the log level: where the first checkpoint went,
and, on a restart, the step it came back at:
ravex: resumed from step 1400 in ./checkpoints; it stops at step 2000 (max_steps)
announce=False silences them; nothing is sent anywhere.
Set max_steps. It is the length of the whole training across restarts,
and it is what makes a resumed run end where the uninterrupted one would have:
without it, the resumed script runs its own for epoch in range(100) from the
top again, from the step it came back at, and trains more than the run that
never stopped. For longer examples, each of which the test suite stops and
resumes: examples/train_mlp.py, a DataLoader loop;
examples/train_gpt.py, a small GPT with nanoGPT's
loop, batches drawn with torch.randint and no DataLoader; and
examples/train_ddp.py, two processes with DDP on a
CPU under torchrun.
A resumed run continues rather than restarting from a good place, because Ravex restores everything around the weights too: optimizer state, LR scheduler, AMP loss scale, the torch, CUDA, Python and NumPy RNGs, and the position in the dataset. The test suite holds it to the strong form of that: a run killed at step 20 and resumed produces the same losses, step by step, and the same final weights as the run that was never interrupted.
On SIGTERM (a spot preemption, scancel, docker stop) the training stops at
the next iteration, writes a final checkpoint and exits with status 143; run
the same command again and it resumes there. That is on by default, and
preemption_handler=False turns it off. Any other keyword argument to train_loop is a
configuration override, and an unknown name raises TypeError rather than
being ignored.
The decorator is the only way in: nothing is ever checkpointed by code that does not say so. Importing Ravex does nothing until a decorated function is called, and its patches on PyTorch come off when that function returns or raises.
What it charts on its own. With nothing in the script but the decorator:
the learning rate, the time per step and the gradient norm; for a language
model the tokens per second per GPU and the MFU (on a GPU Ravex knows the peak
of); histograms per layer of the weights, the gradients, the update-to-weight
ratio and the activations, for the embedding, the first, middle and last block
and the head; and the machine's GPU, CPU and memory. Log the loss as
train/loss (and val/loss) with ravex.log_metrics and the perplexity comes
with it. The full list, and how each is measured, is in
docs/configuration.md.
When "noticed on its own" is a guess, such as two models of which only one
trains, or an optimizer built before the function was entered, name it with
ravex.track(model, optimizer). The one moment a checkpoint is consistent,
the top of an iteration, Ravex takes from the DataLoader iterator or, in a
loop without one, from the first forward of the trained model after each
step; ravex.batch_boundary() hands it over by hand where neither is seen.
Configuration
ravex.yaml, at or above the working directory:
checkpoint_every: 500 # optimizer steps between checkpoints (default 100); see below for Moonclip
backend: moonclip # moonclip | torch_save
storage:
type: local # local | s3 | r2
path: ./checkpoints
keep_last: 5
max_steps: null # stop at this step however many times the process restarted
sharded_checkpoints: gather # gather | per_rank, for FSDP
Every option is also read from a RAVEX_* environment variable, which wins
over the file, and the keyword arguments to train_loop win over both. A
resume is the default (resume: true); RAVEX_ENABLED=0 turns Ravex off for
one run without touching the code.
How often it saves. With torch_save, a checkpoint every
checkpoint_every steps, and keep_last of them are kept. With Moonclip, the
default, Ravex saves a small delta against the last full snapshot at every
step, so a crash costs at most one step; checkpoint_every is then how often
the store is synced to a bucket and the window it keeps (the last that many
steps and the full they stand on), and keep_last is not used. A run of 147
steps holds about a hundred snapshots: that is the design, not a leak.
delta: false goes back to one full save every checkpoint_every
(docs).
Precision. save_dtype (Moonclip only) stores parts of the checkpoint at
a lower precision to make it smaller. It is lossy: a run resumed from a
bf16 optimizer state is close to, not identical with, the run that never
stopped. Leave it unset when a resume must be exact
(docs).
Storage. Ravex decides when to save and what, and puts it back into the
live objects; Moonclip decides how the bytes are written and where, bucket
included. So storage says where the bucket is, and the credentials are never
read by Ravex or from the config file: Moonclip reads them from
MOONCLIP_S3_ACCESS_KEY / MOONCLIP_S3_SECRET_KEY, the usual AWS_* pair, a
profile in ~/.aws/credentials, or the machine's IAM role
(Moonclip's README). Restoring
unpickles part of a checkpoint, so give write access to the bucket only to
what you would let run code on your training machines.
More than one GPU or machine. DDP and FSDP resume on every rank. With FSDP,
gather writes one checkpoint that loads at any world size, bounded by what
rank 0 can hold; per_rank has each rank write its own shard, which is much
cheaper and resumes only at the same world size (reshard_on_resume handles a
different one after a restart). Across machines without a bucket or a shared
filesystem, replicate_every copies each rank's store to a peer on another
machine, so losing one machine costs at most that many checkpoints; with a
bucket, a rank that comes up with an empty disk pulls its store back. Ravex
also trains across slow links between distant nodes with an outer loop that
exchanges parameter differences every outer_inner_steps instead of gradients
every step.
The full option list, with the measurements behind the defaults: docs/configuration.md. How the patches, the step count and the resume work: docs/how-it-works.md.
Next to other tools
- PyTorch Lightning, Accelerate, the Hugging Face Trainer have their own checkpointing, resumed by passing the checkpoint back. Ravex works under them as under a plain loop, since it hooks PyTorch itself, and also puts back the counter their loop stops on; it warns when the framework's own checkpointing would save the same thing twice. Use one of the two.
- torch DCP is a format and a save call; Ravex decides when to save, what,
and how to put it back into a live run, and writes through Moonclip or
torch.save(DCP is read, to resume from a checkpoint another framework wrote:convert_foreign). - W&B, MLflow keep working as they are: Ravex does not touch their calls,
and its own
log_metricsis optional. Runs already logged there come over as Ravex stores of their own, scalars only, withravex import wandb entity/project/run_id --storage DIR(it needs thewandbpackage),ravex import neptune ./exports/data --storage DIRfor the Parquet filesneptune-exporterwrites (it needspyarrow;--runpicks one run where they hold several), orravex import table metrics.csv --storage DIRfor any CSV or JSONL file of metrics, a row per step or a row per value;ravex shipthen sends one to a backend like any other run.
Versioning and compatibility
Ravex is 0.x. A patch release (the last number) only fixes. A minor release
may change an option's default or remove what was deprecated, each said in the
CHANGELOG; what is removed warns for at least one minor release first. A
newer Ravex resumes runs an older one wrote. An older one does not resume a
newer one's checkpoint: it says so and starts from scratch, so pin a minor
version (ravex~=0.13.0) for a run that may restart on another machine.
Python 3.11 and later, each for as long as CPython supports it.
Limits
- Under HuggingFace
Trainerand Lightning the state comes back exactly, but with shuffling and dropout on, the resumed run sees a different random draw, because the framework drives the dataloader and the RNG on its own schedule. Plain loops, DDP and FSDP replay exactly. - An
IterableDatasethas no index sampler, so its position cannot be replayed; everything else is still restored. - A sharded model gets no final checkpoint at exit, since collecting one is a collective and ranks stop being in lockstep at shutdown; the newest checkpoint is the last periodic one.
- A failed checkpoint is lost, logged, and tried again at the next one;
a failure inside Ravex never stops the training (
fallback_on_error).
What changed between versions is in the CHANGELOG.
Ravex and GPU Zero
GPU Zero is a hosted service built on Ravex and Moonclip: it shows a run's metrics and checkpoints, resumes or forks it from any checkpoint, and starts GPUs in your own cloud account for it. Ravex does not need it, and sends it nothing unless a run is given its address.
Development
pip install -e ".[dev]"
pytest tests/unit
tests/unit runs in one process on any OS. tests/distributed and
integration/ start several processes, use torchrun or kill a process with
SIGKILL, and need Linux. The integration tests run in their own image, with
--init so that the SIGKILL they send is not a no-op:
docker build -f integration/Dockerfile -t ravex-integration .
docker run --rm --init ravex-integration
Licence
Apache-2.0 — GPU Zero
Metadata
Release files for ravex 0.14.9
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ravex-0.14.9.tar.gz | 464.3 kB | Without provenance | Details for ravex-0.14.9.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ravex-0.14.9-py3-none-any.whl | Python 3 | none | any | Details for ravex-0.14.9-py3-none-any.whl |
Total release size: 889.9 kB
Release files / ravex-0.14.9.tar.gz
| Download URL | ravex-0.14.9.tar.gz |
|---|---|
| Size | 464.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
cce479c94fbeea399c5af7649ef723d32037cc383c678a3c74e90074ccd1299d
|
|
BLAKE2b-256 checksum How to use checksums |
45e1f98b736b3e8008c45fdfee3f3681face09e2fd9da71cb3862927da28aa04
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.12.16
|
Release files / ravex-0.14.9-py3-none-any.whl
| Download URL | ravex-0.14.9-py3-none-any.whl |
|---|---|
| Size | 425.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4f0330f72d9301303b828aaa692099d87ae5b714a3f84fb19fd7892fc331b14f
|
|
BLAKE2b-256 checksum How to use checksums |
d2aa5d395f31dbb5be9c53c992c89fe87ca852aa6099a233fb8fea00c9b8ec28
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.12.16
|
Security for ravex 0.14.9
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.