# Multi-GPU Training

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

With several GPUs you can train faster and fit larger models and datasets. Surogate splits the work across GPUs with data parallelism and tuned communication patterns.

## Training Models That Don't Fit on a Single GPU

Surogate's ZeRO implementation (stages 1-3), together with [CPU offloading](/engine/guides/offloading/), lets you train models that need more memory than one GPU has. There are limits, though.

What ZeRO lets you do:
- Train models whose base weights fit on one GPU, but whose weights, optimizer states, gradients and activations together don't.
- Example: a 7B model (14 GB weights) that needs 66 GB in total can train on 4x 24GB GPUs with ZeRO-3.
- Memory savings grow with the number of GPUs: ZeRO-3 divides optimizer states, gradients and weight storage by the GPU count.

What ZeRO can't do:
- Train models whose base weights alone exceed the memory of one GPU.
- Example: a 70B model (140 GB in BF16) cannot be trained even with ZeRO-3 on 8x 80GB GPUs.
- The reason: during the forward and backward passes, weights are rebuilt with all-gather operations, so each GPU must briefly hold full weight tensors.

Extending capacity with CPU offloading:
Combine ZeRO with CPU offloading (`offload_optimizer`, `offload_master`, `offload_grads`, `offload_residual`) to use CPU RAM as overflow storage and train even larger models. This can extend capacity by 2-3x, depending on your CPU RAM and PCIe bandwidth.

:::note
For models whose base weights alone exceed single-GPU memory, use [Dispatch Pipeline Parallelism (dispatch-PP)](/engine/guides/dispatch-pp/). It is a model-parallel mode that streams the base weights from pinned CPU memory per stage and passes activations between GPUs through host memory, so it works on PCIe-only boxes without NVLink/P2P. (Classic tensor parallelism, which splits weights across GPUs during computation, needs a fast GPU-to-GPU interconnect.)
:::

## Multi-Threading vs Multiprocessing

On a single node there are two ways to drive several GPUs:

1. **One process per GPU (multiprocessing)**: this sidesteps Python's Global Interpreter Lock (GIL) and scales beyond one node, so it suits distributed training across machines.

2. **Multiple threads in a single process (multi-threading)**: this is Surogate's main focus. Threads share an address space, so GPUs can copy memory directly to each other without IPC handles, which is faster for single-node multi-GPU training.

Surogate supports both, but it is tuned for the multi-threaded setup and its direct communication.

## Data Parallelism with ZeRO-1

On multiple GPUs, Surogate shards optimizer states (ZeRO-1) by default. This beats traditional Distributed Data Parallel (DDP) with replicated optimizer states in every case: it uses less memory and doesn't add communication.

The model is replicated on each GPU and the input data is split across them. Each GPU processes its share of the data, computes gradients, and then synchronizes gradients with the other GPUs before the parameters are updated.

## Kernel Fusion and Communication Optimization

To save memory bandwidth and run faster, Surogate fuses kernels aggressively.

### Fused Operations

To avoid needless round trips to device memory, Surogate fuses every run of successive operations that contains neither a global reduction nor a matrix multiplication. The main fusions:

- **Non-linearity operators**: every non-linearity has an extra output that returns the abs-max of its result, so FP8 quantization needs no extra memory read.
- **RMS-norm and residual addition**: one joint kernel handles both and also returns the abs-max of the RMS-norm output.
- **Transpose and quantize**: FP8 GEMM on consumer GPUs supports only the TN (transpose:non-transpose) layout, so Surogate does the required transposes itself in a fused transpose+quantize kernel.
- **Cross-entropy loss**: the forward and backward passes run in one kernel, so the large per-token loss tensor is never materialized.

