# Single-GPU GRPO

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

Native co-locate mode lets you run [GRPO](/engine/guides/rl-training/) rollouts and LoRA training on a single GPU. The base
weights, including embeddings and normalization weights, are loaded once and shared by
both. Generation pauses during each training update, and the next batch uses
the updated adapter. Per-step adapter updates stay in GPU memory.

The mode works with the training families below (except Nemotron), using
unquantized BF16 safetensors weights with LoRA:

- Qwen3 and Qwen3.5, including their MoE variants and compatible Qwen3.6 checkpoints.
- Llama, MiniCPM5, and Spark-X2.5.
- Gemma 3 and Gemma 4, including E-series, unified, and MoE variants.
- LFM2/LFM2.5, LFM2-MoE, Qwen3-VL, and LFM2-VL.
- GPT-OSS and Laguna, when supplied as unquantized BF16 checkpoints.
- GLM-5.3-Flash text, including sparse DSA and persistent decode state; see the
  [tiny GLM fixture](/engine/examples/recipes/sft-glm/) for tested settings and limitations.

Multimodal checkpoints take text prompts only. Experimental training definitions
such as DeepSeek-V4 and Flash-Next are not included.

Generation uses continuous batching, so new requests can join while others
are still generating. Active generation has priority, but waiting prompts
keep making progress. Long prompts are processed in smaller chunks so
the server stays responsive.

Prompt and completed-turn caching reuse text that was already processed. This saves
work when GRPO asks for several completions of the same prompt, or continues a
conversation. Follow-up requests can reuse the earlier prompt and generated
response when their token history matches. Each request keeps its own sampling
settings and seed. Caches are cleared before each training update, so later
rollouts use the updated policy.
For models with sliding-window attention, older history is released as the window
advances. Full-attention models still need their complete history.

Three things limit context: available GPU memory, `max_model_len`, and the training
`sequence_len`. Use `max_num_seqs` to set how many requests run at once.
The whole model and its training buffers must fit alongside generation.

