Fault-tolerant training with torchft#

Warning

This integration is in alpha. The API may change, and several limitations apply. It requires Ray 2.62.0 or later, or a nightly build.

torchft is a PyTorch library that introduces primitives for fault-tolerant training. The Ray Train integration brings torchft to Ray Train by using these primitives so that training keeps running through a worker failure. The surviving workers continue, Ray Train replaces only the failed worker, and the replacement recovers model and optimizer state from a live peer over the network instead of loading a checkpoint.

Compare this with default fault tolerance, where any worker failure shuts down every worker, and the restarted worker group resumes from the latest checkpoint. The torchft integration avoids both costs: healthy workers don’t restart, and recovery doesn’t read a checkpoint from storage. This matters most for large data-parallel jobs with frequent failures, such as training on spot or preemptible instances, where full restarts and checkpoint reloads add up.

How it works#

torchft splits a data-parallel job into replica groups, each holding a full copy of the model. Training is data-parallel across replica groups. Two torchft components coordinate them:

  • The Lighthouse is a coordination server that decides, every step, which replica groups are part of the current quorum, the set of replica groups that train together.

  • A Manager runs in every worker’s training function. It talks to the Lighthouse, rebuilds the cross-replica communicator when membership changes, and skips the optimizer step on every replica if any replica failed mid-step, so the model stays consistent.

When you pass torch_config=TorchftConfig(...) to a TorchTrainer, Ray Train does the following:

  • Starts the torchft Lighthouse as a Ray actor on the node that runs the Ray Train controller, which is usually the head node, and sets the TORCHFT_LIGHTHOUSE address on every worker.

  • Makes each Ray Train worker its own replica group and creates one process group per replica group. This integration supports DistributedDataParallel (DDP) only, so each replica group has exactly one worker.

  • On a worker failure, replaces only the failed replica group, in the same placement group bundles, instead of shutting down and restarting the whole worker group.

The following figure shows these components during normal training:

Diagram of Ray Train with torchft during normal training. On the head node, the Ray Train controller starts the torchft Lighthouse. The Lighthouse connects to the Manager in each of three workers and decides each step's quorum. Each worker is its own replica group with a Manager and a model copy, and the workers average gradients with allreduce.

Ray Train with torchft during normal training.#

When a worker fails mid-step, torchft discards that step on the surviving workers instead of committing a partial update. If at least min_replicas replica groups survive, they keep training without the failed one. Meanwhile, Ray Train starts a replacement worker. The replacement’s Manager joins the quorum and heals: it copies the current model and optimizer state from a live peer over the network, then trains as a full member. If fewer than min_replicas replica groups survive, each surviving worker’s Manager waits up to its quorum_timeout, 60 seconds by default, for the replacement to join. If the replacement doesn’t join in time, the surviving workers fail too, and Ray Train handles that as another worker failure.

The following figure shows the four steps of recovering from a worker failure:

Four steps of recovering from a worker failure. First, worker 1 crashes in the middle of a step. Second, the surviving workers discard the step and keep training if at least min_replicas remain. Third, Ray Train starts a new worker 1 in the same placement group bundle. Fourth, the new worker 1 copies model and optimizer state from a live peer and rejoins the quorum.

Recovering from a worker failure.#

Requirements#

  • Ray 2.62.0 or later, or a nightly build.

  • torchft installed on every node, with a PyTorch version that your torchft version supports. The APIs this guide uses are available in torchft 0.2.0 and later.

  • A training function written for DDP. See the limitations for what the integration doesn’t support.

Note

Ray 2.56 through 2.61 include an earlier version of this integration that fails to start when the head node has no logical CPUs, which is common on production clusters.

Quick start#

The following example shows a complete PyTorch training script with torchft fault tolerance. The highlighted lines are the changes relative to a standard Ray Train script, and each Step comment matches a subsection after the script:

from datetime import timedelta

import numpy as np
import torch
import torch.nn as nn
from torchft import (
    DistributedDataParallel,
    DistributedSampler,
    Manager,
    Optimizer,
    ProcessGroupGloo,
)
from torchft.checkpointing.pg_transport import PGTransport

