# RL Training (GRPO)

Source: https://docs.surogate.ai/engine/guides/rl-training/

You can fine-tune a model with reinforcement learning in Surogate using [GRPO](/engine/appendix/glossary/) (Group Relative Policy Optimization). The pipeline ties together three parts: Surogate's own inference server, a GRPO orchestrator, and the Surogate trainer.

What you get:

- Surogate's near-SOL training throughput (LoRA, QLoRA, FP8)
- An async RL pipeline (rollouts, reward computation, sample packing)
- Surogate's serving engine for rollouts, which hot-loads the adapter between steps
- Two single-command runners: split-GPU (`grpo`) and co-locate (`grpo-colocate`)
- Training and evaluation with [Environments](/engine/guides/rl-environments/)

## Architecture

GRPO training runs in one of three deployment modes:

| Mode | Command | When to use |
| --- | --- | --- |
| **Split-GPU** | `surogate grpo` | Run serving and training on separate GPU sets |
| **Co-locate** | `surogate grpo-colocate` | Generate rollouts and train on one GPU with shared base weights |
| **Multi-process** | `surogate grpo-infer` + `grpo-orch` + `grpo-train` | Multi-node, or when each component must run in its own process |

### Split-GPU mode

The inference server runs in a spawned subprocess with its own `CUDA_VISIBLE_DEVICES`, and the trainer runs in the parent process on the remaining GPUs. Weight broadcasts go through the filesystem (there is no shared GPU memory):

```
surogate grpo --train train.yaml --infer infer.yaml --orch orch.yaml \
    --infer-gpus 0,1,2,3 --trainer-gpus 4,5,6,7
```

```
┌───────────────────────────────────────────────────────────┐
│  surogate grpo (split mode)                               │
│                                                           │
│  Parent process (CUDA_VISIBLE_DEVICES=<trainer ids>)      │
│   ├─ Trainer thread                                       │
│   │   └─ Loads its own copy of base weights from disk     │
│   └─ Orchestrator (main async event loop)                 │
│                                                           │
│  Spawned server subprocess (CUDA_VISIBLE_DEVICES=<infer>) │
│   └─ surogate serve /v1/chat/completions                  │
│                                                           │
│  Communication:                                           │
│   - Rollouts:  Orchestrator → server via HTTP             │
│   - Batches:   Orchestrator → Trainer via filesystem/zmq  │
│   - Weights:   Trainer → server via filesystem broadcast  │
└───────────────────────────────────────────────────────────┘
```

The trainer GPU count comes from the CLI: `--trainer-gpus 4,5,6,7` sets `train.gpus = 4`, and for MoE models it sets `ep_size` to the same value. The YAML `gpus` field is ignored in this mode. The inference GPU count must equal `infer.dp * infer.tp`.

### Co-locate mode

With co-locate mode you can run GRPO on a single GPU. For supported BF16 training models (all except Nemotron), it loads the base weights once
and shares them between serving and LoRA training. It generates a batch of
rollouts, pauses generation for the training update, then carries on with the
updated adapter. Adapter updates stay in GPU memory.

```bash
CUDA_VISIBLE_DEVICES=0 surogate grpo-colocate \
    --train train.yaml --infer infer.yaml --orch orch.yaml
```

Use `gpus: 1`, `recipe: bf16`, and
`lora: true` in `train.yaml`. `max_steps` must match in the training and orchestrator configs.
Start with a fresh output directory. See [Single-GPU GRPO](/engine/guides/rl-colocate/) for
the full configuration and current limitations.

### Multi-process mode

This is the original three-process architecture. Use it for multi-node setups, or whenever each component must live in its own process:

```
┌─────────────┐    rollouts    ┌──────────────┐    batches    ┌──────────────────┐
│   Server    │ ─────────────> │ Orchestrator │ ────────────> │     Trainer      │
└─────────────┘   new weights  └──────────────┘               └──────────────────┘
       ^                                                             │
       └─────────────── weight broadcast (filesystem) ───────────────┘
```

1. The inference server (`surogate grpo-infer`) generates completions with log-probabilities.
2. The orchestrator (`surogate grpo-orch`) collects rollouts, computes rewards and advantages, and packs samples into training batches.
3. The Surogate trainer (`surogate grpo-train`) runs the policy gradient update and broadcasts the updated weights back to the server.

