Skip to content

Updated example scripts and README #93

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 15 additions & 56 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ By [Apoorv Khandelwal](https://apoorvkh.com) and [Peter Curtin](https://github.c

---

**`torchrunx`** is a *functional* utility for distributing PyTorch code across devices. This is a [more convenient, robust, and featureful](#torchrunx-uniquely-offers) alternative to CLI-based launchers, like `torchrun`, `accelerate launch`, and `deepspeed`.
**`torchrunx`** is a *functional* utility for distributing PyTorch code across devices. This is a [more convenient, robust, and featureful](https://torchrun.xyz/features.html) alternative to CLI-based launchers, like `torchrun`, `accelerate launch`, and `deepspeed`.

It enables complex workflows within a single script and has useful features even if only using 1 GPU.

Expand All @@ -29,20 +29,13 @@ Requires: Linux. If using multiple machines: SSH & shared filesystem.

Suppose we have some distributed training function (which needs to run on every GPU):

```python
def distributed_training(model: nn.Module, num_steps: int) -> nn.Module: ...
```

<details>
<summary><b>Implementation of <code>distributed_training</code> (click to expand)</b></summary>

```python
from __future__ import annotations
import os
import torch
import torch.nn as nn

def distributed_training(num_steps: int = 10) -> nn.Module | None:
def distributed_training(output_dir: str, num_steps: int = 10) -> str | None:
rank = int(os.environ['RANK'])
local_rank = int(os.environ['LOCAL_RANK'])

Expand All @@ -62,10 +55,13 @@ def distributed_training(num_steps: int = 10) -> nn.Module | None:
optimizer.step()

if rank == 0:
return model.cpu()
```
os.makedirs(output_dir, exist_ok=True)
checkpoint_path = os.path.join(output_dir, "model.pt")
torch.save(model, checkpoint_path)
return checkpoint_path

</details>
return None
```

We can distribute and run this function (e.g. on 2 machines x 2 GPUs) using **`torchrunx`**!

Expand All @@ -82,18 +78,20 @@ launcher = torchrunx.Launcher(

results = launcher.run(
distributed_training,
num_steps = 10
output_dir = "outputs",
num_steps = 10,
)
```

Once completed, you can retrieve the results and process them as you wish.

```python
trained_model: nn.Module = results.rank(0)
# or: results.index(hostname="localhost", local_rank=0)
checkpoint_path: str = results.rank(0)
# or: results.index(hostname="localhost", local_rank=0)

# and continue your script
torch.save(trained_model.state_dict(), "outputs/model.pth")
model = torch.load(checkpoint_path, weights_only=False)
model.eval()
```

**See more examples where we fine-tune LLMs using:**
Expand All @@ -102,43 +100,4 @@ torch.save(trained_model.state_dict(), "outputs/model.pth")
- [PyTorch Lightning](https://torchrun.xyz/examples/lightning.html)
- [Accelerate](https://torchrun.xyz/examples/accelerate.html)

**Refer to our [API](https://torchrun.xyz/api.html) and [Usage](https://torchrun.xyz/usage/general.html) for many more capabilities!**

---

## `torchrunx` uniquely offers

1. **An automatic launcher that "just works" for everyone** 🚀

> `torchrunx` is an SSH-based, pure-Python library that is universally easy to install.<br>
> No system-specific dependencies and orchestration for *automatic* multi-node distribution.

2. **Conventional CLI commands** 🖥️

> Run familiar commands, like `python my_script.py ...`, and customize arguments as you wish.
>
> Other launchers override `python` in a cumbersome way: e.g. `torchrun --nproc_per_node=2 --nnodes=2 --node_rank=0 --master_addr=100.43.331.111 --master_port=1234 my_script.py ...`.

3. **Support for more complex workflows in a single script** 🎛️

> Your workflow may have steps that are complex (e.g. pre-train, fine-tune, test) or may different parallelizations (e.g. training on 8 GPUs, testing on 1 GPU). In these cases, CLI-based launchers require each step to live in its own script. Our library treats these steps in a modular way, so they can cleanly fit together in a single script!
>
>
> We clean memory leaks as we go, so previous steps won't crash or adversely affect future steps.

4. **Better handling of system failures. No more zombies!** 🧟

> With `torchrun`, your "work" is inherently coupled to your main Python process. If the system kills one of your workers (e.g. due to RAM OOM or segmentation faults), there is no way to fail gracefully in Python. Your processes might hang for 10 minutes (the NCCL timeout) or become perpetual zombies.
>
>
> `torchrunx` decouples "launcher" and "worker" processes. If the system kills a worker, our launcher immediately raises a `WorkerFailure` exception, which users can handle as they wish. We always clean up all nodes, so no more zombies!

5. **Bonus features** 🎁

> - Return objects from distributed functions.
> - [Automatic detection of SLURM environments.](https://torchrun.xyz/usage/slurm.html)
> - Start multi-node training from Python notebooks!
> - Our library is fully typed!
> - Custom, fine-grained handling of [logging](https://torchrun.xyz/usage/logging.html), [environment variables](https://torchrun.xyz/usage/general.html#environment-variables), and [exception propagation](https://torchrun.xyz/usage/general.html#exceptions). We have nice defaults too: no more interleaved logs and irrelevant exceptions!

**On our [roadmap](https://github.com/apoorvkh/torchrunx/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement): higher-order parallelism, support for debuggers, and more!**
**Refer to our [API](https://torchrun.xyz/api.html), [Features](https://torchrun.xyz/features.html), and [Usage](https://torchrun.xyz/usage/general.html) for many more capabilities!**
7 changes: 5 additions & 2 deletions docs/source/artifacts/accelerate_help.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,15 @@ usage: accelerate_train.py [-h] [OPTIONS]
│ ``"/etc/ssh/ssh_config"``. (default: None) │
│ --launcher.backend {None,nccl,gloo,mpi,ucc} │
│ `Backend │
│ <https://pytorch.org/docs/stable/distributed.html#torch.distributed.B… │
│ <https://pytorch.org/docs/stable/distributed.html#torch.distributed.Ba │
│ ckend>`_ │
│ for worker process group. By default, NCCL (GPU backend). │
│ Use GLOO for CPU backend. ``None`` for no process group. │
│ (default: nccl) │
│ --launcher.timeout INT
│ --launcher.worker-timeout INT │
│ Worker process group timeout (seconds). (default: 600) │
│ --launcher.agent-timeout INT │
│ Agent communication timeout (seconds). (default: 180) │
│ --launcher.copy-env-vars [STR [STR ...]] │
│ Environment variables to copy from the launcher process to workers. │
│ Supports Unix pattern matching syntax. (default: PATH LD_LIBRARY │
Expand Down
8 changes: 6 additions & 2 deletions docs/source/artifacts/argparse_cli_help.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
usage: -c [-h] [--hostnames HOSTNAMES [HOSTNAMES ...]]
[--workers-per-host WORKERS_PER_HOST [WORKERS_PER_HOST ...]]
[--ssh-config-file SSH_CONFIG_FILE]
[--backend {nccl,gloo,mpi,ucc,None}] [--timeout TIMEOUT]
[--backend {nccl,gloo,mpi,ucc,None}]
[--worker-timeout WORKER_TIMEOUT] [--agent-timeout AGENT_TIMEOUT]
[--copy-env-vars COPY_ENV_VARS [COPY_ENV_VARS ...]]
[--extra-env-vars [EXTRA_ENV_VARS ...]] [--env-file ENV_FILE]

Expand All @@ -21,7 +22,10 @@ torchrunx:
--backend {nccl,gloo,mpi,ucc,None}
For worker process group. Default: 'nccl'. Use 'gloo'
for CPU. 'None' to disable.
--timeout TIMEOUT Worker process group timeout in seconds. Default: 600.
--worker-timeout WORKER_TIMEOUT
Worker process group timeout in seconds. Default: 600.
--agent-timeout AGENT_TIMEOUT
Agent communication timeout in seconds. Default: 180.
--copy-env-vars COPY_ENV_VARS [COPY_ENV_VARS ...]
Environment variables to copy to workers. Supports
Unix pattern matching.
Expand Down
8 changes: 5 additions & 3 deletions docs/source/artifacts/deepspeed_help.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[2025-02-23 16:02:38,914] [WARNING] [real_accelerator.py:181:get_accelerator] Setting accelerator to CPU. If you have GPU or other accelerator, we were unable to detect it.
[2025-02-23 16:02:38,930] [INFO] [real_accelerator.py:222:get_accelerator] Setting ds_accelerator to cpu (auto detect)
[2025-06-25 15:33:02,489] [INFO] [real_accelerator.py:222:get_accelerator] Setting ds_accelerator to cuda (auto detect)
Warning: The cache directory for DeepSpeed Triton autotune, /users/akhand10/.triton/autotune, appears to be on an NFS system. While this is generally acceptable, if you experience slowdowns or hanging when DeepSpeed exits, it is recommended to set the TRITON_CACHE_DIR environment variable to a non-NFS path.
usage: deepspeed_train.py [-h] [OPTIONS]

╭─ options ──────────────────────────────────────────────────────────────────╮
Expand Down Expand Up @@ -42,8 +42,10 @@ usage: deepspeed_train.py [-h] [OPTIONS]
│ for worker process group. By default, NCCL (GPU backend). │
│ Use GLOO for CPU backend. ``None`` for no process group. │
│ (default: nccl) │
│ --launcher.timeout INT
│ --launcher.worker-timeout INT │
│ Worker process group timeout (seconds). (default: 600) │
│ --launcher.agent-timeout INT │
│ Agent communication timeout (seconds). (default: 180) │
│ --launcher.copy-env-vars [STR [STR ...]] │
│ Environment variables to copy from the launcher process to workers. │
│ Supports Unix pattern matching syntax. (default: PATH LD_LIBRARY │
Expand Down
7 changes: 5 additions & 2 deletions docs/source/artifacts/lightning_help.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,15 @@ usage: lightning_train.py [-h] [OPTIONS]
│ ``"/etc/ssh/ssh_config"``. (default: None) │
│ --launcher.backend {None,nccl,gloo,mpi,ucc} │
│ `Backend │
│ <https://pytorch.org/docs/stable/distributed.html#torch.distributed.B… │
│ <https://pytorch.org/docs/stable/distributed.html#torch.distributed.Ba │
│ ckend>`_ │
│ for worker process group. By default, NCCL (GPU backend). │
│ Use GLOO for CPU backend. ``None`` for no process group. │
│ (default: nccl) │
│ --launcher.timeout INT
│ --launcher.worker-timeout INT │
│ Worker process group timeout (seconds). (default: 600) │
│ --launcher.agent-timeout INT │
│ Agent communication timeout (seconds). (default: 180) │
│ --launcher.copy-env-vars [STR [STR ...]] │
│ Environment variables to copy from the launcher process to workers. │
│ Supports Unix pattern matching syntax. (default: PATH LD_LIBRARY │
Expand Down
Loading