import ray.train
from ray.train import FailureConfig, RunConfig, ScalingConfig
from ray.train.torch import TorchftConfig, TorchTrainer


class LinearDataset(torch.utils.data.Dataset):
    """y = a * x + b"""

    def __init__(self, a, b, size=1000):
        x = np.arange(0, 10, 10 / size, dtype=np.float32)
        self.x = torch.from_numpy(x)
        self.y = torch.from_numpy(a * x + b)

    def __getitem__(self, index):
        return self.x[index, None], self.y[index, None]

    def __len__(self):
        return len(self.x)


def train_func(config):
    num_steps = config.get("num_steps", 100)
    min_replicas = config.get("min_replicas", 1)

    context = ray.train.get_context()
    world_rank = context.get_world_rank()
    world_size = context.get_world_size()

    model = nn.Linear(1, 1)
    optimizer = torch.optim.SGD(model.parameters(), lr=1e-2)
    loss_fn = nn.MSELoss()

    # Step 1: Create the Manager.
    pg = ProcessGroupGloo(timeout=timedelta(seconds=30))
    transport = PGTransport(
        pg,
        timeout=timedelta(seconds=30),
        device=torch.device("cpu"),
    )

    def load_state_dict(state_dict):
        model.load_state_dict(state_dict["model"])
        optimizer.load_state_dict(state_dict["optim"])

    def state_dict():
        return {
            "model": model.state_dict(),
            "optim": optimizer.state_dict(),
        }

    manager = Manager(
        pg=pg,
        min_replica_size=min_replicas,
        load_state_dict=load_state_dict,
        state_dict=state_dict,
        world_size=1,
        rank=0,
        replica_id=f"train_ddp_{world_rank}",
        timeout=timedelta(seconds=60),
        checkpoint_transport=transport,
    )

    # Step 2: Wrap the model and optimizer.
    model = DistributedDataParallel(manager, model)
    optimizer = Optimizer(manager, optimizer)

    # Step 3: Shard the data.
    train_dataset = LinearDataset(2, 5)
    sampler = DistributedSampler(
        train_dataset,
        replica_rank=world_rank,
        num_replica_groups=world_size,
        group_rank=0,
        num_replicas=1,
        shuffle=False,
    )
    train_loader = torch.utils.data.DataLoader(
        train_dataset, batch_size=4, sampler=sampler
    )

    # Step 4: Train by step count, not epochs.
    train_iter = iter(train_loader)
    while manager.current_step() < num_steps:
        try:
            X, y = next(train_iter)
        except StopIteration:
            train_iter = iter(train_loader)
            X, y = next(train_iter)

        optimizer.zero_grad()
        pred = model(X)
        loss = loss_fn(pred, y)
        loss.backward()
        optimizer.step()

    ray.train.report({"loss": loss.item()})

    # Step 5: Shut down the Manager.
    manager.shutdown()


# Step 6: Configure the trainer.
trainer = TorchTrainer(
    train_func,
    train_loop_config={"num_steps": 100, "min_replicas": 1},
    scaling_config=ScalingConfig(num_workers=2),
    torch_config=TorchftConfig(lighthouse_kwargs={"min_replicas": 1}, backend="gloo"),
    run_config=RunConfig(failure_config=FailureConfig(max_failures=3)),
)
result = trainer.fit()

Step 1: Create the Manager#

Create a torchft process group and a Manager with state_dict and load_state_dict callbacks. Use ProcessGroupGloo on CPU or ProcessGroupNCCL on GPU, and set the process group timeouts high enough to re-form the group after a replica fails. The callbacks must include both the model and the optimizer state, because they’re what a replacement replica group heals from. Because each Ray Train worker is its own replica group, pass world_size=1, rank=0, and a replica_id that’s unique per worker, such as one derived from the Ray Train world rank. Set min_replica_size to the same value as the Lighthouse’s min_replicas. The optional checkpoint_transport configures how state transfers between peers during healing. PGTransport sends it over the process group.

Step 2: Wrap the model and optimizer#

Wrap the model with torchft.DistributedDataParallel and the optimizer with torchft.Optimizer. These replace ray.train.torch.prepare_model(), so don’t call it. The wrapped optimizer starts quorum negotiation on zero_grad() and commits the step on step() only if the whole quorum finished it.

