# Multi-Node Training

Source: https://docs.surogate.ai/engine/guides/multi-node/

When one machine isn't enough, you can train across several. Surogate uses [Ray](https://www.ray.io/) to manage the cluster and NCCL for fast GPU-to-GPU communication. This guide shows how to set up and run a multi-node job.

## Overview

In multi-node training:
- Ray manages the cluster and coordinates work across nodes.
- NCCL handles GPU-to-GPU communication (InfiniBand when available, TCP otherwise).
- Each node drives all its local GPUs with the threaded backend (see [Multi-GPU training](/engine/guides/multi-gpu/)).
- Data is sharded across nodes automatically, so each node works on its own part.

## Setup

### 1. Start the Ray Cluster

On your head node (the main machine), start Ray:

```bash
ray start --head --port=6379
```

Ray prints the head node's IP address. Note it down: the worker nodes need it to connect.

On each worker node, connect to the head node:

```bash
ray start --address='<head-node-ip>:6379'
```

Replace `<head-node-ip>` with the IP address the head node printed.

### 2. Configure Your Training

Add a `distributed` section to your training config:

```yaml
# Your existing config...
model: meta-llama/Llama-3.1-8B
per_device_train_batch_size: 2
sequence_len: 2048

# Multi-node configuration
distributed:
  ray_address: "auto"          # Connect to existing Ray cluster
  num_nodes: 2                 # Total number of nodes
  gpus_per_node: 8             # GPUs per node (0 = use config.gpus)
  worker_output_dir: null      # Optional: shared directory for tokenized data
```

The options (also in the [config reference](/engine/reference/config/#multi-node-distributed-training)):
- `ray_address`: how to connect to Ray
  - `"auto"`: connect to an existing cluster (recommended)
  - `"local"`: start a local Ray instance (for single-node testing)
  - `"ray://host:port"`: connect to a specific head node
- `num_nodes`: total number of nodes to use
- `gpus_per_node`: GPUs per node (leave at 0 to use `gpus` from the main config)
- `worker_output_dir`: optional directory for worker-local data (defaults to `/tmp/surogate-{run_name}`)

### 3. Run Training

Start training from the head node:

```bash
surogate sft config.yaml
```

Surogate detects the `distributed` section ([`surogate sft`](/engine/reference/cli/#sft) works the same as on one machine), then:
1. Spawns one Ray worker per node.
2. Each node downloads the model on its own.
3. Each node tokenizes its own data shard (1/num_nodes of the dataset).
4. All nodes synchronize before initializing NCCL.
5. Training runs, with gradients synchronized across nodes.

## How It Works

### Data Sharding

Each node processes a different part of your dataset:
- Training data is split automatically: node 0 gets samples 0, N, 2N, ...; node 1 gets samples 1, N+1, 2N+1, ...
- Each node tokenizes only its shard, which saves memory and runs in parallel.
- Validation data is replicated on all nodes, so metrics are consistent.

### Model Synchronization

- All nodes start with identical model weights.
- During training, each node computes gradients on its local data.
- NCCL synchronizes gradients across nodes after each training step.
- Every node applies the same optimizer update, so the weights stay in sync.

### Network Communication

Surogate configures NCCL for you:
- It uses InfiniBand/RoCE when available, for maximum bandwidth.
- It falls back to TCP sockets over standard network interfaces.
- It detects the right network interface on each node.

## Monitoring

The head node logs training progress:

```
Starting distributed training with 2 nodes...
  Nodes: 2
  GPUs per node: 8
  Total GPUs: 16
  Tokens per step: 524288
  Max steps: 1000

Step 0/1000 | Loss: 2.3456 | Norm: 1.23 | LR: 1.00e-05 | 2.34s | 223891 tok/s
Step 1/1000 | Loss: 2.2891 | Norm: 1.18 | LR: 2.00e-05 | 2.31s | 226926 tok/s
...
```

The logged metrics are averaged across all nodes.

## Checkpointing and Export

- Only node 0 saves checkpoints and exports the final model.
- All nodes take part in checkpoint synchronization (NCCL barriers).
- Checkpoints go to the `output_dir` on the head node.
- LoRA adapters are exported in PEFT-compatible format.

## Troubleshooting

### Connection Issues

If nodes can't communicate:
1. Check that firewall rules allow traffic on the required ports.
2. Check that all nodes can reach each other: `ping <node-ip>`.
3. Read the NCCL logs in `/tmp/nccl_debug_node_*.log` (if debug is enabled).

### Performance Tips

- Use InfiniBand or other high-bandwidth networking.
- Give all nodes identical GPU configurations.
- Put `worker_output_dir` on a shared filesystem (NFS, Lustre) so tokenized data is cached across runs.
- Increase `gradient_accumulation_steps` to communicate less often.

### Ray Cluster Management

View cluster status:
```bash
ray status
```

Stop all Ray processes:
```bash
ray stop
```

## Example: Training Llama 3.1 8B on 2 Nodes

```yaml
# config.yaml
model: meta-llama/Llama-3.1-8B
datasets:
  - path: timdettmers/openassistant-guanaco
    type: auto

per_device_train_batch_size: 4
sequence_len: 2048
gradient_accumulation_steps: 4
num_epochs: 3

learning_rate: 2e-5
warmup_steps: 100

output_dir: ./output/llama-3.1-8b-guanaco

distributed:
  ray_address: "auto"
  num_nodes: 2
  gpus_per_node: 8
```

Start Ray on both nodes, then run:
```bash
surogate sft config.yaml
```

This configuration trains on 16 GPUs total (2 nodes × 8 GPUs) with an effective batch size of 256 sequences per step (4 per GPU × 4 accumulation steps × 16 GPUs).

Next: [Multi-GPU training](/engine/guides/multi-gpu/) explains the ZeRO levels each node uses, and the [config reference](/engine/reference/config/#multi-node-distributed-training) lists every `distributed` option.