Together these cut memory traffic and raise training throughput, most of all in [FP8](/engine/guides/precision-and-recipes/#fp8-hybrid).

## LM-Head and Embeddings: Replication Strategy

Language models have a large vocabulary, so the LM-head (language modeling head) costs far more compute and communication than a regular transformer block. Surogate handles this imbalance with a dedicated strategy.

### Replication Instead of Sharding

Surogate replicates the LM-head and token embeddings on each GPU instead of sharding them across workers. This has two advantages:

- **Less frequent synchronization**: LM-head gradients only need to be synchronized at the last gradient accumulation step, not at every step.
- **Better communication overlap**: the LM-head sits in its own buffer, apart from the double-buffered transformer blocks, so its gradient communication can overlap with computation in the backward pass.

### Communication Overlap Strategies

During the last backward pass:

1. **LM-head gradient communication** overlaps with computing the gradients of the last two transformer blocks, whose weights are still on the GPU from the preceding forward pass.
2. **Backward matrix scheduling**: of the two backward matrices in the LM-head gradient, the weight gradient is computed first, so communication can overlap with the input gradient calculation.

The more you chunk gradient accumulation, the less this helps, because gradient communication can only start in the last chunk.

### Token Embeddings Limitation

For token embeddings, the next operation after the backward pass is the global norm reduction of the gradients. There is no computation to overlap with that communication, so its latency can't be hidden.

## Configuration Parameters

### `gpus`

The number of GPUs to train on.

- **Default**: `1` (uses the first available GPU)
- **Special value**: `0` uses all available GPUs

Example:

```yaml
gpus: 4 # Use 4 GPUs
```

The effective batch size grows with the number of GPUs:

```
Effective batch size = per_device_batch_size × gradient_accumulation_steps × gpus
```

### `zero_level`

Sets the ZeRO (Zero Redundancy Optimizer, see the [glossary](/engine/appendix/glossary/)) level, which decides how optimizer states, gradients and weights are partitioned across GPUs to save memory.

- **Default**: `1`

| Level | Description              | What's Sharded                               |
| ----- | ------------------------ | -------------------------------------------- |
| 1     | Sharded optimizer states | Optimizer states (momentum, variance)        |
| 2     | Sharded gradients        | Optimizer states + gradients                 |
| 3     | Sharded weights          | Optimizer states + gradients + model weights |

Example:

```yaml
zero_level: 2 # Shard optimizer states and gradients
```

Higher ZeRO levels use less memory per GPU but communicate more. ZeRO-3 shards weights for storage, but full weights are rebuilt with all-gather operations during the forward and backward passes (see the limits at the top of this page).

### `shard_weights`

Shards model weights across data-parallel processes.

- **Default**: `false`

When enabled:

- Model weights are partitioned across GPUs.
- Each GPU stores only a fraction of the weights.
- All-gather operations rebuild full weights when needed.
- CPU offloading becomes more effective.
- Per-GPU memory use drops.

Example:

```yaml
shard_weights: true
```

### `shard_gradients`

Shards gradients across data-parallel processes.

- **Default**: `false`

When enabled:

- Gradients are partitioned across GPUs with reduce-scatter operations.
- Each GPU stores and updates only its own shard of the gradients.
- CPU offloading becomes more effective.
- Per-GPU memory use drops.

Example:

```yaml
shard_gradients: true
```

## Advanced Options

For finer control over multi-GPU communication and memory (all listed in the [config reference](/engine/reference/config/#multi-gpu-training-zero-options)):

- `memcpy_all_gather`: use memcpy for all-gather operations (threads backend only)
- `memcpy_send_recv`: use memcpy for send/receive operations (threads backend only)
- `use_all_to_all_reduce`: use an all-to-all-based reduce algorithm, which may be faster

---

## See also

- [Dispatch Pipeline Parallelism](/engine/guides/dispatch-pp/): for models whose base weights don't fit on one GPU (PCIe-only boxes)
- [Offloading](/engine/guides/offloading/): use CPU RAM to fit more on each GPU
- [Multi-node training](/engine/guides/multi-node/): scale past one machine
- [Config reference](/engine/reference/config/)
- [Back to docs index](/engine/)