Step 3: Shard the data#

Shard the dataset with torchft.DistributedSampler instead of ray.train.torch.prepare_data_loader(). It shards first across replica groups, then across the ranks within each group. With DDP, each group has one rank, so pass group_rank=0 and num_replicas=1.

Step 4: Train by step count, not epochs#

Loop on while manager.current_step() < num_steps. The Manager’s step count advances across failures, so a replacement replica group continues from the current step instead of starting over. Epoch-based loops don’t work, because torchft doesn’t transfer the data iterator position to a replacement worker.

The example calls ray.train.report() once, after the loop, when all workers are present. See the limitations for why reporting while a replica group is missing doesn’t complete.

Step 5: Shut down the Manager#

Call manager.shutdown() at the end of the training function. Without it, a worker that rejoins late can hang in backward(), waiting for peers that already finished.

Step 6: Configure the trainer#

Pass a TorchftConfig as the torch_config, with at least min_replicas in lighthouse_kwargs. Also set max_failures in FailureConfig to 1 or higher. Otherwise, the first worker failure ends the run instead of replacing the failed replica group.

Configure the Lighthouse#

TorchftConfig(lighthouse_kwargs=...) passes its keyword arguments to the torchft.coordination.LighthouseServer constructor. The torchft version you install defines the accepted keys. As of torchft 0.2.0, they’re the following:

  • min_replicas (required): The minimum number of replica groups that must be alive to form a quorum. With min_replicas equal to num_workers, any failure pauses training until the replacement joins. With a smaller value, training continues on the survivors while Ray Train starts the replacement.

  • bind: The address the Lighthouse listens on. Ray Train defaults this to "[::]:0", which picks a free port.

  • join_timeout_ms, quorum_tick_ms, heartbeat_timeout_ms: Quorum timing parameters. See the torchft documentation for details.

Also pass the same value as min_replica_size to the Manager in your training function. Both settings count replica groups, not workers within a replica group. The Manager commits a step only if at least min_replica_size replica groups took part in it.

TorchftConfig forwards its remaining keyword arguments, such as backend, to TorchConfig.

Behavior on a worker failure#

What happens when a worker fails depends on min_replicas and max_failures. The following table shows the behavior for a run with two workers when one fails mid-training:

min_replicas

max_failures

Behavior

1

1

The surviving replica group keeps training without replaying the interrupted step. Ray Train replaces the failed worker, and the replacement heals and rejoins.

2

0

The run raises immediately. Ray Train never replaces a replica group when max_failures is 0.

2

1

Training pauses below the quorum size, resumes when the replacement joins, and replays the interrupted step.

In every recovered case, the interrupted step doesn’t commit a partial update. Either the quorum replays it, or the survivors skip it and move on. Each replica group replacement counts against max_failures.

Limitations#

This integration is in alpha. The following limitations apply:

  • DDP only, with one worker per replica group. The integration doesn’t support fully sharded data parallel (FSDP), hybrid sharded data parallel (HSDP), or tensor or pipeline parallelism.

  • No Ray Data support. Load data with a PyTorch DataLoader and torchft.DistributedSampler, as in the preceding example.

  • Step-based training only. torchft doesn’t transfer the data iterator position to a replacement worker, so training can skip or repeat batches around a failure. Train for a fixed number of steps.

  • With min_replicas smaller than num_workers, ray.train.report() doesn’t complete while a replica group is missing, because it waits for all num_workers workers. Call it only when all workers are present, such as once at the end of training, or set min_replicas equal to num_workers if you rely on frequent reporting.

  • The Lighthouse runs on the node that runs the Ray Train controller, with no persistence. If that node fails, the job fails, and job driver fault tolerance applies as usual.

  • The worker count stays fixed. Ray Train replaces failed workers in place but doesn’t resize the worker group. For adapting the worker count to resource availability, see Elastic training.

Next steps#

  • Default fault tolerance: Checkpoint-based recovery, which also covers job driver failures.

  • Elastic training: Adapt the worker count to resource availability.

  • torchft: The torchft repository, with its design notes and the train_ddp.py example.