# Offloading in Surogate

Source: https://docs.surogate.ai/engine/guides/offloading/

Offloading lets you fit a larger model on a smaller GPU. Surogate moves model components that are accessed less often to CPU or NVMe storage, which is slower but much larger than GPU memory. It works for both training and inference.

These are the offloading options. The [config reference](/engine/reference/config/#offloading-options-legacy) lists them too, and for most setups recommends [CPU-RAM centric training](/engine/reference/config/#cpu-ram-centric-training) as the simpler replacement for the legacy ones.

| Parameter             | Description                                                                                          | Default |
| --------------------- | ---------------------------------------------------------------------------------------------------- | ------- |
| **offload_residual**  | Offloads residual activations to CPU to reduce GPU memory usage during training.                     | False   |
| **offload_optimizer** | Offloads optimizer states (e.g., momentum, variance) to CPU to save GPU memory during training.      | False   |
| **offload_master**    | Offloads master weights to CPU to save GPU memory during optimizer updates.                          | False   |
| **offload_grads**     | Offloads gradients to CPU to reduce GPU memory usage during backpropagation.                         | False   |
| **offload_quants**    | Offloads quantized weights to CPU to reduce GPU memory usage during forward/backward passes.         | False   |
| **persistent_quants** | Keeps quantized weights in GPU memory between iterations to speed up training at the cost of memory. | False   |

## Offloading Residual Activations

With `offload_residual` on, Surogate copies residual activations from the GPU to pinned CPU memory during the forward pass and prefetches them back during the backward pass. Together with `recompute: true` (see [Recomputation](/engine/reference/config/#recomputation)), this makes activation memory O(1) instead of O(L), where L is the number of layers.

### Buffer Allocation

**With offloading enabled:**

- **GPU buffers:** 2 double-buffered device tensors (shared across all layers via round-robin)
- **CPU buffers:** L pinned host buffers (one per layer to store each layer's residual)

**Without offloading:**

- L device buffers (one per layer, all on GPU)

### Memory Scaling

| Mode            | GPU Memory       | CPU Memory  | Transfers/step |
| --------------- | ---------------- | ----------- | -------------- |
| **Offload ON**  | O(1) - 2 buffers | O(L) pinned | 2L (D2H + H2D) |
| **Offload OFF** | O(L) - L buffers | 0           | 0              |

## Offloading Optimizer States

With `offload_optimizer` on, Surogate keeps the optimizer states (the first moment `m` and second moment `v` for AdamW) in pinned CPU memory instead of on the GPU. For large models this frees a lot of GPU memory.

### Optimizer State Structure

The optimizer keeps these states for each parameter:

- **First moment (m):** Exponential moving average of gradients (momentum)
- **Second moment (v):** Exponential moving average of squared gradients (variance)
- **FP8 scales:** Additional scale tensors when using 8-bit optimizer states

### Double-Buffering Mechanism

Surogate double-buffers the states so data transfers overlap with computation:

```
Buffer 0: layer 0, 2, 4, ...  (layer_idx % 2 == 0)
Buffer 1: layer 1, 3, 5, ...  (layer_idx % 2 == 1)
```

Two temporary GPU buffers exist during the optimizer pass. One receives data while the other is used for computation.

### Memory Impact

| Configuration        | GPU Memory             | CPU Memory              |
| -------------------- | ---------------------- | ----------------------- |
| **Offload OFF**      | ~8 bytes/param (m + v) | 0                       |
| **Offload ON**       | 2 temporary buffers    | ~8 bytes/param (pinned) |
| **Offload ON + FP8** | 2 temporary buffers    | ~2 bytes/param + scales |

### Performance Considerations

Offloading makes the optimizer step much slower, because the step is memory-bound and now has to go over PCIe. With enough gradient accumulation steps, though, its share of the total time becomes negligible. With `gradient_accumulation_steps=4` (a [training loop setting](/engine/reference/config/#training-loop-settings)), for example, the optimizer runs once per 4 forward/backward passes.

## Offloading Master Weights

With `offload_master` on, Surogate keeps the master copy of the model weights in pinned CPU memory instead of on the GPU. Master weights (see [Precision & recipes](/engine/guides/precision-and-recipes/#master-weights-dtype)) are the full-precision (typically FP32) copies the optimizer updates. The forward and backward passes use lower-precision work weights (BF16/FP8/FP4).

### What are Master Weights?

Mixed-precision training keeps two copies of the weights:

- **Master weights** (`master_dtype`): Full-precision (FP32 or BF16) weights updated by the optimizer
- **Work weights** (`matmul_dtype`): Lower-precision weights (BF16, FP8, FP4) used for forward/backward passes

The optimizer updates the master weights, and Surogate converts them to work weights for the next iteration.

### Double-Buffering Mechanism

Master weights are double-buffered in the same way as optimizer states:

```
Layer 0 → Buffer 0
Layer 1 → Buffer 1
Layer 2 → Buffer 0  (reuse)
Layer 3 → Buffer 1  (reuse)
...
```

Two temporary GPU buffers exist during the optimizer pass. While one layer is updated, the next layer's weights are prefetched.

### Memory Impact

| Configuration   | GPU Memory             | CPU Memory                      |
| --------------- | ---------------------- | ------------------------------- |
| **Offload OFF** | L × master_weight_size | 0                               |
| **Offload ON**  | 2 × master_weight_size | L × master_weight_size (pinned) |

### Performance Considerations

Offloading master weights adds two PCIe transfers to the optimizer step:

- H2D transfer before each layer's update
- D2H transfer after each layer's update

It pays off when GPU memory is tight and gradient accumulation spreads the optimizer cost over many passes.

### QLoRA Mode

:::note
`offload_master` has no effect with [QLoRA](/engine/guides/qlora/). In QLoRA the base model weights are frozen and stored quantized. Only the LoRA adapter weights are trainable, and they are too small for offloading to help.
:::

## Offloading Gradients (Multi-GPU only)

With `offload_grads` on, Surogate keeps the persistent gradient shards in pinned CPU memory instead of on the GPU. This saves GPU memory, and gradient accumulation still works correctly.

:::note[Important]
`offload_grads` requires `shard_gradients=true` (ZeRO-2, see [Multi-GPU options](/engine/reference/config/#multi-gpu-training-zero-options)). It is not supported for unsharded gradients.
:::

### How Gradient Sharding Works (ZeRO-2)

With gradient sharding enabled:

- Each GPU computes full gradients during the backward pass
- Gradients are reduce-scattered across GPUs (each rank receives its local shard of the sum)
- Each rank stores only its own shard persistently
- During the optimizer step, each rank updates only its shard of the weights

### Buffer Architecture

**GPU buffers (always on device):**

- 2 double-buffered full gradient tensors for backward computation
- Used round-robin: layer L uses buffer (L % 2)

**Persistent shards (HOST or GPU depending on `offload_grads`):**

- L sharded gradient tensors (one per layer, only local shard)
- If `offload_grads=true`: stored in pinned host memory
- If `offload_grads=false`: stored on GPU

### Memory Impact

| Configuration   | GPU Memory                | CPU Memory        |
| --------------- | ------------------------- | ----------------- |
| **Offload OFF** | 2 full buffers + L shards | 0                 |
| **Offload ON**  | 2 full buffers            | L shards (pinned) |

### Performance Considerations

- GPU only holds double-buffered full gradients during backward
- Persistent shards on host memory are accessed via CUDA's host memory mapping
- Reduce-scatter communication overlaps backward computation via double-buffering
- Trade-off: reduced GPU memory vs. PCIe bandwidth for optimizer access
- On a single GPU, there's no sharding benefit

## Quantized Weights: persistent_quants and offload_quants (Multi-GPU only)

These two options control where quantized weights are stored in distributed training.

**Important constraints:**

- `persistent_quants` requires `shard_weights=true` (ZeRO-3)
- `offload_quants` requires `persistent_quants=true`

### What are Quantized Weights?

In weight-sharded (ZeRO-3) training, weights have to be gathered across GPUs before each forward/backward pass. Quantized weights are lower-precision copies (FP8, FP4, or INT8) of the master weights. They:

- Reduce all-gather communication bandwidth
- Reduce GPU memory for the gathered full weights
- Are re-quantized after each optimizer step (when master weights change)

### persistent_quants

With `persistent_quants` on:

- Quantized weights are computed once and stored persistently (one copy per layer)
- No re-quantizing on every forward pass, which saves compute
- After an optimizer update, version tracking marks the quantized weights as stale
- Stale weights are re-quantized on the next `gather_block()` call

Without it, weights are quantized on the fly during each gather.

### offload_quants

With `offload_quants` on (it requires `persistent_quants`):

- Persistent quantized weights live in pinned host memory instead of on the GPU
- Double-buffered GPU staging buffers handle H2D transfers
- Quantized weights are streamed to GPU only when needed for gather/all-gather

### Memory Impact

| Configuration                          | GPU Memory                      | CPU Memory                         |
| -------------------------------------- | ------------------------------- | ---------------------------------- |
| **Neither**                            | Quantize on-the-fly (temporary) | 0                                  |
| **persistent_quants only**             | L × quantized_weight_size       | 0                                  |
| **persistent_quants + offload_quants** | 2 staging buffers               | L × quantized_weight_size (pinned) |

### Performance Considerations

- `persistent_quants` trades memory for compute (avoids repeated quantization)
- `offload_quants` moves quantized weights to CPU, reducing GPU memory
- In PCIe multi-GPU setups, H2D transfer may overlap with all-gather communication
- Combined with `--memcpy-all-gather` (see [Multi-GPU options](/engine/reference/config/#multi-gpu-training-zero-options)), this can speed up training

### QLoRA Mode

:::note
`persistent_quants` and `offload_quants` have no effect when using QLoRA (FP8 or FP4).
:::

---

## Tuning a PCIe-bound step

Any configuration that streams weights (`cpu_training`, `offload_master`) tends to be
limited by the PCIe link before compute. Before you optimize kernels, check which of the two
you are waiting on:

```bash
nsys profile -o prof --trace=cuda -y 50 -d 45 python -m surogate.cli.sft config.yaml
nsys stats --report cuda_gpu_mem_time_sum prof.nsys-rep
```

If `[CUDA memcpy Host-to-Device]` dominates and its achieved bandwidth is close to your
link's ceiling (~53 GB/s measured on PCIe 5.0 x16), the step is transfer-bound. Faster
kernels would only turn busy time into idle time; the step would not get shorter. What helps
is moving fewer bytes or overlapping them better. See
[Tuning knobs](/engine/reference/config/#tuning-knobs-environment-variables) for
`SUROGATE_DISPATCH_PREFETCH_BLOCKS` and `SUROGATE_RESIDENT_LAYERS`.

## See also

- [Memory](/engine/guides/memory/): the other ways to cut GPU memory, in the order to try them
- [Multi-GPU](/engine/guides/multi-gpu/): ZeRO sharding, which `offload_grads` and the quantized-weight options build on
- [Dispatch Pipeline Parallelism](/engine/guides/dispatch-pp/): uses `offload_master` to stream the base weights per stage
- [Config reference](/engine/reference/config/): every option and its default
- [Back to docs index](/engine/)
