# Precision & Recipes

Source: https://docs.surogate.ai/engine/guides/precision-and-recipes/

This guide helps you pick a precision setup (a recipe, plus QLoRA if you want it) and explains how the dtype settings interact.

## How to choose

- Start with BF16 if you want the most stability and portability.
- Use FP8-hybrid if you are on SM89+ (Ada/Hopper/Blackwell) and want higher throughput.
- Use NVFP4 if you are on SM100+ (Blackwell) and want the most compression and speed.
- Add [QLoRA](/engine/guides/qlora/) when you want to freeze the base weights and fine-tune adapters with as little VRAM as possible.

For QLoRA details, see [QLoRA](/engine/guides/qlora/).

---

## Precision Recipes

Surogate ships 3 precision recipes (set with `recipe`, see [Mixed precision & recipe options](/engine/reference/config/#mixed-precision--recipe-options)), one for each of the 3 most common numerical formats in training:

- BF16 (bfloat16) is the default. It gives the best numerical accuracy and uses the most memory.
- FP8-Hybrid (float8) uses 8-bit floating point to balance numerical accuracy against memory use.
- FP4 (nvfp4) uses 4-bit floating point for the most speed on Blackwell GPUs, at the cost of some numerical accuracy.

### BF16

This recipe runs every GEMM in `bfloat16`, with no quantization. Use it when memory and compute are not tight, or for smaller models where lower-precision formats would save little.

Use this recipe when:

- Only bfloat16 is supported on your hardware
- Memory and compute are not constrained
- You need a baseline for comparing quantized training
- You are training a smaller model, where FP8/FP4 would save little

#### Forward/Backward Format

| Pass     | Data Type | Scaling |
| -------- | --------- | ------- |
| Forward  | bfloat16  | None    |
| Backward | bfloat16  | None    |

#### Example

```yaml
recipe: bf16
```

### FP8-Hybrid

This recipe uses FP8 in E4M3 format for the forward pass and E5M2 format for the backward pass, with delayed scaling for stability.

- E4M3 (max=448) holds forward-pass activations and weights. It has more precision.
- E5M2 (max=57344) holds backward-pass gradients. It has a larger dynamic range.

Delayed scaling computes scale factors from the previous iteration's abs-max values, which trains more stably than just-in-time scaling. The recipe keeps a window of amax history and takes the maximum value in it to compute the scale factors.

Accuracy is usually close to bfloat16, and you save a lot of memory and time on hardware with FP8 tensor cores (SM89+: Ada Lovelace, Hopper, Blackwell).

Use this recipe when:

- Your GPU supports FP8 tensor cores (SM89+: Ada Lovelace, Hopper, Blackwell)
- You accept a small drop in numerical accuracy for large memory and speed gains
- You are training a large model

#### Forward/Backward Format

| Pass     | Data Type | Max Value | Scaling            |
| -------- | --------- | --------- | ------------------ |
| Forward  | FP8 E4M3  | 448       | Per-tensor delayed |
| Backward | FP8 E5M2  | 57344     | Per-tensor delayed |

#### Parameters

| Parameter                 | Default | Description                                                    |
| ------------------------- | ------- | -------------------------------------------------------------- |
| `fp8_amax_history`        | 1024    | Length of amax history window for delayed scaling              |
| `fp8_weight_cache`        | auto    | Cache FP8 copies of frozen weights (LoRA base) so they are quantized once per run, not at every matmul; `auto` when they fit in free memory, `on` / `off` to force |
| `skip_quant_first_layers` | 0       | Number of first layers to skip quantization (keep in bfloat16) |
| `skip_quant_last_layers`  | 0       | Number of last layers to skip quantization (keep in bfloat16)  |

#### Stability Tips

The layer-skip options are listed under [Layer quantization skip options](/engine/reference/config/#layer-quantization-skip-options).

- Use `skip_quant_first_layers: 1` to keep the embedding layer in BF16
- Use `skip_quant_last_layers: 2` if training is unstable (keeps the lm_head layers in BF16)

#### Example

```yaml
recipe: fp8-hybrid
skip_quant_first_layers: 1
skip_quant_last_layers: 2
```

### FP4 (NVFP4)

This recipe uses NVIDIA's NVFP4 format for both the forward and backward passes, with two-level block scaling for stability: an FP8 E4M3 scale per 16 values plus a global FP32 amax. Weights get 2D block quantization and gradients get stochastic rounding. Optional Random Hadamard Transforms (RHT) spread outliers out before quantization.

It also uses the Four Over Six (4/6) technique, on by default. This change to the NVFP4 quantization algorithm tries two scale factors (max=4.0 and max=6.0) for each block of values and keeps the one with the lower quantization error.

FP4 E2M1 representable values: ±{0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0}

Use this recipe when:

- You are training on Blackwell GPUs with FP4 support (SM100+)

#### Forward/Backward Format

| Tensor      | Data Type | Scale Format    | Block Size |
| ----------- | --------- | --------------- | ---------- |
| Activations | FP4 E2M1  | FP8 E4M3 + FP32 | 16         |
| Weights     | FP4 E2M1  | FP8 E4M3 + FP32 | 16x16 (2D) |
| Gradients   | FP4 E2M1  | FP8 E4M3 + FP32 | 16         |

#### Parameters

| Parameter                    | Default | Description                                                       |
| ---------------------------- | ------- | ----------------------------------------------------------------- |
| `fp4_backend`                | cutlass | Matmul backend: `cutlass` (default) or `cudnn`                    |
| `no_fp4_stochastic_rounding` | false   | Disable stochastic rounding for gradients                         |
| `skip_quant_first_layers`    | 0       | Skip quantization for first N layers (keep in BF16 for stability) |
| `skip_quant_last_layers`     | 0       | Skip quantization for last N layers (keep in BF16 for stability)  |

#### Backend Selection

- cutlass (default) uses CUTLASS with the Sm1xxBlkScaledConfig interleaved scale layout. It can fuse alpha into the epilogue to write BF16 output directly.
- cudnn uses cuDNN with the F8_128x4 scale swizzling layout.

Both backends implement the same quantization strategy (`fp4_backend` in [FP4/NVFP4 recipe options](/engine/reference/config/#fp4nvfp4-recipe-options)). Benchmark your workload and pick the faster one.

#### Weight Caching (SM100+)

On Blackwell GPUs (SM100+), FP4 weight caching is on by default, so weights are not re-quantized on every forward pass.

How it works:

1. Weights are pre-quantized to FP4 in a CUTLASS-optimized layout when the model is initialized
2. The cached FP4 weights (packed data + FP8 block scales + global amax) are reused across forward passes
3. A separate transposed weight cache serves the backward pass (dgrad)

Requirements:

- Blackwell GPU (SM100+)
- ZeRO-3/FSDP weight streaming disabled (weights must be static on device)
- Best suited for [LoRA/QLoRA](/engine/guides/qlora/) fine-tuning where base weights are frozen

#### Stability Tips

- Use `skip_quant_first_layers: 1` to keep the embedding layer in BF16
- Use `skip_quant_last_layers: 4` if training is unstable (keeps the lm_head layers in BF16)
- Keep Random Hadamard Transforms and stochastic rounding on (they are on by default)

#### Example

```yaml
recipe: nvfp4
skip_quant_first_layers: 1
skip_quant_last_layers: 4
```

---

## Mixed-Precision Training

Mixed-precision training combines several numerical formats to save memory and time without losing model accuracy.

These parameters set the precision of each part of training (all of them are in the [config reference](/engine/reference/config/#mixed-precision--recipe-options)):

| Parameter          | Options          | Description                                                                                                                                                         |
| ------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **matmul_dtype**   | fp32, bf16, e4m3 | Data type for matrix multiplications. Defaults to model_dtype. e5m2/fp16/e2m1 not supported for forward pass. FP8 requires SM89+ (Ada/Hopper)                       |
| **gradient_dtype** | fp32, bf16, e5m2 | Data type for activation gradients and backward matmuls. Defaults to matmul_dtype. fp16/e4m3/e2m1 not supported. fp8-hybrid recipe forces e5m2                      |
| **master_dtype**   | fp32, bf16       | Master weight dtype for optimizer updates. Defaults to model_dtype. Only fp32 and bf16 are supported                                                                |
| **model_dtype**    | fp32, bf16       | Data type for non-matmul weights (RMSNorm, embeddings) and activations. Defaults to bf16. Other dtype params fall back to this. Only fp32/bf16 supported by kernels |
| **lora_dtype**     | fp32, bf16       | LoRA adapter master weights dtype for optimizer/export. Defaults to fp32. Work weights converted to model_dtype for compute. Only fp32↔bf16 conversion supported    |

### Matmul Dtype and Gradient Dtype

**Note on recipe behavior:** `matmul_dtype` and `gradient_dtype` only take effect with the default `bf16` recipe. The `fp8-hybrid` and `nvfp4` recipes override them:

| Recipe       | Forward matmul | Backward matmul |
| ------------ | -------------- | --------------- |
| `bf16`       | matmul_dtype   | gradient_dtype  |
| `fp8-hybrid` | e4m3 (forced)  | e5m2 (forced)   |
| `nvfp4`      | e2m1 (forced)  | e2m1 (forced)   |

### Supported Matmul Dispatches

Matrix multiplications support these dtype combinations:

| A (input/weight) | B (input/weight) | C (output) | Use Case                                        |
| ---------------- | ---------------- | ---------- | ----------------------------------------------- |
| fp32             | fp32             | fp32       | Full precision training                         |
| bf16             | bf16             | fp32       | Mixed precision (BF16 compute, FP32 accumulate) |
| bf16             | bf16             | bf16       | Pure BF16 training                              |
| e4m3             | e4m3             | fp32       | FP8 forward pass                                |
| e4m3             | e4m3             | bf16       | FP8 forward pass (BF16 output)                  |
| e4m3             | e5m2             | bf16       | FP8 backward pass (weight × gradient)           |

### Master Weights Dtype

`master_dtype` sets the precision of the master weights, the authoritative copy of the model weights. They are used for:

1. Optimizer updates
2. Checkpointing
3. Weight synchronization

Work weights are a separate copy used for the forward and backward passes.

When `master_dtype` differs from `model_dtype` or `matmul_dtype`, the two copies get separate storage:

- The optimizer updates the master weights
- Work weights are converted from the master weights before each forward pass

### Model Dtype

`model_dtype` is the base dtype. It sets the precision of non-matmul parameters and of activations.

### LoRA Dtype

`lora_dtype` sets the precision of the LoRA adapter master weights and of the
adapter's gradients. The forward and backward use work copies of the masters in `model_dtype` (BF16 by
default, rounded to nearest even), so compute precision is the same either way. What `lora_dtype`
decides is where updates and gradient sums are kept:

- **`fp32` (default).** The optimizer updates FP32 masters, so an update smaller than half a BF16 ulp
  of a weight still accumulates. Gradients are summed in FP32 over all of a step's microbatches,
  chunks and dispatch-PP calls. This includes MoE expert LoRA: the grouped expert weight-gradient
  GEMMs take BF16 operands and accumulate and store in FP32.
- **`bf16`.** Half the adapter memory, but gradients are rounded to BF16 after each microbatch or
  chunk is added. Over many of them the sum drifts, most when contributions cancel, as GRPO advantages
  of mixed sign do. On a 1.04M-token GRPO step of Qwen3.5-35B-A3B (expert LoRA r16, 32 chunks per
  row), the BF16-summed gradient was 41 % off the FP32 one (cosine 0.93). Small updates to large
  weights are also rounded away, so at RL learning rates the A matrices barely move.

Exported adapters keep the master dtype. [GRPO](/engine/guides/rl-training/) weight broadcasts round FP32 masters to BF16
(`broadcast_dtype: bf16`, the default; see [GRPO settings](/engine/reference/config/#grpo-rl-settings)) for serving engines that load BF16 LoRA, while checkpoints keep
FP32 for resuming.

---

## See also

- [QLoRA](/engine/guides/qlora/): freeze a quantized base model and train adapters on top, with any recipe above
- [Offloading](/engine/guides/offloading/): move master weights and optimizer states off the GPU when precision alone doesn't save enough memory
- [Config reference](/engine/reference/config/): every dtype and recipe option with its default
- [Back to docs index](/engine/)