The three processes communicate through a shared filesystem directory (`output_dir`). The [CLI reference](/engine/reference/cli/#grpo-infer) lists each command's arguments.

## Quick Start (split-GPU mode)

This walkthrough uses the reverse-text example. Split-GPU mode needs at least two GPUs, one for the server and one for the trainer. On a single GPU, see [Co-locate mode](#quick-start-co-locate-mode) below.

### 1. Create the three config files

**`train.yaml`**:

```yaml
model: "Qwen/Qwen3-0.6B"
output_dir: ./outputs
gpus: 1  # ignored in split mode (auto-derived from --trainer-gpus)

per_device_train_batch_size: 1
sequence_len: 2048
max_steps: 40
logging_steps: 1

learning_rate: 2e-4
lr_scheduler_type: constant
max_grad_norm: 1.0
weight_decay: 0.01

recipe: fp8-hybrid

lora: true
lora_rank: 16
lora_alpha: 32
lora_target_modules:
  - q_proj
  - k_proj
  - v_proj
  - o_proj
  - gate_proj
  - up_proj
  - down_proj

loss:
  kl_tau: 0.0
  adv_tau: 1.0
  ipo_mask_low: 0.2
  ipo_mask_high: 0.2
```

**`infer.yaml`**:

```yaml
model: "Qwen/Qwen3-0.6B"
enable_lora: true
max_lora_rank: 32
```

**`orch.yaml`**:

```yaml
model:
  name: "Qwen/Qwen3-0.6B"
  lora_adapter: "default"

env:
  - id: reverse-text

batch_size: 128
rollouts_per_example: 16
seq_len: 2048
max_steps: 40

sampling:
  max_tokens: 128
```

### 2. Run with a single command

```bash
surogate grpo --train train.yaml --infer infer.yaml --orch orch.yaml \
    --infer-gpus 0 --trainer-gpus 1
```

The command:

1. Spawns the inference server as a subprocess with `CUDA_VISIBLE_DEVICES=0`.
2. Polls `/health` until the server is ready.
3. Starts the Surogate trainer in a background thread, restricted to GPU 1.
4. Runs the orchestrator, which coordinates rollouts and training steps.
5. Shuts down the server and the trainer cleanly when `max_steps` is reached.

`--trainer-gpus` also sets the trainer's GPU count, so the YAML `gpus` field is optional. For MoE models, `ep_size` is set to the same count. See [`surogate grpo`](/engine/reference/cli/#grpo) for every flag.

## Quick Start (co-locate mode)

On a single GPU, run serving and training together with `surogate grpo-colocate`:

```bash
surogate grpo-colocate --train train.yaml --infer infer.yaml --orch orch.yaml
```

[Single-GPU GRPO](/engine/guides/rl-colocate/) covers the configuration and its current limits.

## Quick Start (multi-process mode)

For multi-node setups, or whenever you want each component in its own process, run the three commands separately:

```bash
# Terminal 1: Start the inference server (GPU 0)
CUDA_VISIBLE_DEVICES=0 surogate grpo-infer infer.yaml

# Terminal 2: Start orchestrator (CPU only)
surogate grpo-orch orch.yaml

# Terminal 3: Start Surogate trainer (GPU 1)
CUDA_VISIBLE_DEVICES=1 surogate grpo-train train.yaml
```

At startup the trainer waits until the orchestrator delivers the first batch, and the orchestrator waits until inference has generated enough rollouts. Once all three are running, the pipeline runs on its own.

## How the Training Loop Works

Each training step does the following:

1. **Weight broadcast** (after step 0): saves the LoRA adapter to `{output_dir}/broadcasts/step_{N}/` with a `STABLE` marker file. The orchestrator watches for the marker and asks the server to hot-load the adapter. If QeRL is enabled, noisy norm weights are saved next to the adapter.

2. **Pack and receive the batch**: the packer (on master) turns the orchestrator's `TrainingBatch` into packed `MicroBatch` sequences, which the data loader delivers as numpy arrays.

3. **For each micro-batch** (gradient accumulation):
    - `compute_logprobs()` computes log-probabilities under the current policy
    - `compute_grpo_per_token_grads()` computes per-token gradient multipliers using the GRPO loss formula
    - `step_with_custom_loss()` performs the forward + backward pass with GRPO gradient seeding

4. **Optimizer step**: updates the LoRA adapter weights with the configured optimizer and learning rate schedule.

### GRPO Loss Formula

The GRPO loss for each token is:

```
loss = -(coeff * trainer_logprobs)[keep_mask].sum()

where:
  log_ratio = trainer_logprobs - inference_logprobs
  importance_ratio = exp(log_ratio)
  coeff = importance_ratio * (adv_tau * advantages - kl_tau * log_ratio)
```

The coefficient is treated as a constant (detached) during backpropagation, so the per-token gradient is:

```
grad[t] = -coeff[t] * keep_mask[t] / loss_scale
```

A token is masked (left out) when the trainer's probability for it differs from the rollout engine's by more than `ipo_mask_high` (above) or `ipo_mask_low` (below). The ratio in `coeff` is capped at `ratio_clip`.

## Asynchronous Off-Policy Training

Surogate trains asynchronously and off-policy: inference generates rollouts from a policy that may lag behind the trainer by up to `max_async_level` steps (call this $k$). With $k=1$ and equal trainer and inference step times, neither side sits idle. The default is `max_async_level: 1`. Raise it to `2` when weight broadcasts take longer (over a network, for example).

### Step Semantics

Surogate tags every artifact with a global step counter $n = 1, 2, 3, \ldots$:

- Trainer: produces policy $\pi_n$ with weights $\theta_n$ from rollouts $(x_n, y_n)$.
- Inference: produces rollouts $(x_n, y_n)$ from policy $\pi_{\max(0,\, n-k)}$.

The off-policy gap is at most $k$ steps. The orchestrator discards rollouts whose gap exceeds `max_off_policy_steps`.

### Resuming a run

The trainer resumes from the latest checkpoint in `checkpoint_dir` on its own
(`resume_from_checkpoint` defaults to `true`; see [Checkpoint resume](/engine/reference/config/#checkpoint-resume)). A checkpoint at step $S$ means
"trained through batch $S$", so the resumed run starts at $S + 1$ and logs:

```
Resuming from checkpoint step 5 (next batch: 6)
```

The trainer owns the resume point on purpose. The orchestrator's progress
counter runs *ahead* by up to $k$ steps, so starting from it would skip the
unconsumed batches in between and publish broadcasts under step numbers the
orchestrator has already read. The resumed trainer re-emits the
checkpoint's weights under step $S$ instead, which unblocks an orchestrator already
waiting on that broadcast.

### Loss Objective

The loss is a token-level variant of the [AIPO objective](https://arxiv.org/abs/2505.24034) (introduced in Llama-RL), without the entropy and KL terms. For $N$ prompts, each with a group of $G$ rollouts:

$$
\mathcal{J}(\theta)
= \frac{1}{\sum_{j=1}^N \sum_{i=1}^G |y_i^{(j)}|}
\sum_{j=1}^N
\sum_{i=1}^G
\sum_{t=1}^{|y_i^{(j)}|}
\min\!\left(
\frac{\pi_\theta(y^{(j)}_{i,t}\mid x_j, y^{(j)}_{i,<t})}{\mu(y^{(j)}_{i,t}\mid x_j, y^{(j)}_{i,<t})},\;
\delta
\right)\hat{A}^{(j)}_{i,t}
$$

Here $\mu$ is the rollout policy, $\pi_\theta$ is the current trainer policy, $\hat{A}_{i,t}$ is the token-level advantage, and $\delta$ is the importance-sampling cap (`ratio_clip`, e² by default). The probability-difference mask (`ipo_mask_low`, `ipo_mask_high`) leaves out tokens the off-policy gap has moved too far.

## Split-GPU Mode Details

### GPU assignment

The `--infer-gpus` and `--trainer-gpus` CLI flags take driver-level GPU indices (the same values you would put in `CUDA_VISIBLE_DEVICES`). The two sets must not overlap.

- The number of `--infer-gpus N0,N1,...` must equal `infer.dp * infer.tp`, and the server uses every one. `dp > 1` loads a whole replica on each GPU and spreads rollouts over them; `tp > 1` splits one replica's layers across the GPUs. The engine's replicas are one GPU each, so `dp` and `tp` cannot both be above 1.
- The number of `--trainer-gpus M0,M1,...` overrides `train.gpus`. When the flag is present, the YAML field is ignored.
- For MoE models, `ep_size` is set to the trainer GPU count. The runner checks again that `num_experts` is divisible by `ep_size`, and if it isn't, the run stops at once with a clear error.

The CLI applies `CUDA_VISIBLE_DEVICES=<trainer ids>` to the parent process *before* any import touches CUDA, and passes `CUDA_VISIBLE_DEVICES=<infer ids>` to the spawned server in its own environment. The CUDA driver reads the two values independently, so the parent's mask does not carry over to the child.

### CPU offloading

For split-GPU runs and `surogate grpo-infer`, set up serving offload in
`infer.yaml`. For example, you can let the server choose how many MoE layers' experts
to keep in CPU RAM so the model fits:

```yaml
# Add to infer.yaml for a MoE model.
host_moe_layers: auto
```

| Setting | Accepted values | Effect |
| --- | --- | --- |
| `gpu_layers` | Nonnegative integer or `all` | Keep the first N decoder layers on GPU and offload the rest. `0` offloads all decoder layers; `all` keeps them resident. |
| `host_moe_layers` | Nonnegative integer, `auto`, or `all` | Keep the routed experts of this many MoE layers in CPU RAM. `auto` chooses enough layers to fit; `all` offloads every MoE layer's routed experts. |
| `expert_slots` | Nonnegative integer | Set the GPU expert-cache size for offloaded MoE models. |
| `host_expert_bank` | `auto`, `w8`, or `q4` | Choose the CPU expert storage format. |
| `cpu_moe_share` | Number from `0` to `1`, or `auto` | Choose the fraction of decode expert cache misses computed on CPU. `auto` tunes the split at startup. |
| `cpu_moe_prefill_share` | Number from `0` to `1` | Choose the CPU share of expert computation during prompt processing. |
| `cpu_moe_min_tokens` | Nonnegative integer | Set the minimum token count for CPU expert computation. `0` uses the model's default. |

Leave a setting out, or set it to `null`, to keep the server default. Offloading trades GPU
memory for CPU RAM and can lower throughput. Changing the expert storage format
can also change rollout numerics, so watch `mismatch_kl` while you tune it.

Training offload is configured separately, in `train.yaml`. For LoRA training,
`cpu_training: true` streams the base weights from CPU RAM while adapter training
stays on GPU. See [CPU offloading](/engine/guides/offloading/) for training settings.

These serving settings are not available in `grpo-colocate`, which needs the
base weights resident on the GPU. Use split-GPU mode when serving or training needs CPU
weight offload.

### Weight broadcast

In split mode, weight broadcasts always use the filesystem backend, whatever the YAML says. Each broadcast writes the LoRA adapter (~10 MB) to `{output_dir}/broadcasts/step_N/`, and the orchestrator watches for the `STABLE` marker and asks the server to hot-load it. The adapter is written in BF16 (`broadcast_dtype: bf16`, the default): FP32 masters are rounded to nearest even, and checkpoints keep FP32.

### Long sequences: chunked GRPO

Agentic rollouts run far longer than a dense activation budget allows. Set
`sequence_chunks: N` in `train.yaml` to send the native GRPO step down the
chunked path ([Chunked-sequence training](/engine/reference/config/#chunked-sequence-training-long-sequences)). Chunks are forwarded left to right to fill the attention KV
caches, then walked in reverse for the GRPO dloss and backward, accumulating
dK/dV across chunks. Gradients are exact, and memory stays at the footprint of a
single chunk. Tail chunks that are all padding are detected from the per-sample end offsets
and skipped.

The update is normalized by the step's total loss tokens, and `loss`, `kl` and
`masked` are per-sample means over all of a sample's loss tokens, so none of
them depends on where the chunk boundaries fall. A prompt longer than one chunk
needs no special handling. That is the usual shape of an agentic rollout, where the
first chunks of every sample hold no loss token at all.

Pair it with `single_sample_bins: true`. Attention in chunked training does not isolate
packed documents, so a row holding several samples would let them
attend to each other.

```yaml
# train.yaml
sequence_len: 6144
sequence_chunks: 4        # 1536-token chunks
single_sample_bins: true
per_device_train_batch_size: 1
```

### Adapter precision

Keep `lora_dtype: fp32`, the GRPO default, for MoE expert LoRA too. A GRPO step sums the adapter's
gradients over many micro-batches or chunks whose advantages partly cancel. In BF16 that sum is rounded
after each one, and on a 1.04M-token step the result was 41 % off the FP32 sum. BF16 masters also round
away the small updates that RL learning rates produce. See
[Precision: LoRA dtype](/engine/guides/precision-and-recipes/#lora-dtype); for runs under `parallelism: dispatch_pp`,
see [Dispatch-PP: GRPO steps](/engine/guides/dispatch-pp/#grpo-steps).

### Bounding the importance ratio

`loss.ratio_clip` (default `7.389056`, i.e. e²) caps the importance ratio. The
IPO mask drops tokens whose probability moved too far. With periodic
merged-weight reloads, though, the sampling policy and the trainer policy can drift
far enough apart that tokens that survive the mask still carry an extreme ratio. `ratio_clip` limits
how much any single token can contribute.

### GSPO: one ratio per sequence

`loss.variant: gspo` is [GSPO](https://arxiv.org/abs/2507.18071) in its GSPO-token form. Each sequence $y_i$ has one
importance ratio, the geometric mean of its tokens' ratios:

$$
s_i(\theta) = \exp\Big(\frac{1}{|y_i|}\sum_{t} \log\frac{\pi_\theta(y_{i,t}\mid x, y_{i,<t})}{\mu(y_{i,t}\mid x, y_{i,<t})}\Big)
$$

The objective takes PPO's minimum of $s_i \hat{A}_{i,t}$ and $\mathrm{clip}(s_i, 1-\epsilon_{low}, 1+\epsilon_{high})
\hat{A}_{i,t}$. Its gradient on token $t$ is therefore $\hat{A}_{i,t}\, s_i / |y_i|$, or zero when the clipped term is
the minimum: $\hat{A} > 0$ with $s_i > 1 + \epsilon_{high}$, or $\hat{A} < 0$ with $s_i < 1 - \epsilon_{low}$. A step
divides by its number of trials (sequences), not by its tokens, so every sequence weighs the same whatever its length.

- **Settings.** `seq_clip_low` and `seq_clip_high` are $\epsilon_{low}$ and $\epsilon_{high}$; the defaults are the
  paper's 3e-4 and 4e-4. GSPO turns off the probability-difference mask and the KL term, and does not use
  `ratio_clip`.
- **The ratio carries the engine mismatch.** $\mu$ is the rollout engine's log-probs, so $s_i$ also holds the gap
  between the engine and the trainer. The mean log-ratio is $-\mathrm{KL}(\mu \Vert \pi_\theta)$, so a k3 mismatch
  of 0.005 per token puts $s_i$ near 0.995, outside the paper's clips. Read `train/seq_log_ratio` and the clip shares
  before choosing the clips. `seq_ratio_old: trainer` takes π_old from the trainer at the current parameters
  instead: the ratio is then 1, nothing is clipped, and the update corrects for neither the lag nor the mismatch.
- **Trials split into several rows.** A trial whose turns do not merge into one sequence becomes several samples.
  Give them the same `TrainingSample.trial_idx` and divide each one's advantage by their count. The step then counts
  that trial once; a sample without `trial_idx` is a trial of its own.
- **Metrics.** `is_masked_low` and `is_masked_high` are the shares of sequences clipped on each side, and
  `train/seq_log_ratio` is the mean of $\log s_i$.
- **Constraint.** `parallelism: dispatch_pp` only: the sequence ratio needs a whole sequence's log-probs before its
  backward, which the native step does not have.

The paper's own procedure recomputes π_old with the training engine and takes several mini-batch updates per rollout
batch. That is these settings together:

```yaml
minibatches: 4            # four updates per rollout batch, each over whole groups (group_idx) or trials
max_policy_lag: 0         # on-policy batches: drop samples sampled by any other policy version
learning_rate: 1.25e-5    # per update
lr_scheduler_type: constant
loss:
  variant: gspo
  seq_ratio_old: step_start   # pi_old = the trainer's log-probs at the weights the step starts from
  seq_clip_low: 3.0e-4
  seq_clip_high: 4.0e-4
  teacher_tau: 0.0
```

- **Groups.** With `TrainingSample.group_idx` each mini-batch holds whole GRPO groups, so its advantages still sum to
  zero per group; the mini-batch size is the batch's groups divided by `minibatches`.
- **Versions.** The producer sends `TrainingSample.completion_versions`, the policy version that sampled each
  completion token; samples sampled by another version, or by several, are dropped and counted
  (`train/offpolicy_dropped_samples`).
- **π_old.** One scoring pass over the step's rows before its first update gives π_old, so mini-batch 1 has
  $s_i = 1$. Later mini-batches see the drift of the updates before them.
- **Metrics.** Per mini-batch: `train/mb<k>/log_s_p05`, `_p50`, `_p95`, the shares of A < 0 and A > 0 sequences
  clipped (`clip_neg`, `clip_pos`), `trials` and `grad_norm`. `train/engine_mismatch_kl` keeps the k3 gap between the
  rollout engine and the trainer's π_old.

#### Precision: the LoRA forward from the fp32 masters

With `lora_dtype: fp32` the optimizer updates FP32 masters, but by default the forward computes the LoRA products from
their BF16 work copies. A work copy changes only where an update crosses a BF16 rounding step, and then by a whole
step, so the policy moves in rounding jumps rather than with the learning rate.

On Qwen3.5-35B-A3B's NVFP4 base at 131k (expert LoRA r16, a real on-policy GSPO batch), the spread of log s_i over a
mini-batch's sequences after one update was about ±0.0012-0.0020 at every lr from 1.25e-6 to 5e-5. That is the size of
rounding the whole adapter once (truncated vs. to nearest: ±0.0012, token k3 0.0025).

`lora_fp32_forward: true` (needs `lora_dtype: fp32`) computes the forward's LoRA products from the masters themselves:
the expert kernel for gate_up and down, and dense LoRA (the shared expert) through the same kernel as a one-expert
group. The backward keeps the BF16 copies, and broadcasts stay BF16. On the same batch:

- **The spread grows with lr.** About ±0.002 after one update at 1.25e-5 and ±0.008 at 5e-5.
- **A floor remains.** After any update, even at lr 1.25e-6, the spread stays near ±0.0012, probably from MoE
  routing flips and the activations' own BF16 rounding. It is above the paper's clips, so several mini-batches per
  rollout batch clip 25-80 % of this model's sequences at any lr. With `minibatches: 1` on on-policy batches the
  ratio is exactly 1 and nothing is clipped.
- **The same nominal lr moves the policy further,** since the BF16 copies used to drop most updates to lora_A.
  Probe: a fresh adapter (B = 0) and fresh Adam, 5 updates on one batch, token k3 / mean |log s| against the start
  on a held batch of the start's samples:

  | lr | after update 1 | 3 | 5 |
  | --- | --- | --- | --- |
  | 5e-5 | 0.0019 / 0.0008 | 0.0080 / 0.0056 | 0.0233 / 0.0210 |
  | 2.5e-5 | 0.0018 / 0.0007 | 0.0026 / 0.0009 | 0.0067 / 0.0043 |
  | 1.25e-5 | 0.0018 / 0.0006 | 0.0019 / 0.0006 | 0.0025 / 0.0009 |

  A run with the BF16 forward at lr warming up to 5e-5 reached a per-step drift from its start of 0.004-0.005 after
  five steps (`teacher_kl`), about the 2.5e-5 row.
- **Cost and agreement.** The step time did not change measurably (+2 %). The engine/trainer k3 at lag 0 against the
  BF16 broadcast was 0.0043, against 0.0044 with the BF16 forward.

### Reading progress from a log file

The orchestrator's rollout progress bar is `tqdm`, which needs a TTY. Under
`nohup` or any redirect it writes nothing readable, so the orchestrator also
writes plain `[progress]` INFO lines with the rate and ETA:

```
[progress] step 11 Generating rollouts (train): 128/256 (50%) | 42.7/min | elapsed 3m00s | eta 3m00s
```

When a step stops completing rollouts, the log says so instead of going quiet:

```
[progress] step 11 Generating rollouts (train): 128/256 — NO completions in the last 60s (inflight 64, scoring 3, elapsed 14m22s)
```

When you see that line, check the inference server. A deep queue, an
unresponsive engine and failing rollouts all look the same on a
frozen progress bar. Failed rollouts in particular are logged one by one,
which makes them easy to scroll past when there are many.

### Lifecycle

The `surogate grpo` process owns the server subprocess: on shutdown it terminates the child, and kills it if necessary. If the parent is `SIGKILL`ed, the server can be left orphaned and holding GPU memory. If that happens, clean up with `nvidia-smi`.

## QLoRA for RL Training

All QLoRA formats work with GRPO. QLoRA helps in RL training because it shrinks the frozen base model's memory footprint, which leaves more room for the sequence buffers and logprob computations:

```yaml
# FP8 QLoRA (SM89+: RTX 40xx, L40, H100)
lora: true
qlora_fp8: true
recipe: bf16

# NF4 QLoRA (any GPU)
lora: true
qlora_bnb: true
recipe: bf16

# FP4 QLoRA (SM100+: Blackwell)
lora: true
qlora_fp4: true
recipe: nvfp4
```

See the [QLoRA guide](/engine/guides/qlora/) for details on each format.

## Multi-GPU RL Training

Multi-GPU training works as it does for SFT ([Multi-GPU training](/engine/guides/multi-gpu/)). Surogate handles data parallelism internally, and the orchestrator sees the trainer as a single process:

```yaml
gpus: 4
zero_level: 1  # Default: shard optimizer states
```

Each micro-batch is replicated on every GPU. The per-token gradients are computed from the first GPU's logprobs, and the result is replicated for the backward pass.

### Fitting a large policy on the inference side

Two `infer.yaml` keys ([Inference server config](/engine/reference/config/#inference-server-config-inferyaml)) decide whether a large model plus LoRA fits, and people
often try them in the wrong order:

- `max_num_seqs` caps the number of concurrent sequences, which sets the size of the
  CUDA-graph and activation buffers. On a 27B model served TP2 with
  `enable_lora: true`, the default runs out of memory at startup, and a small value
  (e.g. `16`) fits.
- `kv_cache_dtype: fp8` halves the KV bytes per token, which raises the
  concurrency a KV-bound server can sustain. It also perturbs sampled
  logprobs, which feed GRPO's importance ratio, so watch `mismatch_kl` for a
  step or two after you turn it on.

```yaml
# infer.yaml
max_num_seqs: 16
kv_cache_dtype: fp8
```

## Tuning Tips

### QeRL Adaptive Quantization Noise

QeRL (Quantization-enhanced RL, [arXiv:2510.11696](https://arxiv.org/abs/2510.11696)) adds controlled Gaussian noise to the inference model's RMSNorm weights while it generates rollouts. The noise makes the inference policy slightly stochastic, which encourages exploration and gives more varied rewards early in training.

#### How it works

1. At each training step, the noise scheduler computes a sigma from a geometric decay schedule.
2. All RMSNorm weights (input_layernorm, post_attention_layernorm, etc.) are read from the base model.
3. Gaussian noise N(0, sigma^2) is added to make noisy copies.
4. The noisy norm weights go to the inference server with a full-model broadcast.
5. The trainer always computes gradients with the clean weights.

Sigma decays geometrically from `sigma_start` to `sigma_end` over `num_stages` intervals. The first interval uses sigma=0 (no noise) to set a baseline.

#### Configuration

Add `noise_scheduler` to `train.yaml`:

```yaml
noise_scheduler:
  enabled: true
  sigma_start: 5e-2    # Initial noise level
  sigma_end: 5e-4      # Final noise level
  num_stages: 10        # Number of decay intervals
```

| Parameter     | Default | Description                                     |
| ------------- | ------- | ----------------------------------------------- |
| `enabled`     | `false` | Enable QeRL noise injection                     |
| `sigma_start` | `5e-2`  | Initial noise standard deviation                |
| `sigma_end`   | `5e-4`  | Final noise standard deviation                  |
| `num_stages`  | `10`    | Number of geometric decay intervals             |

#### When to use QeRL

- Models that converge too quickly to a local optimum
- Tasks with little variety in the reward (many rollouts get the same reward)
- Pre-quantized models (NVFP4, FP8), where quantization already adds noise and QeRL amplifies it in a controlled way

QeRL needs the inference server to load the perturbed norms between steps, and the native engine can't do that yet. Both runners therefore refuse `noise_scheduler.enabled` instead of computing a sigma that nothing would apply.

### On-Policy Distillation

On-policy distillation adds a teacher model that gives dense, token-level feedback alongside the reward signal, or in place of it. The student generates rollouts, and the teacher's log-probabilities pull the student toward stronger behavior while it still learns from rewards.

The loss coefficient for each token becomes:

```
coeff = importance_ratio * (adv_tau * advantages + teacher_tau * (teacher_logprob - trainer_logprob) - kl_tau * log_ratio)
```

The `teacher_tau * (teacher_logprob - trainer_logprob)` term is positive when the teacher gives a token higher probability than the student does, which pulls the student toward the teacher's distribution.

#### Enabling distillation

Set `teacher_tau > 0` in `train.yaml` and configure the teacher in `orch.yaml`. The orchestrator computes teacher log-probabilities and sends them with the advantages in each micro-batch, so the trainer command stays the same.

When the teacher is the base model the adapter trains on (a KL anchor that keeps the policy near where it started), a [dispatch-PP](/engine/guides/dispatch-pp/) trainer can score it itself: set `teacher_from_base: true` in `train.yaml` and leave `teacher_model` out of `orch.yaml`. Each dispatch call then runs one more log-prob pass with the LoRA delta off, on the same kernels as the policy pass, and its log-probs replace the rows' `teacher_logprobs`.

A run without the anchor sets `teacher_tau: 0` and `teacher_from_base: false`, and its producer sends no teacher
log-probs. The trainer refuses `teacher_from_base: true` with `teacher_tau: 0`, a base pass that would only feed the
`teacher_kl` metric. It warns once when rows arrive without teacher log-probs while `teacher_tau > 0` (no anchor on
those rows), or with teacher log-probs while `teacher_tau` is 0.

In **`train.yaml`**, add `teacher_tau` to the loss block:

```yaml
loss:
  adv_tau: 1.0
  teacher_tau: 0.5   # blend: half reward signal, half teacher signal
  kl_tau: 0.0
```

In **`orch.yaml`**, add a `teacher_model` section to the orchestrator:

```yaml
model:
  name: "Qwen/Qwen3-0.6B"
  lora_adapter: "default"

teacher_model:
  model:
    name: "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"

env:
  - id: reverse-text

batch_size: 128
rollouts_per_example: 16
seq_len: 2048
max_steps: 40
```

If the teacher's inference server is already running elsewhere, point to it with a `client` entry instead:

```yaml
teacher_model:
  model:
    name: "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
  client:
    base_url: ["http://teacher-server:8000/v1"]
```

The orchestrator sends each sample's exact token ids to the teacher's `/v1/chat/completions/tokens` route with
`prompt_logprobs: 0`, and reads every position's score by the id of the token there, so the teacher must share the
student's tokenizer. Surogate's server provides that route. vLLM does not, so a vLLM teacher goes behind the small
proxy in [examples/turnopd](/engine/examples/recipes/turnopd/).

#### A teacher per environment

An `env` entry can carry its own `teacher_model`, which replaces the top-level one for that environment's samples.
Once any training environment has a teacher, every environment must have one (its own or the top-level one). A batch
packs the samples of all environments together, and there is no neutral value to stand in for a sample's missing
teacher log-probabilities. Environments whose teachers share base URLs and model share one connection pool.

```yaml
teacher_model:              # for every env without its own
  model:
    name: "Qwen/Qwen3-8B"
  client:
    base_url: ["http://teacher-a:8000/v1"]

env:
  - id: reverse-text
  - id: tool-use
    teacher_model:
      model:
        name: "Qwen/Qwen3-32B"
      client:
        base_url: ["http://teacher-b:8000/v1"]
```

#### Rule self-distillation

With `rule`, the frozen model becomes its own teacher. Serve the student's base model as the teacher, and give it a
short rule that the student never sees. The orchestrator tokenizes the rule with the student tokenizer and splices
it into every sequence it sends to that teacher, at the end of the first system message of a ChatML prompt, or as a
new system message in front when there is none. It then drops the rule's positions from the returned
log-probabilities, so they line up with the student's tokens again. The teacher term pulls the student toward what
the model does when it has read the rule.

```yaml
teacher_model:
  model:
    name: "Qwen/Qwen3-0.6B"   # the student's base model, frozen
  client:
    base_url: ["http://teacher-server:8000/v1"]
  rule: "Before you answer, look up the current state with a tool call."
```

#### Pure distillation (no reward verification)

For agentic tasks where verification is expensive (code execution, tool use, multi-turn), you can skip reward scoring entirely and learn only from the teacher signal:

**`train.yaml`**:

```yaml
loss:
  adv_tau: 0.0       # disable reward signal
  teacher_tau: 1.0   # learn only from teacher
  kl_tau: 0.0
```

**`orch.yaml`**:

```yaml
teacher_model:
  model:
    name: "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"

buffer:
  skip_verification: true  # skip reward scoring

env:
  - id: your-env
```

#### Monitoring

When teacher log-probabilities are present, the trainer logs one more metric:

| Metric       | Description                                                   |
| ------------ | ------------------------------------------------------------- |
| `teacher_kl` | Mean KL divergence from teacher to student (lower = closer to teacher) |

If `teacher_kl` goes down, the student is learning to match the teacher's distribution. For offline distillation from a teacher, see [Distillation](/engine/guides/distillation/).


### RULER (LLM-as-Judge Rewards)

RULER ([Relative Universal LLM-Elicited Rewards](https://art.openpipe.ai/fundamentals/ruler)) replaces the env's hand-written rubric, or adds to it, with an LLM judge that ranks all the rollouts in a group. This works because GRPO normalizes scores within each group. Only the *relative* order matters, so the judge doesn't need to give calibrated absolute scores.

Use it when:

- your task has no verifiable reward function (open-ended generation, agentic tasks)
- writing a rubric by hand would take days, and you'd rather pay for judge tokens
- you want a richer reward signal than the env's pass/fail check
- you need a quick baseline before you spend time on a custom rubric

#### How it works

1. The orchestrator wraps each training env's rubric in a `vf.RubricGroup` that adds a group-level RULER reward function.
2. When all `rollouts_per_example` rollouts of a scenario are done, the orchestrator sends the whole group to the judge in one request.
3. The judge returns one score in `[0, 1]` per rollout, plus a short explanation.
4. The scores become per-rollout rewards, and GRPO computes advantages with group-mean normalization as usual.

Group judging runs at the same time as rollout generation. The scheduler dispatches each completed group as an `asyncio.Task`, so judge latency overlaps the next step's rollouts instead of blocking the pipeline. `ruler.max_concurrent_judges` caps concurrency globally.

RULER needs `rollouts_per_example >= 2`, since a single rollout has nothing to be ranked against. ART's launch report recommends 4–8 rollouts per scenario for stable relative rankings.

#### Configuration

The judge runs as a *separate* OpenAI-compatible inference server. Start it on its own before you launch `surogate grpo`:

**Terminal 1**, the judge server:

```bash
CUDA_VISIBLE_DEVICES=2 surogate grpo-infer judge.yaml
```

Here `judge.yaml` is a plain inference config (`enable_lora: false` and the model you want as judge). Any OpenAI-compatible endpoint works: a local `surogate grpo-infer`, a hosted API, or a LiteLLM proxy.

**Terminal 2**, `surogate grpo` with RULER enabled in `orch.yaml`:

```yaml
verification:
  enabled: true   # required: RULER plugs into the deferred group-scoring path

batch_size: 16
rollouts_per_example: 4   # >= 2 required; 4-8 recommended

ruler:
  enabled: true
  mode: replace                  # 'replace' | 'add' | 'metric'
  judge_model: "Qwen/Qwen3-1.7B"
  judge:
    base_url: ["http://localhost:8001/v1"]
    api_key_var: RULER_JUDGE_API_KEY
    timeout: 90.0
  weight: 1.0
  max_concurrent_judges: 8
  sampling:
    temperature: 0.0
    max_completion_tokens: 1024
  swallow_exceptions: true
  debug: true
```

#### Modes

| Mode      | Behavior                                                                                  |
| --------- | ----------------------------------------------------------------------------------------- |
| `replace` | Drop the env's existing rubric. RULER is the sole reward source.                          |
| `add`     | Sum RULER's score with the env's existing rubric (each weighted). Combines both signals.  |
| `metric`  | Run RULER for observability only — `weight=0`, the env's rubric drives the reward.        |

In `add` and `metric` mode, the env needs a rubric that produces non-zero rewards (otherwise `metric` mode trains on zeros). When the env has no usable rubric, use `replace`.

#### Custom rubric

The built-in rubric is generic (efficiency, goal achievement, partial credit, a hallucination penalty). You can override it per task:

```yaml
ruler:
  enabled: true
  rubric: |
    - Reward concise, well-formatted answers.
    - Penalize tool-call hallucinations and off-topic responses.
    - Award partial credit for incomplete but on-track attempts.
```

The judge also takes context from the env's system prompts, so make sure each env states the agent's goal clearly.

#### Cost tracking

Set per-token rates (USD per 1M tokens) to get a metric for cost in dollars:

```yaml
ruler:
  cost:
    input_per_million: 0.15
    output_per_million: 0.60
```

#### Monitoring

When RULER is enabled, the orchestrator adds these metrics:

| Metric                         | Description                                                                              |
| ------------------------------ | ---------------------------------------------------------------------------------------- |
| `ruler/total_judge_calls`      | Total judge HTTP calls this step (= `batch_size / rollouts_per_example` in steady state) |
| `ruler/total_input_tokens`     | Step total of judge prompt tokens                                                        |
| `ruler/total_output_tokens`    | Step total of judge completion tokens                                                    |
| `ruler/total_judge_latency_ms` | Step total of judge compute time (sum of per-call durations)                             |
| `ruler/total_judge_cost_usd`   | Step total of judge USD cost (zero unless `ruler.cost.*` is set)                         |
| `ruler/score_mean`             | Mean RULER score across the batch                                                        |
| `ruler/score_std`              | Std-dev of RULER scores — collapses to 0 when the judge is undiscriminating              |
| `ruler/judge_failure_rate`     | Fraction of groups where the judge call raised; >0 indicates trouble                     |
| `metrics/ruler_*`              | Per-rollout averages of the same fields                                                  |

Healthy signals during a run:

- `ruler/total_judge_calls` equals `batch_size / rollouts_per_example` exactly (no retries firing).
- `ruler/judge_failure_rate == 0`.
- `ruler/score_std > 0`, ideally > 0.1 (the judge really tells rollouts apart).
- `ruler/total_judge_latency_ms`, amortized over `max_concurrent_judges`, fits within `time/step`. If not, the judge is the bottleneck: use a smaller judge or add replicas to `ruler.judge.base_url`.
- Under `mode: replace`, `reward/mean` equals `ruler/score_mean` exactly.

#### Evaluating a RULER-trained model

RULER attaches only to training environments. By design, two paths run the env's *native, ground-truth* rubric instead:

| Path                                | Rubric used                       | Why                                                                                |
| ----------------------------------- | --------------------------------- | ---------------------------------------------------------------------------------- |
| `eval:` block in `orch.yaml`        | Eval env's own rubric             | Online evaluation during training measures task improvement, not judge fit          |
| `surogate vf-eval` (standalone CLI) | Env's own rubric                  | `vf-eval` doesn't import the orchestrator config; it loads the env directly         |

If you trained against the judge, evaluating against the same judge is circular: the model may only have learned to look good to *that* judge. Evaluating against the env's hand-written verifier tells you whether RULER training improved task performance.

The recommended workflow:

1. Train with RULER as the reward source (`ruler.enabled: true`, optionally `mode: replace` if no native rubric exists).
2. Evaluate the trained model with `surogate vf-eval` against the env's native rubric:

   ```bash
   surogate vf-eval markdown-table-qa \
       --model Qwen/Qwen3-0.6B \
       --api-base-url http://localhost:8007/v1 \
       --num-examples 200 --rollouts-per-example 1 \
       --save-results
   ```

3. Compare to a baseline run (untrained model, or trained without RULER) to isolate the RULER training effect.

When the env has no usable rubric (open-ended generation, agentic tasks), `vf-eval` can't measure ground truth. You have two practical options:

- For offline evaluation, use a *different, stronger* judge than the one used in training, and keep it out of the training loop entirely. This breaks the circularity, though judge bias remains.
- Run `ruler.mode: metric` during training, so the judge logs `ruler/score_mean` without driving the gradient. This helps you check the judge's alignment while you iterate on the rubric prompt.

A complete worked example, with `train.yaml`, `infer.yaml`, `judge.yaml`, `orch.yaml` and a step-by-step runbook, is in [`examples/ruler/`](https://github.com/invergent-ai/surogate/tree/main/examples/ruler).

#### Reasoning-mode judges and token budgets

Reasoning models (Qwen3 with thinking on, OpenAI o-series, DeepSeek-R1) can spend thousands of chain-of-thought tokens before they start writing the JSON. If the judge runs out of tokens mid-response, the OpenAI SDK raises `LengthFinishReasonError`. RULER catches this and retries with double the `max_completion_tokens` (capped at 16K), but the wasted first attempt costs latency and tokens. Two things help:

1. Set a generous budget from the start. `ruler.sampling.max_completion_tokens: 4096` is a safe starting point for non-reasoning judges; raise it to 8192 or more for a reasoning judge.
2. Turn reasoning off on the judge. For Qwen3:

   ```yaml
   ruler:
     extra_body:
       chat_template_kwargs:
         enable_thinking: false
   ```

   For OpenAI o-series, set `ruler.sampling.reasoning_effort: minimal`.


### Learning Rate

RL training usually needs a lower learning rate than SFT (5e-7 to 5e-5). Start with `5e-6` and adjust it based on the KL divergence metrics.

### Masking Thresholds

Two settings keep training stable:

- The probability-difference mask (`ipo_mask_low`/`ipo_mask_high`, both `0.2`) leaves out a token when the trainer's probability for it is more than 0.2 above or below the rollout engine's.
- `ratio_clip` (e², about 7.39) caps each kept token's importance ratio. The mask alone doesn't bound it: a rare token can pass the mask with a ratio in the thousands.
- If `is_masked` in the logs is high (>50%), the policy is drifting too fast. Lower the learning rate or raise `kl_tau`.

### KL Penalty

`kl_tau > 0` adds a KL penalty that keeps the policy close to the reference (inference) policy. This prevents reward hacking but slows learning. Start with `kl_tau: 0.0` and raise it if the policy diverges.

### Gradient Accumulation

In SFT, gradient accumulation increases the effective batch size. In RL training it sets how many packed micro-batches each optimizer step processes. With `gradient_accumulation_steps: 1` and packed sequences, each step processes one densely packed sequence.

## Monitoring

The trainer logs these GRPO metrics at each step (see [Training metrics](/engine/guides/metrics/) for the general ones):

| Metric       | Description                                             |
| ------------ | ------------------------------------------------------- |
| `kl`         | Mean KL divergence between current and inference policy |
| `masked`     | Fraction of loss-eligible tokens that were masked       |
| `tokens`     | Total loss-eligible tokens in the step                  |
| `loss`       | Training loss (from the backward pass)                  |
| `grad_norm`  | Norm of the step's gradient, before clipping            |
| `teacher_kl` | KL from teacher to student (only when `teacher_tau > 0`) |

In a healthy training run:

- `kl` rises slowly from near zero (the policy is improving)
- `masked` stays below 30-40% (the policy isn't drifting too fast)
- `loss` trends downward
- `grad_norm` settles instead of growing from step to step. Values above `max_grad_norm` are clipped to it before the update

---

## Configuration Reference

### Inference config

The main inference options (the full list is in the [config reference](/engine/reference/config/#inference-server-config-inferyaml)):

| Key                       | Default        | Description                                            |
| ------------------------- | -------------- | ------------------------------------------------------ |
| `model`                   | (required)     | HuggingFace model ID or local path                     |
| `host`                    | `null`         | Bind address (null = all interfaces)                   |
| `port`                    | `8000`         | Bind port                                              |
| `max_model_len`           | `null`         | Maximum context length                                 |
| `max_num_seqs`            | `null`         | Max concurrent sequences (null = engine default)       |
| `kv_cache_dtype`          | `null`         | KV cache dtype, e.g. `fp8` (null = engine default)     |
| `tp`                      | `1`            | GPUs per replica; the engine splits the layers across them |
| `dp`                      | `1`            | Replicas, one whole model per GPU; not with `tp > 1`   |
| `enable_lora`             | `true`         | Enable LoRA hot-loading                                |
| `max_lora_rank`           | `null`         | Largest adapter rank the server accepts                |
| `max_loras`               | `8`            | Max simultaneously loaded LoRA adapters                |
| `seed`                    | `0`            | Sampling seed                                          |
| `enable_auto_tool_choice` | `false`        | Permit `tool_choice: "auto"`. Needed by a tool-using environment |
| `tool_call_parser`        | engine default | How the model marks a tool call; takes vLLM's names |
| `rope_scaling`            | `null`         | RoPE scaling configuration dict                        |

### Orchestrator config

The main orchestrator settings:

| Key                    | Default                 | Description                                                 |
| ---------------------- | ----------------------- | ----------------------------------------------------------- |
| `model.name`           | `null`                  | HuggingFace model ID or local path                          |
| `batch_size`           | `128`                   | Number of rollouts per training step                        |
| `rollouts_per_example` | `1`                     | Samples generated per prompt                                |
| `seq_len`              | `2048`                  | Maximum sequence length for packing                         |
| `max_steps`            | `null`                  | Total training steps (null = run indefinitely)              |
| `max_async_level`      | `1`                     | How many steps inference can lag behind trainer             |
| `max_off_policy_steps` | `8`                     | Max allowed policy lag for a rollout before it is discarded |
| `oversampling_factor`  | `1.0`                   | Factor by which to oversample rollout requests              |
| `output_dir`           | `"outputs/run_default"` | Directory for checkpoints, weights, rollouts, and logs      |
| `seed`                 | `42`                    | Random seed                                                 |

**Sampling** (`sampling.*`):

| Key                                         | Default | Description                                                   |
| ------------------------------------------- | ------- | ------------------------------------------------------------- |
| `sampling.max_tokens`                       | `null`  | Max tokens per generation                                     |
| `sampling.temperature`                      | `1.0`   | Sampling temperature (set this OR `temp_scheduler`, not both) |
| `sampling.temp_scheduler.type`              | ---     | Temperature schedule shape: `linear` or `cosine`              |
| `sampling.temp_scheduler.start_temperature` | ---     | Temperature at step 0                                         |
| `sampling.temp_scheduler.end_temperature`   | ---     | Temperature at final step                                     |
| `sampling.repetition_penalty`               | `1.0`   | Repetition penalty                                            |
| `sampling.min_tokens`                       | `0`     | Minimum tokens per sequence                                   |
| `sampling.seed`                             | `null`  | Sampling seed                                                 |

**Environments** (`env[]`):

| Key                   | Default    | Description                                                           |
| --------------------- | ---------- | --------------------------------------------------------------------- |
| `env[].id`            | (required) | Environment ID from the verifiers registry                            |
| `env[].name`          | `null`     | Optional human-readable name                                          |
| `env[].args`          | `{}`       | Environment-specific arguments                                        |
| `env[].address`       | `null`     | Address of external env server (null = spawn subprocess)              |
| `env[].teacher_model` | `null`     | Teacher for this environment's samples, in place of the top-level one |

**Teacher** (`teacher_model.*`, also under `env[].teacher_model`; see [On-Policy Distillation](#on-policy-distillation)):

| Key                        | Default       | Description                                                                   |
| -------------------------- | ------------- | ----------------------------------------------------------------------------- |
| `teacher_model.model.name` | `null`        | Teacher model name, as its server lists it                                    |
| `teacher_model.client.*`   | as `client.*` | Teacher server URL(s), timeout, API key variable                              |
| `teacher_model.rule`       | `null`        | Text only the teacher sees, spliced into its prompts (rule self-distillation) |

**Client** (`client.*`):

| Key                            | Default                        | Description                             |
| ------------------------------ | ------------------------------ | --------------------------------------- |
| `client.base_url`              | `["http://localhost:8000/v1"]` | Inference server URL(s)                 |
| `client.timeout`               | `1200`                         | Request timeout in seconds              |
| `client.api_key_var`           | `"SUROGATE_API_KEY"`           | Env var name for the API key            |
| `client.skip_model_check`      | `false`                        | Skip checking `/models` endpoint        |
| `client.elastic.hostname`      | ---                            | DNS hostname for elastic pool discovery |
| `client.elastic.port`          | `8000`                         | Port for elastic pool servers           |
| `client.elastic.sync_interval` | `5.0`                          | Discovery re-check interval (seconds)   |

To generate rollouts on several GPUs with a model that fits on one, serve it once with
`surogate serve <model> --devices 0,1,... --data-parallel` and give that one URL, or start one
server per GPU and list every URL in `client.base_url`. Either way, each GPU runs a whole copy
of the model. A `--devices` server without `--data-parallel` is a pipeline. That is meant for models
too large for one GPU, and it is many times slower for rollouts
([Pipeline or data-parallel](/engine/inference/cli/#pipeline-or-data-parallel)).

**Buffer** (`buffer.*`):

| Key                                  | Default              | Description                                             |
| ------------------------------------ | -------------------- | ------------------------------------------------------- |
| `buffer.seed`                        | `null`               | Random seed for deterministic sampling                  |
| `buffer.online_difficulty_filtering` | `false`              | Skip rollouts with reward 0.0 or 1.0                    |
| `buffer.easy_threshold`              | `null`               | Reward threshold above which a problem is "easy"        |
| `buffer.hard_threshold`              | `null`               | Reward threshold below which a problem is "hard"        |
| `buffer.easy_fraction`               | `0.0`                | Fraction of easy problems to promote to normal on start |
| `buffer.hard_fraction`               | `0.0`                | Fraction of hard problems to promote to normal on start |
| `buffer.normal_pool_min_examples`    | `0`                  | Recycle easy/hard examples when normal pool is this low |
| `buffer.recycle_easy_fraction`       | `0.0`                | Fraction of easy examples recycled when normal is low   |
| `buffer.recycle_hard_fraction`       | `0.0`                | Fraction of hard examples recycled when normal is low   |
| `buffer.sample_without_replacement`  | `false`              | Permanently consume an example when its rollout group is scheduled (one-attempt agentic tasks). Cannot be combined with recycling. |
| `buffer.hash_keys`                   | `["task", "prompt"]` | Keys used for example deduplication                     |
| `buffer.skip_verification`           | `false`              | If true, disable reward scoring (rewards always 0)      |
| `buffer.env_ratios`                  | `null`               | Per-environment sampling ratios (list, must sum to >0)  |

**Advantage** (`advantage.*`):

| Key                              | Default     | Description                                       |
| -------------------------------- | ----------- | ------------------------------------------------- |
| `advantage.type`                 | `"default"` | `"default"` or `"custom"`                         |
| `advantage.length_weighted_mean` | `false`     | Weight advantage by sequence length               |
| `advantage.import_path`          | ---         | (custom only) Import path to advantage function   |
| `advantage.kwargs`               | ---         | (custom only) Kwargs passed to advantage function |

**Filters** (`filters[]`):

| Key                            | Default  | Description                                              |
| ------------------------------ | -------- | -------------------------------------------------------- |
| `filters[].type`               | ---      | `"gibberish"` or `"repetition"`                          |
| `filters[].enforce`            | `false`  | If true, mask flagged rollouts from training loss        |
| `filters[].token_id_threshold` | `100000` | (gibberish) Min token ID to flag as gibberish candidate  |
| `filters[].logprob_offset`     | `2.0`    | (gibberish) Offset from uniform-distribution logprob     |
| `filters[].window`             | `3000`   | (repetition) Consecutive high-prob steps before flagging |
| `filters[].prob_threshold`     | `0.99`   | (repetition) Per-token probability threshold             |

**Checkpointing** (`ckpt.*`):

| Key                             | Default | Description                                    |
| ------------------------------- | ------- | ---------------------------------------------- |
| `ckpt.interval`                 | `null`  | Save checkpoint every N steps                  |
| `ckpt.resume_step`              | `null`  | Step to resume from (-1 = latest available)    |
| `ckpt.wait_for_weights_timeout` | `null`  | Seconds to wait for weight directory on resume |
| `ckpt.keep_last`                | `null`  | Keep at most N recent checkpoints              |
| `ckpt.keep_interval`            | `null`  | Permanently keep checkpoints at every N steps  |
| `ckpt.skip_progress`            | `false` | Skip restoring progress state from checkpoint  |
| `ckpt.skip_buffer`              | `false` | Skip restoring buffer state from checkpoint    |

**Online evaluation** (`eval.*`):

| Key                                     | Default    | Description                              |
| --------------------------------------- | ---------- | ---------------------------------------- |
| `eval.env[].id`                         | (required) | Eval environment ID                      |
| `eval.num_examples`                     | `-1`       | Examples per eval environment (-1 = all) |
| `eval.rollouts_per_example`             | `1`        | Rollouts per example during eval         |
| `eval.interval`                         | `100`      | Evaluate every N training steps          |
| `eval.eval_base_model`                  | `true`     | Also evaluate the unmodified base model  |
| `eval.skip_eval_on_resume`              | `true`     | Skip eval immediately after resuming     |
| `eval.cancel_inflight_rollouts_on_eval` | `false`    | Cancel in-flight rollouts before eval    |
| `eval.max_concurrent` | `128` | Most eval rollouts in flight at once, shared by all eval envs; the server's pending queue is sized for it. `null` sends the whole set at once |

**Reporting** (`report_to.*`):

| Key                       | Default      | Description                        |
| ------------------------- | ------------ | ---------------------------------- |
| `report_to.project`       | `"Surogate"` | W&B project name                   |
| `report_to.name`          | `null`       | W&B run name                       |
| `report_to.offline`       | `false`      | Run W&B in offline mode            |
| `report_to.samples`       | `null`       | Log prompt/response samples        |
| `report_to.distributions` | `null`       | Log reward/advantage distributions |
| `report_to.interval`      | `10`         | Logging interval in steps          |

**RULER** (`ruler.*`; see [RULER (LLM-as-Judge Rewards)](#ruler-llm-as-judge-rewards) above):

| Key                                     | Default                 | Description                                                                                           |
| --------------------------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------- |
| `ruler.enabled`                         | `false`                 | Master switch                                                                                         |
| `ruler.mode`                            | `"replace"`             | `"replace"` (RULER alone), `"add"` (sum with env rubric), `"metric"` (observability only, weight 0)   |
| `ruler.judge_model`                     | `null`                  | Judge model name (must be served by `judge.base_url`); required when `enabled: true`                  |
| `ruler.judge.base_url`                  | `null`                  | List of OpenAI-compatible judge endpoints (round-robined); required when `enabled: true`              |
| `ruler.judge.api_key_var`               | `"RULER_JUDGE_API_KEY"` | Env var holding the judge API key (use any string for an unauthenticated local server)                     |
| `ruler.judge.timeout`                   | `120.0`                 | Per-request timeout in seconds                                                                        |
| `ruler.judge.connect_timeout`           | `5.0`                   | Per-request connect timeout in seconds                                                                |
| `ruler.judge.max_connections`           | `256`                   | Max HTTP connections per endpoint                                                                     |
| `ruler.judge.max_keepalive_connections` | `256`                   | Max keep-alive HTTP connections per endpoint                                                          |
| `ruler.judge.max_retries`               | `4`                     | Auto-retries inside the OpenAI client                                                                 |
| `ruler.judge.headers`                   | `{}`                    | Extra HTTP headers sent with each judge request                                                       |
| `ruler.rubric`                          | (built-in default)      | Free-form rubric text passed to the judge as grading guidance                                         |
| `ruler.weight`                          | `1.0`                   | Multiplier on RULER score before combining with the reward; ignored in `metric` mode                  |
| `ruler.max_concurrent_judges`           | `32`                    | Global cap on concurrent judge HTTP calls across all envs (`null` = unbounded)                        |
| `ruler.request_timeout`                 | `null`                  | Per-judge-call timeout override (falls back to `judge.timeout`)                                       |
| `ruler.max_retries_on_parse_error`      | `2`                     | Retries when the judge returns malformed JSON                                                         |
| `ruler.swallow_exceptions`              | `true`                  | When true, judge failures drop the group instead of crashing the orchestrator                         |
| `ruler.debug`                           | `false`                 | Log per-group judge reasoning at INFO (otherwise DEBUG)                                               |
| `ruler.extra_body`                      | `{}`                    | Extra request-body fields forwarded to the judge (e.g. structured-output knobs)                      |
| `ruler.sampling`                        | `{}`                    | Sampling overrides for the judge call (`temperature`, `max_completion_tokens`, `reasoning_effort`)    |
| `ruler.cost.input_per_million`          | `null`                  | USD per 1M input tokens (drives `ruler/total_judge_cost_usd`)                                         |
| `ruler.cost.output_per_million`         | `null`                  | USD per 1M output tokens                                                                              |

**Transport** (`rollout_transport.*`, `weight_broadcast.*`):

| Key                        | Default        | Description                                      |
| -------------------------- | -------------- | ------------------------------------------------ |
| `rollout_transport.type`   | `"filesystem"` | `"filesystem"` or `"zmq"`                        |
| `rollout_transport.host`   | `"localhost"`  | (zmq only) ZMQ bind host                         |
| `rollout_transport.port`   | `5555`         | (zmq only) ZMQ bind port                         |
| `rollout_transport.hwm`    | `10`           | (zmq only) High-water mark (max queued messages) |
| `weight_broadcast.type`    | `"filesystem"` | `"filesystem"` or `"nccl"`                       |
| `weight_broadcast.host`    | `"localhost"`  | (nccl only) NCCL rendezvous host                 |
| `weight_broadcast.port`    | `29501`        | (nccl only) NCCL rendezvous port                 |
| `weight_broadcast.timeout` | `1200`         | (nccl only) NCCL timeout in seconds              |

### Trainer config (inherited from SFT)

GRPO trainer configs inherit every field of `SFTConfig`. These are the ones that matter most for RL training:

| Parameter                     | Default    | Description                                                 |
| ----------------------------- | ---------- | ----------------------------------------------------------- |
| `model`                       | (required) | HuggingFace model ID or local path                          |
| `gpus`                        | 1          | Number of GPUs (auto-derived from `--trainer-gpus` in split mode) |
| `sequence_len`                | 1024       | Maximum sequence length                                     |
| `learning_rate`               | 2e-4       | Initial learning rate                                       |
| `max_steps`                   | -1         | Training steps (-1 = run until orchestrator stops)          |
| `gradient_accumulation_steps` | 4          | Micro-batches per optimizer step                            |
| `per_device_train_batch_size` | 2          | Batch size per device (typically 1 for packed RL sequences) |
| `optimizer`                   | adamw_8bit | Optimizer type                                              |
| `recipe`                      | bf16       | Precision recipe (bf16, fp8_hybrid, nvfp4)                  |
| `lora`                        | true       | Enable LoRA adapters                                        |
| `lora_rank`                   | 16         | LoRA rank                                                   |
| `output_dir`                  | output     | Parent directory containing orchestrator `run_*` subdirs    |

All the LoRA, QLoRA, precision and multi-GPU settings from SFT are available. See the [Configuration guide](/engine/guides/configuration/) for the full list.

### GRPO-specific trainer fields

#### `loss` (nested)

Controls how the GRPO policy gradient loss is computed.

| Parameter       | Default    | Description                                                                          |
| --------------- | ---------- | ------------------------------------------------------------------------------------ |
| `variant`       | `"ipo"`    | `ipo`, `cispo` or `gspo` (one ratio per sequence, see [GSPO](#gspo-one-ratio-per-sequence)) |
| `ipo_mask_low`  | 0.2        | `ipo`: mask a token whose probability fell by more than this                         |
| `ipo_mask_high` | 0.2        | `ipo`: mask a token whose probability rose by more than this                         |
| `kl_tau`        | 1e-3       | `ipo`: KL penalty coefficient. Higher values keep the policy closer to the sampler   |
| `adv_tau`       | 1.0        | Advantage scaling factor                                                             |
| `teacher_tau`   | 0.0        | Teacher KL distillation coefficient (requires teacher logprobs)                      |
| `ratio_clip`    | 7.389056   | Cap on a token's importance ratio (`ipo`, `cispo`)                                   |
| `seq_clip_low`  | 3e-4       | `gspo`: clip the sequence ratio at `1 - seq_clip_low`                                |
| `seq_clip_high` | 4e-4       | `gspo`: clip the sequence ratio at `1 + seq_clip_high`                               |
| `seq_ratio_old` | `"inference"` | `gspo`: π_old from the rollout engine, or `trainer` (ratio 1, no clip)          |

#### `noise_scheduler` (nested)

QeRL adaptive quantization noise. See the [QeRL section](#qerl-adaptive-quantization-noise) above.

| Parameter     | Default | Description                                     |
| ------------- | ------- | ----------------------------------------------- |
| `enabled`     | `false` | Enable QeRL noise injection                     |
| `sigma_start` | `5e-2`  | Initial noise standard deviation                |
| `sigma_end`   | `5e-4`  | Final noise standard deviation                  |
| `num_stages`  | `10`    | Number of geometric decay intervals             |

#### `transport_type`

How the orchestrator delivers batches to the trainer.

| Value          | Description                                                    |
| -------------- | -------------------------------------------------------------- |
| `"filesystem"` | (default) IPC via shared filesystem. Simple and reliable       |
| `"zmq"`        | IPC via ZeroMQ sockets. Lower latency for co-located processes |

#### `max_async_level`

Sets how many weight broadcasts can be in flight at once. Default: `1`. Higher values let the inference engine fall further behind the trainer.

## See also

- [RL Environments](/engine/guides/rl-environments/): build the tasks and rewards GRPO trains on
- [Single-GPU GRPO](/engine/guides/rl-colocate/): run the whole loop on one card
- [GRPO kits](/engine/examples/kits/): ready-made tasks with measured before/after scores
- [QLoRA](/engine/guides/qlora/)
- [Multi-GPU Training](/engine/guides/multi-gpu/)
- [Precision & Recipes](/engine/guides/precision-and-recipes/)
- [Config reference](/engine/reference/config/)
- [Back to docs index](/engine/)