Dense Qwen3 and Qwen3.5 normally use the optimized generation server. The following
`infer.yaml` settings ([Inference server config](/engine/reference/config/#inference-server-config-inferyaml)) apply to models that use the shared training server:

| Setting | Default | When to change it |
|---|---|---|
| `decode_prefill_chunk` | `256` | Lower the maximum prompt tokens processed per round to improve responsiveness during long prompts. The server also reduces chunks automatically when busy or short of memory. |
| `decode_prefix_entries` | `32` | Increase the number of cached prompt and completed-turn prefixes for more reuse, at the cost of memory. Set `0` to disable both. |
| `decode_cache_bytes` | `0` | Cap generation cache memory in bytes. `0` selects 25% of free GPU memory after the trainer is loaded. |
| `decode_memory_bytes` | `0` | Cap total generation memory in bytes. `0` selects 80% of free GPU memory after the trainer is loaded. |

These memory budgets come on top of the model and training memory already in
use. When memory is tight, the server discards unused cached prompts and shrinks
batches. If a request still cannot fit, it gets HTTP 429 (a streaming request
reports an error and ends), and other requests carry on. Retry when capacity frees
up, or reduce concurrency or context length. Active requests cannot be
paused and moved to CPU to make room.

You can use text completions, streaming, and token-based multi-turn conversations with
function tools. Sampling options include temperature,
top-k/top-p/min-p, repetition/presence/frequency penalties, logit bias, and minimum
completion length. Returned log-probabilities describe the temperature-scaled
policy before penalties and filtering, which is what GRPO needs. Structured
`response_format` decoding is not supported on this path.

For MoE models and GLM, native co-locate automatically keeps rollout and scoring
log-probabilities consistent, including for packed conversations. This can make
training slower than ordinary SFT. Use `doc_masking: true` and
`sequence_chunks: 1` in the training config.

Set `long_context: true` and `lora_dropout: 0` to reduce memory use during scoring
and training with long sequences. See [long-context memory](/engine/guides/long-context/).

Pick a model and sequence length that fit on your GPU together with the training
activations and optimizer state. The whole base model must fit on one GPU, including every
expert of an MoE model. Training buffers stay reserved for the whole run.

Create `train.yaml`:

```yaml
model: Qwen/Qwen3.5-0.8B
output_dir: ./outputs/shared-grpo
gpus: 1
per_device_train_batch_size: 1
sequence_len: 2048
max_steps: 20
save_steps: 5
learning_rate: 1e-4
lr_scheduler_type: constant
recipe: bf16
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
```

Create `infer.yaml`:

```yaml
backend: surogate
model: Qwen/Qwen3.5-0.8B
enable_lora: true
max_model_len: 2048
max_num_seqs: 4
port: 8007
```

Create `orch.yaml`:

```yaml
model:
  name: Qwen/Qwen3.5-0.8B
  lora_adapter: default
  lora_rank: 16
  lora_alpha: 32
env:
  - id: markdown-table-qa
batch_size: 4
rollouts_per_example: 4
sequence_len: 2048
max_steps: 20
use_token_client: true
sampling:
  max_tokens: 1024
  temperature: 1.0
  top_p: 1.0
output_dir: ./outputs/shared-grpo/run_default
```

Run it on your chosen GPU with [`surogate grpo-colocate`](/engine/reference/cli/#grpo-colocate):

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

To use another supported model, put its checkpoint in all three files and take
the LoRA targets from that model's training example.
`lora_target_modules: [all]` selects every target its training definition supports.
For MoE models either `lora_dtype` works. With `fp32`, the expert LoRA gradients are
accumulated and stored in FP32 (BF16 activations, FP32 masters); `bf16` halves the
adapter's memory. Official quantized GPT-OSS and FP8 Laguna checkpoints must first be
exported as BF16; their quantized formats cannot be used in this mode.

Use the same model in all three files, the same `max_steps` in the training and
orchestrator configs, and an orchestrator output directory directly inside the training
output directory. Start each new run in a fresh directory. The runner connects
the orchestrator to the local server and turns on synchronous generation for you.

Reduce `max_num_seqs` to lower serving concurrency and memory use. On the shared
training path, `decode_cache_bytes` also caps persistent request cache storage.
Use `decode_memory_bytes` to cap that storage together with decode workspaces.
To lower memory use, reduce `sequence_len` and `max_model_len` together. Set `sequence_len` in both the
training and orchestrator configs. Leave enough generation tokens for the model
to finish its answer and earn a useful reward.

The run writes `shared_weights.jsonl` to the training output directory, with
the shared base size and policy version at each phase. Base
upload bytes and serving base allocation bytes should both be zero. Final adapters are saved as usual. Set `save_steps` in `train.yaml` to save
resumable checkpoints every few updates and at the end of the run. Set it to `0`
to disable checkpoint saving.

Native co-locate mode does not yet support quantized checkpoints, QLoRA, full fine-tuning, image/video prompts,
Nemotron, multiple GPUs, CPU weight offload, or QeRL weight noise. Use the [split-GPU runner](/engine/guides/rl-training/#split-gpu-mode) for those.

## Resume a run

Run the same command with the same output directories. With
`resume_from_checkpoint: true` in `train.yaml` (the default), native co-locate
restores the latest complete checkpoint, including the adapter, optimizer, and
rollout progress. Incomplete checkpoint saves are skipped. To extend a finished
run, increase `max_steps` in both `train.yaml` and `orch.yaml` before restarting.
Keep the model, adapter, optimizer type, and sequence length unchanged.

To resume from an earlier saved update, set `ckpt.resume_step` in `orch.yaml`:

```yaml
ckpt:
  resume_step: 10
```

The number counts completed training updates. Set `resume_step: -1`
(or leave it out) to pick the latest complete checkpoint. Later rollout work is
kept separately and regenerated from the restored policy. Generation caches
rebuild after a restart, so new rollouts may differ from those of an uninterrupted run.

Resuming needs checkpoints that this native runner saved, with both training and
rollout progress. An adapter export alone cannot resume a run. For a fresh run,
choose a new output directory, and set `resume_from_checkpoint: false` if you want.

## Agentic tool rollouts

Every supported family above accepts OpenAI function tools. Use a Verifiers
`ToolEnv` (or any environment that provides tool schemas and executes tool calls) and
set `use_token_client: true`. The server returns structured `tool_calls` with
JSON argument strings and `finish_reason: tool_calls`. The environment executes
the function and supplies the next tool message. For a runnable local example, see
[`examples/grpo/tools-orch.yaml`](https://github.com/invergent-ai/surogate/blob/main/examples/grpo/tools-orch.yaml).

The shared training server chooses the parser from the checkpoint's actual chat
template, including custom and `tool_use` variants:

| Checkpoint protocol | Families using it |
|---|---|
| JSON inside `<tool_call>` | Qwen3, Qwen3-MoE, Qwen3-VL |
| Function/parameter XML | Qwen3.5 and its variants |
| Function/param XML | MiniCPM5 (including checkpoints identifying as Llama) |
| Argument-key/value XML | GLM-5.3-Flash, Spark-X2.5, Laguna |
| JSON or Python function lists | Llama tool templates, Gemma 3 tool templates |
| Python function lists with control tokens | LFM2/LFM2.5, MoE and VL text variants |
| Gemma tool and channel tokens | Gemma 4 variants |
| Harmony channels and tool handoff | GPT-OSS |

Templates without tool support get a JSON tool prompt and adapted tool history, and
checkpoints without a chat template use a basic text template. That gives base models
the interface too, though they still have to learn to use tools.
The optimized Qwen server enables automatic tool choice and accepts both Qwen
JSON and function/parameter XML responses.

Raw completion IDs and per-token policy log probabilities include reasoning,
tool syntax and stop tokens. Parsing changes only the HTTP message fields.
The token client appends tool results while keeping earlier generated IDs, and
tool results get a zero loss mask. Its template bridge keeps function names
for GPT-OSS/Gemma and a stable dummy reasoning span for Qwen. The bridge is installed
in the orchestrator and its environment workers.

Tool calls are exposed only after a complete generation that ended normally.
Incomplete, malformed, unknown-function or length-truncated calls stay as text.
Parallel calls work in formats that allow them. On the shared training
path, `parallel_tool_calls: false` prevents returning multiple executable calls.
That path supports `tool_choice: auto` and `none`; required/named choices and
schema-constrained decoding are unavailable. Function `strict` metadata is
accepted for Verifiers compatibility but does not turn on constrained sampling, so
the environment handles argument validation and execution errors.
In streaming responses, tool arguments are buffered until the generation completes.
Harmony chat fields are buffered too, while raw token/logprob events keep streaming.
Multimodal tool results are not supported; use text or text-only content parts.

Next: the [GRPO kits](/engine/examples/kits/) are ready-made single-GPU runs with measured results, and [RL Training (GRPO)](/engine/guides/rl-training/) explains the loss, the orchestrator settings and the other runners.
