Skip to content
SurogateSurogateDocs
↑↓ to move↵ to openesc to close

Configuration Reference

This page lists every configuration option in Surogate, with what it does, its default and the values it accepts.

OptionTypeDefaultDescription
run_name#stringauto-generatedA descriptor for the run. If not provided, a unique name is generated automatically.
num_epochs#int3Total number of training epochs to perform.
output_dir#string"output"The output directory where the model predictions and checkpoints will be written.
checkpoint_dir#stringnullDirectory to save checkpoints during training. If None, defaults to output_dir.
resume_from_checkpoint#booltrueContinue from checkpoint. If enabled, uses the latest checkpoint.
save_steps#int50Number of steps between saving checkpoints.
save_total_limit#int5Limit the total amount of checkpoints. Deletes older checkpoints in output_dir.
from_scratch#boolfalseTrain from scratch (random initialization) instead of fine-tuning a pre-trained model.
OptionTypeDefaultDescription
model#stringrequiredPath or HuggingFace model identifier (e.g., "Qwen/Qwen3-0.6B").
model_type#stringauto-detectType of the model group. Automatically detected from model config if not specified.
sequence_len#int1024Maximum sequence length for training. Samples exceeding this length are truncated.
max_model_len#intnullMaximum model length for rope scaling. Automatically detected from model config if not specified.
rope_scaling#stringnullType of RoPE scaling. Pass a string like "linear", "dynamic", or "yarn" along with max_model_len to automatically configure rope_scaling. Alternatively, pass a JSON string like '{"factor": 2.0, "type": "yarn"}' to directly override the rope_scaling in the model’s config.
torch_dtype#stringauto-detectPyTorch data type for model weights. Options: "bfloat16", "float16", "float32". Automatically detected from model config if not specified.

Recomputation saves memory at the cost of extra compute: activations are recomputed during the backward pass instead of being stored. The Memory guide shows when to reach for it.

OptionTypeDefaultDescription
recompute#booltrueEnable activation recomputation. false saves all activations (fastest, most memory). true recomputes intermediates from checkpoints (saves VRAM, small compute overhead).
qlora_recompute#booltrueQLoRA and pre-quantized bases recompute whatever recompute says. Set false together with recompute: false to save their activations instead (verified with parallelism: dispatch_pp on a pre-quantized NVFP4 base).

Chunked-Sequence Training (long sequences)

Section titled “Chunked-Sequence Training (long sequences)”

You can train sequences far longer than activation memory would normally allow. The engine runs the layer stack over fixed-size chunks and carries attention KV from one chunk to the next. Memory stays at the single-chunk footprint plus a small KV/state budget (KV is 2 * kv_heads * head_dim bytes per token per attention layer), while gradients remain exact: backward walks chunks in reverse and accumulates dK/dV in FP32. Trailing all-padding chunks are skipped automatically, since nothing attends to them. It works with sample_packing (per-document attention across chunk boundaries is preserved, including documents split across rows) and with GDN hybrid models (Qwen3.5/3.6: the delta-rule recurrent state and causal-conv tail are carried across chunks exactly). It requires per_device_train_batch_size: 1, BF16 attention, and lora_dropout: 0; CUDA graphs are disabled automatically. It applies to GRPO as well as SFT: when sequence_chunks > 1, the native GRPO step dispatches to the chunked path, which windows the GRPO dloss per chunk and skips all-padding tail chunks. It also works with parallelism: dispatch_pp, where every chunk passes through every stage; that is the 131k path (dispatch-PP: long sequences).

OptionTypeDefaultDescription
sequence_chunks#int1Process sequence_len as N chunks of sequence_len / N tokens (must divide evenly). 1 = normal dense training.

CPU-RAM centric training keeps model weights and optimizer state on the CPU and streams them to and from the GPU one layer at a time. You can then train models that don’t fit in GPU memory, on one GPU or on several with plain data parallelism (no ZeRO sharding needed).

OptionTypeDefaultDescription
cpu_training#boolfalseEnable CPU-RAM centric training. Streams weights from CPU per-layer during forward/backward, offloads gradients to CPU per-layer, and runs FP32 AdamW optimizer on CPU. Works with single-GPU and multi-GPU (data parallelism via per-layer NCCL all-reduce). Disables CUDA graphs.

What cpu_training enables:

  • Weight streaming: base model weights live in CPU pinned memory and load to the GPU one layer at a time through a double-buffered prefetch, which overlaps H2D copies with compute.
  • Gradient streaming (FFT only): during backward, parameter gradients are copied to the CPU layer by layer through a double-buffered D2H, then the GPU buffers are reused. GPU gradient memory stays constant whatever the model depth.
  • CPU optimizer (FFT only): FP32 AdamW runs on the CPU with OpenMP. There is no 8-bit quantization, because CPU RAM is plentiful.
  • LoRA support: with LoRA only weight streaming is active. The adapters and their optimizer are small, so they stay on the GPU.
  • Multi-GPU: each GPU streams weights on its own. Gradients are all-reduced per layer on the GPU (over NVLink/PCIe) before the D2H copy, and every rank runs the same CPU optimizer update, so the weights stay in sync.

GPU memory usage with cpu_training:

ComponentWithout cpu_trainingWith cpu_training
Model weightsAll layers on GPU~2 layers (double-buffered prefetch; see the tuning knobs below to raise the slot count or pin the first N layers on device)
Gradients (FFT)All layers on GPU~2 layers (double-buffered D2H)
Optimizer stateOn GPU (8-bit quantized)On CPU (FP32, unlimited RAM)
ActivationsPer recompute settingsSame
LoRA adaptersOn GPUOn GPU (unchanged, small)

Limitations:

  • Not compatible with QLoRA (qlora_bnb, qlora_fp8, qlora_fp4) or pre-quantized models. These use a separate weight pipeline that doesn’t support CPU streaming.
  • Not recommended for MoE models: streaming expert weights per layer means many small PCIe transfers and is too slow. Use QLoRA with qlora_offload_experts instead.
  • Mutually exclusive with ZeRO sharding (zero_level > 1).

Example:

yaml
model: Qwen/Qwen3-8B
cpu_training: true
lora: true
lora_rank: 16
per_device_train_batch_size: 2
sequence_len: 2048

cpu_training is usually PCIe-bound: the GPU spends much of the step waiting for the next layer’s weights. Profiling a 27B fp8 step (Nsight Systems, RTX 5090) found the GPU idle 29.4% of wall time (26.1% of it with an H2D transfer in flight, only 3.3% launch-bound), while H2D ran at 53.5 GB/s, which is PCIe 5.0 line rate, with 97% of bytes in transfers larger than 16 MB. No bandwidth or batching is left to recover, so the knobs below either overlap the transfers better or take bytes off the bus.

All of them are numerically neutral: they change where bytes live and when they move, and leave the computation alone. They are off by default because each one spends GPU memory, and the safe amount depends on your model, sequence length and free VRAM.

VariableDefaultEffect
SUROGATE_DISPATCH_PREFETCH_BLOCKS#2Number of layer prefetch slots. 3 is the measured knee (4 and 6 were no better); costs one extra layer of weights in VRAM. Under parallelism: dispatch_pp it is the resident weight window instead: the trainers set it to the most layers any GPU runs plus two (dispatch-PP).
SUROGATE_RESIDENT_LAYERS#0Keep the first N layers’ quantized masters in device memory, so their per-traversal gather is a D2D copy instead of PCIe traffic. Works for both FP8 and NVFP4; promoted after quantization, so each costs its quantized size rather than the BF16 size the import needed. Raise it until it OOMs at startup, then back off. NVFP4 fits roughly twice as many layers (0.5625 B/param with SUROGATE_FP4_DERIVE_WT vs FP8’s 1.0).
SUROGATE_SHARED_NONBLOCK_STAGING#unsetReverts the resident embedding/lm_head buffers to one shared staging buffer (saves ~max(emb, lm_head) VRAM, costs ~5 GB of PCIe traffic per sweep).
SUROGATE_GRPO_FULL_KV_SWEEP#unsetRestores the Phase-A KV sweep for the last occupied chunk in chunked GRPO. Slower, but bit-exact against the pre-optimization engine.
SUROGATE_QUANT_ATTN_PROJ#recipe-dependentForce attention/GDN projection quantization on (1) or off (0). Defaults on for FP8 (+0.36% loss for −6.5% step time) and off for NVFP4 (+3.01% loss — not worth it).
SUROGATE_FP4_DERIVE_WT#unsetNVFP4 only: stream just the forward weight blob (0.5625 B/param instead of 1.125) and rebuild the dgrad transpose on device. Wins when PCIe-bound (27B: −4.5%), loses when compute-bound (2B: +2.4%).

Measured on a 27B hybrid, fp8, single RTX 5090, 20 identical micro-batches:

Configurations/micro-batch
defaults7.175
PREFETCH_BLOCKS=37.117 (−0.8%)
PREFETCH_BLOCKS=3 + RESIDENT_LAYERS=166.832 (−4.8%)
PREFETCH_BLOCKS=3 + RESIDENT_LAYERS=206.748 (−6.0%)
RESIDENT_LAYERS=24 and aboveout of memory on 32 GB

The same knobs applied to NVFP4 on the same workload, where the smaller blob allows far more residency (SUROGATE_FP4_DERIVE_WT=1 SUROGATE_DISPATCH_PREFETCH_BLOCKS=3):

Configurations/micro-batch
nvfp4 before this work9.338 (and OOM’d under cpu_training at all)
stream_fp4#7.151 (−23.4%)
+ FP4_DERIVE_WT6.834 (−26.8%)
+ RESIDENT_LAYERS=406.420 (−31.2%)
RESIDENT_LAYERS=52 and aboveout of memory on 32 GB

Fully tuned, NVFP4 ends up ~5% faster than fully tuned FP8 on a transfer-bound step, because it converts VRAM into avoided PCIe traffic about twice as efficiently. It still costs more accuracy (≈+3.4% loss against BF16 over 120 training steps, versus ≈+0.3% for FP8-hybrid), so FP8-hybrid remains the better default and NVFP4 the choice when memory is the constraint.

The gain grows with how much of the model stops crossing the bus, so the useful ceiling is whatever VRAM allows: on a 32 GB card with this 27B model that was 20 layers. Only the FP8-streamed weights are promoted (the fields in the stream-eligible set, i.e. mlp_up and mlp_down on a Qwen3.5/3.6 hybrid), so the log line promoted N FP8 block masters to device tells you how many actually moved.

Start with SUROGATE_DISPATCH_PREFETCH_BLOCKS=3, then raise SUROGATE_RESIDENT_LAYERS until it OOMs at startup and back off by one. Both fail fast with a clear error if they don’t fit.

These options give fine-grained control over CPU offloading (see the Offloading guide). For most setups cpu_training: true is simpler and replaces them; they stay available for advanced configurations and backward compatibility.

OptionTypeDefaultDescription
offload_residual#boolfalseOffload residuals (of the FFN block) to pinned host memory. Combined with recompute, total activation memory becomes independent of network depth.
offload_master#boolfalseLegacy — use cpu_training instead. Store master weights in pinned host memory.
offload_quants#boolfalseStore quantized weights in pinned host memory. Requires persistent_quants.
offload_optimizer#boolfalseLegacy — use cpu_training instead. Store optimizer state in pinned host memory.
offload_grads#boolfalseLegacy — use cpu_training instead. Offload gradients to pinned host memory.
persistent_quants#boolfalseAvoid re-quantization of weights. Increases memory, but when combined with offload_quants, the additional memory is placed on the host. In PCIe settings, this can lead to significant speed-ups. Requires shard_weights.
use_zero_copy#boolfalseLegacy — use cpu_training instead. Use ZeroCopy memory access for offloaded optimizer states.
use_write_combined#boolfalseLegacy — use cpu_training instead. Use write-combined memory for offloaded tensors.

These options apply to single-node multi-GPU training, covered in the Multi-GPU guide. For multi-node distributed training, see Multi-Node Distributed Training.

OptionTypeDefaultDescription
zero_level#int1ZeRO redundancy optimization level: 1 = sharded optimizer states (default), 2 = sharded gradients + optimizer states, 3 = sharded weights + gradients + optimizer states.
shard_weights#boolfalseShard model weights across data-parallel processes. Enables more effective offloading and reduces memory consumption.
shard_gradients#boolfalseShard gradients across data-parallel processes. Enables more effective offloading and reduces memory consumption.
use_all_to_all_reduce#boolfalseUse all-to-all-based reduce algorithm (combine with memcpy_send_recv).
memcpy_all_gather#boolfalseUse memcpy for all-gather operations (threads backend only). Generally gets better bandwidth utilization on PCIe and does not consume SM resources.
memcpy_send_recv#boolfalseUse memcpy for send/receive operations (threads backend only).

Spread MoE experts across GPUs so each GPU holds num_experts / ep_size local experts. See the MoE guide and Adaptive Training for LLEP details.

OptionTypeDefaultDescription
ep_size#int1Number of GPUs per expert-parallel group. Must divide gpus and num_experts. 1 disables EP.
ep_load_balance_threshold#float1.3Imbalance ratio (max_gpu_load / mean_gpu_load) above which LLEP dynamic load balancing activates. 1.0 = always active; large values (e.g. 999) = static EP only.
ep_plan_refresh_interval#int16LLEP sticky plans: the expert placement plan is recomputed every N forward dispatches per layer. Between refreshes the plan is reused, which skips the per-layer imbalance all-reduce and lets foreign expert weights be prefetched one layer ahead. 1 = recompute every step.

Pipeline Parallelism (dispatch-PP) Options

Section titled “Pipeline Parallelism (dispatch-PP) Options”

A model-parallel mode for models whose base weights don’t fit on one GPU, on PCIe-only machines. See Dispatch Pipeline Parallelism. Mutually exclusive with the ZeRO options above, cpu_training, and MoE expert parallelism (ep_size > 1); CUDA graphs are auto-disabled.

OptionTypeDefaultDescription
parallelism#strunsetSet to dispatch_pp to enable Dispatch Pipeline Parallelism (or ddp/unset for the default data-parallel path).
offload_master#boolfalseRequired for dispatch-PP on models that can’t sit resident: streams the frozen base weights from pinned CPU per block.
recipe#strbf16bf16 or fp8_hybrid. fp8_hybrid quantizes the frozen matmul base weights to FP8-E4M3 once at load and streams them as FP8 (~half the PCIe bytes).

Each step runs gpus × gradient_accumulation_steps microbatches, accumulated into one optimizer step. Set the stage size with the SUROGATE_DISPATCH_STAGE_BLOCKS environment variable (default 4).

Settings for training across several machines with Ray and NCCL. The Multi-Node Training Guide walks through the setup.

OptionTypeDefaultDescription
distributed.ray_address#string"auto"Ray cluster address. Options: "auto" (connect to existing cluster), "local" (start local instance), "ray://host:port" (connect to specific head).
distributed.num_nodes#int1Total number of nodes to use for training. Set to > 1 to enable multi-node training.
distributed.gpus_per_node#int0Number of GPUs per node. If 0, uses the value from gpus config parameter.
distributed.worker_output_dir#stringnullBase directory for worker-local tokenized data. Each worker creates a node-{rank}/ subdirectory. If null, uses /tmp/surogate-{run_name}/ on each node.

Example configuration:

yaml
distributed:
ray_address: "auto"
num_nodes: 2
gpus_per_node: 8
worker_output_dir: /shared/surogate-data

Offline top-K logit distillation on the SFT path. Capture teacher logprobs once with surogate distill-capture config.yaml, then train with surogate sft config.yaml. The teacher and student must share a tokenizer. See the Knowledge Distillation Guide. Single-node only (mutually exclusive with distributed: and parallelism: dispatch_pp); CUDA graphs and lmhead_drop_ignored_rows are auto-disabled.

OptionTypeDefaultDescription
distillation.teacher_model#stringnullTeacher model id or path. Required by distill-capture; ignored at train time.
distillation.top_k#int32Teacher logprobs stored per token. Range [1, 1024]; training validates that sidecars were captured with this exact value.
distillation.temperature#float1.0Distillation temperature τ (> 0).
distillation.kd_weight#float0.5Weight of the KD (KL) term (≥ 0).
distillation.ce_weight#float1 - kd_weightWeight of the CE term (≥ 0). Must be set explicitly when kd_weight > 1.
distillation.teacher_batch_size#int4Capture-time only (local backend): windows of sequence_len tokens per teacher forward pass (≥ 1).
distillation.kd_dir#stringnullSidecar directory override. Default: alongside the token shards. The trainer bridges kd_dir captures to the native DataLoader via <shard>.kd symlinks.
distillation.teacher_api_base#stringnullCapture-time only: OpenAI-compatible base URL of a served teacher (e.g. http://localhost:8000/v1). Switches capture to a vLLM API backend; teacher_model is then the served model name. Requires a vLLM server started with --max-logprobs >= top_k; aggregators (e.g. OpenRouter) cannot be used.
distillation.teacher_api_key_var#string"VLLM_API_KEY"Capture-time only: env var holding the API key. Empty/unset resolves to EMPTY (accepted by local vLLM).
distillation.teacher_api_concurrency#int8Capture-time only: concurrent in-flight API capture requests (≥ 1).
distillation.teacher_api_timeout#int1200Capture-time only: per-request API timeout in seconds (≥ 1).

Example configuration:

yaml
distillation:
teacher_model: Qwen/Qwen3-1.7B
top_k: 64
temperature: 1.0
kd_weight: 0.5
OptionTypeDefaultDescription
gpus#int1Number of GPUs to use for training. Use 0 for all available GPUs.
use_cuda_graphs#booltrueEnable CUDA graphs for performance.
OptionTypeDefaultDescription
recipe#string"bf16"Mixed precision training recipe. Options: "bf16" (default), "fp8_hybrid", "nvfp4".
gradient_dtype#stringnullDtype for activation gradients / backward matmul policy. Defaults to matmul-dtype. Note: recipes may override backward dtype.
master_dtype#stringnullMaster weight dtype for optimizer updates (e.g., FP32 for stable full fine-tuning). Defaults to model-dtype.
use_fused_rope#boolfalseUse fused RoPE kernel with on-the-fly cos/sin computation (saves memory, reduces bandwidth).
OptionTypeDefaultDescription
fp8_amax_history#int16FP8 delayed scaling amax history length (for fp8_hybrid recipe).
fp8_pow2_scales#boolfalseUnder fp8_hybrid, round every per-tensor FP8 scale (JIT and delayed) down to a power of two, so a token quantizes to the same bits whatever else shares its tensor (padding, or the other rows of a packed window). Costs at most one bit of range headroom. Recommended with row_packing.
fp8_weight_cache#stringautoKeep FP8 copies of frozen weights (the LoRA base) so each is quantized once per run instead of at every matmul of every micro-batch. Costs two bytes per frozen weight element (forward copy plus transposed backward copy). auto enables it when the copies fit in free GPU memory with a margin; on / off force it. Trainable weights are never cached.
OptionTypeDefaultDescription
fp4_backend#string"cutlass"FP4 matmul backend: "cutlass" (default) or "cudnn" (for nvfp4 recipe).
OptionTypeDefaultDescription
skip_quant_first_layers#int0Skip quantization for the first N transformer decoder layers. (embedding layers are always kept in BF16).
skip_quant_last_layers#int0Skip quantization for the last N transformer decoder layers (lm_head layers are always kept in BF16).
OptionTypeDefaultDescription
optimizer#string"adamw_8bit"Optimizer type. Options: "adamw_8bit" (8-bit AdamW), "normuon" (NorMuon hybrid)
learning_rate#float2e-4The initial learning rate for the optimizer.
lr_scheduler_type#string"linear"Learning rate schedule function: "linear", "cosine", or "wsd".
warmup_ratio#float0.0Ratio of total training steps used for linear warmup from 0 to learning_rate.
warmup_steps#int0Number of steps for linear warmup. Overrides warmup_ratio if set.
cooldown_steps#int0Number of steps for linear cooldown from learning_rate to final_lr_fraction * learning_rate.
final_lr_fraction#float0.0Final learning rate as a fraction of the initial learning rate.
weight_decay#float0.1Weight decay applied to all layers except bias and LayerNorm weights.
max_grad_norm#float1.0Maximum gradient norm for gradient clipping. 0.0 disables clipping.

Used when optimizer: "adamw_8bit" (default).

OptionTypeDefaultDescription
adamw_beta1#float0.9The beta1 parameter for AdamW optimizer.
adamw_beta2#float0.999The beta2 parameter for AdamW optimizer.
adamw_epsilon#float1e-8The epsilon parameter for AdamW optimizer.

Used when optimizer: "normuon". NorMuon (see the Optimizers guide) is a hybrid: it uses AdamW for embeddings, norms and lm_head, and orthogonalized momentum for 2D weight matrices.

OptionTypeDefaultDescription
normuon_momentum#float0.95Momentum coefficient for orthogonalized momentum updates in 2D weight matrices.
normuon_beta2#float0.95Second moment coefficient for variance tracking in NorMuon optimizer.
normuon_cautious_wd#booltrueEnable cautious weight decay that only applies decay when gradient and momentum align.
OptionTypeDefaultDescription
per_device_train_batch_size#int2Batch size per device during training/evaluation.
gradient_accumulation_steps#int4Number of update steps to accumulate gradients before performing backward/update pass. Effective batch size = batch_size × grad_accumulation × num_gpus.
max_steps#int-1Total number of training steps. -1 derives from epochs and dataset size.
eval_steps#int100Run evaluation every N optimizer steps.
train_vision#boolnullIf true, run the vision encoder during training to process images/videos. If false, train on text only. If null and the model is multimodal, defaults to true.
OptionTypeDefaultDescription
datasets#listnullList of datasets for training. Each dataset should specify path, type, and other dataset-specific options. See Dataset Configuration Options below.
validation_datasets#listnullList of datasets for validation during training. If not provided, uses validation_split_ratio to create validation split from training data. Uses same format as datasets.
validation_split_ratio#float0.1Ratio of training data to use for validation if no validation_datasets are provided. Value between 0.0 and 1.0.
train_seed#int1234Random seed for the training dataloader. Controls shuffling and sampling order.
eval_seed#int1234Random seed for the evaluation dataloader. Controls shuffling and sampling order.
dataloader_num_workers#intautoNumber of subprocesses to use for data loading. 0 means data will be loaded in the main process. Defaults to optimal value based on CPU count.
sample_packing#booltrueWhether to enable sample packing to fit multiple data samples into a single sequence. Packing reduces the number of samples in the dataset; adjust gradient accumulation steps and learning rate accordingly for packed datasets. Tokenize-time packing concatenates documents into a continuous stream cut every sequence_len tokens, so a document can be split across two windows; use row_packing when every example must stay whole.
row_packing#boolfalseTrain-time packing of a padded shard (one example per window, e.g. sample_packing: false). Each optimizer step loads exactly the rows padded training would, cuts each row after its last supervised position, and packs them into ceil(windows / (gpus × per_device_train_batch_size)) micro-steps instead of gradient_accumulation_steps; every row is its own attention document (position ids restart at 0), its KD sidecar rows travel with it, and the loss is normalised over the same supervised tokens. Rows per step, epochs, checkpoints and the tokenize hash are unchanged. Disables CUDA graphs (the micro-step count varies); not with sequence_chunks, dispatch_pp or multi-node training. See Row packing.

row_packing: true keeps everything that defines the optimisation of a padded run and removes the padding compute. What stays identical to padded training, and why:

  • The rows of every step and their order: the step still makes gradient_accumulation_steps loader calls, so the data-loader position saved in checkpoints, epoch boundaries and SUROGATE_AUDIT_TRAIN_BATCHES audits are the padded run’s.
  • Each row’s forward: position ids restart at 0 at every row, which the engine turns into document masking (FlashAttention varlen for sliding-window layers, the mem-efficient kernel for wide global heads). Linear-attention layers (Qwen3.5-family Gated DeltaNet) mix tokens outside attention too, and restart at every document: the causal convolution reads zeros before a document’s first token, and the gated delta rule runs each document as a sequence of its own from a zero recurrent state, so a row computes what it computes at the start of a padded window (bit-identical per-row losses on Qwen3.5-0.8B, 32 rows, bf16). Every other op is per token and the micro-batch shape (per_device_train_batch_size × sequence_len) is the padded one, so the same kernels run on the same rows: with recipe: bf16 a row’s per-token losses were bit-identical packed and padded in every measurement (Gemma 4 MoE fixtures and a real-weight truncation, RTX 5090).
  • Each row’s backward, per token: activation gradients do not depend on where the row sits in its window (the autodiff accumulation adds round to nearest, and the deterministic attention backward uses a split count fixed by the batch geometry, not by the number of documents); measured bit-identical.
  • Loss normalisation: the step’s summed loss and gradient are divided by the step’s supervised-token count, the same tokens in both layouts.

What differs is floating-point summation order: a packed window’s weight gradient sums several rows inside one GEMM, where padded training sums them across micro-steps in the gradient dtype. The measured difference is within the spread padded training shows when only its micro-step order changes. Rows are spread over all the windows a step needs, which keeps windows no fuller than necessary.

Under fp8_hybrid, per-tensor quantisation scales span the whole micro-batch, so by default a row’s arithmetic also depends on the other rows of its window (as it would with per_device_train_batch_size > 1). Set fp8_pow2_scales: true with row packing: scales rounded down to powers of two only shift exponents, so an element quantises to the same bits whatever the window’s maximum, except elements that fall into the FP8 subnormal range because another row raised the maximum (more than ~2^14 below it for E4M3, ~2^29 for E5M2). Measured on a real-weight Gemma 4 truncation: 31 of 32 rows’ losses bit-identical to padded training with the same setting, the other within 0.005 nats.

Requirements and limits: a padded shard (sample_packing: false), doc_masking on (the default), lora_dropout: 0 (dropout masks are drawn by buffer position) and zero MoE router aux/z loss coefficients for row-for-row equivalence (they are computed over each micro-step’s tokens; the config warns). Not supported with sequence_chunks, parallelism: dispatch_pp, ep_size > 1, train_vision or multi-node training. CUDA graphs are disabled because the micro-step count varies per step. At most 64 rows share a window.

Each entry in the datasets or validation_datasets list takes the options below; the Datasets guide has an overview. The dataset type decides which extra fields are required.

OptionTypeDefaultDescription
path#stringrequiredHuggingFace dataset repo, s3:// URL, gs:// URL, or path to local file or directory.
type#stringrequiredDataset type. Options: "text", "instruction", "conversation", "preference" (DPO), "auto" (auto-detect format).
subset#stringnullHuggingFace dataset subset/configuration name to load (e.g., "default" for datasets with multiple configurations).
split#string"train"Dataset split to load. Common values: "train", "test", "validation".
samples#intnullLimit the number of samples to use from this dataset. If not specified, uses all available samples.

For pre-training or continued pre-training on raw text data.

OptionTypeDefaultDescription
text_field#string"text"Name of the column in the dataset that contains the raw text content.

Example:

yaml
datasets:
- path: "HuggingFaceFW/fineweb-edu"
type: text
text_field: text
split: train
samples: 100000

Instruction Dataset Options (type: "instruction")

Section titled “Instruction Dataset Options (type: "instruction")”

For instruction-following datasets with system/instruction/input/output format.

OptionTypeDefaultDescription
instruction_field#stringrequiredName of the column containing the instruction/question.
output_field#stringrequiredName of the column containing the expected output/answer.
input_field#stringnullName of the column containing additional input context (optional).
system_prompt_type#stringnullHow to provide system prompt. Options: "field" (from dataset column), "fixed" (same for all samples), null.
system_prompt_field#stringnullName of the column containing system prompts (required when system_prompt_type: "field").
system_prompt#stringnullFixed system prompt text to use for all samples (required when system_prompt_type: "fixed").
prompt_format#stringnullCustom prompt format template. Use {system}, {instruction}, {input}, {output} as placeholders.
prompt_format_no_input#stringnullCustom prompt format when no input field. Use {system}, {instruction}, {output} as placeholders.

Example:

yaml
datasets:
- path: "yahma/alpaca-cleaned"
type: instruction
instruction_field: instruction
input_field: input
output_field: output
system_prompt_type: fixed
system_prompt: "You are a helpful AI assistant."

Conversation Dataset Options (type: "conversation")

Section titled “Conversation Dataset Options (type: "conversation")”

For multi-turn conversational datasets in chat format.

OptionTypeDefaultDescription
messages_field#string"messages"Name of the column containing the list of conversation messages.
system_field#stringnullName of the column containing the system prompt for the conversation (optional).
tools_field#stringnullName of the column containing tool/function definitions for function calling.
message_property_mappings#dict{"role": "role", "content": "content", ...}Mapping of message property names if dataset uses non-standard field names.

Example:

yaml
datasets:
- path: "HuggingFaceH4/ultrachat_200k"
type: conversation
messages_field: messages
split: train_sft

Preference Dataset Options (type: "preference")

Section titled “Preference Dataset Options (type: "preference")”

For offline DPO. Each row has prompt (a string or a chat messages list), chosen, and rejected (the two competing assistant continuations). Chat rows may also set enable_thinking to control the generation prefix. Loss is applied only on the response tokens. Used by the surogate dpo command together with the DPO loss block. Preference datasets load through the same pipeline as the other types, so path may be a local JSONL/JSON/parquet/CSV file, a dataset directory, or a HuggingFace hub repo, and subset/split/samples apply as usual.

OptionTypeDefaultDescription
prompt_field#string"prompt"Name of the column containing the prompt (string or chat messages list).
chosen_field#string"chosen"Name of the column containing the preferred response.
rejected_field#string"rejected"Name of the column containing the dispreferred response.
enable_thinking_field#string"enable_thinking"Name of the optional column controlling the chat-template thinking prefix.
json
{"prompt": "...", "chosen": "preferred response", "rejected": "dispreferred response"}

Example:

yaml
datasets:
- path: ./pairs.jsonl
type: preference
- path: "org/hf-preference-dataset"
type: preference
split: train
chosen_field: preferred
rejected_field: dispreferred

Direct Preference Optimization (the surogate dpo command). Offline: a static set of {prompt, chosen, rejected} pairs (type: preference) with the frozen reference model evaluated inline, with no reward model and no rollouts. See Training Modes and Quickstart: DPO.

Configured under a nested loss: block:

OptionTypeDefaultDescription
type#string"dpo"Loss type. Must be "dpo".
dpo_beta#float0.1KL temperature β. The implicit reward is β · (logπθ − logπref); higher β pushes harder from the reference.
length_norm#boolfalseDivide each response’s log-prob sum by its length (SimPO-style). Leave off for minimal/equal-length pairs.
span_mask#boolfalseScore only the disjoint token spans that differ; rows without surviving edits on both sides are dropped.
reference_free#boolfalseOptimize the chosen/rejected likelihood gap directly and skip the frozen-reference forward.
target_margin#float0.0Non-negative beta-scaled target gap for reference-free training. Requires reference_free: true.

Example:

yaml
loss:
type: dpo
dpo_beta: 0.1
length_norm: false
span_mask: false
reference_free: false
target_margin: 0.0
datasets:
- path: ./pairs.jsonl
type: preference

DPO inherits all LoRA, recipe, optimizer, checkpoint-resume, retention, and training-loop settings from the SFT config. gradient_dtype and the LoRA dtype default to FP32; the frozen base does not require an FP32 master copy. CUDA graphs are disabled because the native DPO step is not graph-captured.

Online reinforcement learning (the surogate grpo, grpo-colocate, and grpo-train commands). GRPOTrainConfig extends the SFT config, so every model, LoRA, QLoRA, recipe, optimizer, checkpoint, and runtime option above applies unchanged. Data comes from the orchestrator over the transport rather than from datasets, which is forced empty. See the RL Training guide and Quickstart: GRPO.

OptionTypeDefaultDescription
transport_type#string"filesystem"How training batches arrive from the orchestrator: filesystem or zmq.
weight_broadcast_type#string"filesystem"How updated weights reach the inference server: filesystem (disk), nccl (GPU broadcast), or colocate (zero-copy shared memory).
max_async_level#int1How many steps the orchestrator may run ahead of the trainer. 1 is one step of off-policy staleness.
pad_to_multiple_of#int1Padding multiple for packed micro-batches.
doc_masking#booltrueDocument-level masking so packed samples cannot see each other: attention, and the convolution and recurrent state of linear-attention (Gated DeltaNet) layers.
single_sample_bins#boolfalsePack one sample per row instead of filling each row. Chunked-training attention has no packed-doc isolation, so multi-sample rows would let samples attend across each other.
turn_diagnostics#boolfalseRoute the micro-step through the Python loss instead of the fused native step so per-token logprobs are visible. Same gradients, slower — measurement only.
broadcast_dtype#string"bf16"dtype of the LoRA adapter in weight broadcasts: bf16 rounds FP32 masters (lora_dtype: fp32) to BF16, the copy a BF16 serving engine loads, at half the bytes; master writes them as stored. Checkpoints keep full precision.
minibatches#int1dispatch-PP only: optimizer updates per rollout batch. The rows are partitioned into this many mini-batches of whole GRPO groups (TrainingSample.group_idx), or whole trials without one, seeded per step; each gets its own log-prob pass, backward and update, normalized by its own trial count (gspo) or loss tokens. Adam’s step index of update k is minibatches * step + k.
lora_fp32_forward#boolfalseThe forward computes its LoRA products from the FP32 masters (lora_dtype: fp32), not their BF16 work copies, so the policy moves with the learning rate instead of in BF16 rounding jumps: routed experts and dense LoRA (the shared expert). The backward keeps the BF16 copies; broadcasts stay BF16. See Precision.
max_policy_lag#intnulldispatch-PP only: drop the samples whose trained tokens were sampled (TrainingSample.completion_versions) by several policy versions or by one older than the step’s by more than this. 0 = on-policy batches only.
teacher_from_base#boolfalsedispatch-PP only: the trainer scores each row with its own base model (the LoRA delta off) and uses those log-probs as the rows’ teacher_logprobs, a KL anchor to the base weighted by loss.teacher_tau that needs no teacher server. One more log-prob pass per dispatch call. Needs loss.teacher_tau > 0.

gradient_dtype defaults to fp32 for GRPO (the per-token gradient is 10-100x smaller than in SFT), while master weights follow the model dtype; precision where it matters comes from lora_dtype, which stays fp32.

OptionTypeDefaultDescription
ipo_mask_low#float0.2Low threshold for masking tokens by probability difference.
ipo_mask_high#float0.2High threshold for masking tokens by probability difference.
adv_tau#float1.0Advantage scaling.
teacher_tau#float0.0Weight on the teacher term for on-policy distillation. 0.0 disables it.
kl_tau#float1e-3KL penalty coefficient. Raise if the policy diverges from the reference too fast.
ratio_clip#float7.389056Hard ceiling on the importance ratio (default e²). Bounds the update when the sampling policy and the trainer policy drift apart — e.g. under periodic merged-weight reloads, where the baseline mismatch is larger than the IPO mask alone can absorb.
variant#string"ipo"ipo (token-level, the masks above), cispo (token-level, no mask, ratio truncated at ratio_clip) or gspo (one ratio per sequence, every sequence weighted equally; parallelism: dispatch_pp only). See GSPO.
seq_clip_low#float3e-4gspo: the sequence ratio’s clip below 1, 1 - seq_clip_low (the paper’s value).
seq_clip_high#float4e-4gspo: the sequence ratio’s clip above 1, 1 + seq_clip_high (the paper’s value).
seq_ratio_old#string"inference"gspo: the ratio’s π_old. inference = the rollout engine’s log-probs; step_start = the trainer’s own, scored once at the weights the step starts from (the paper’s recomputation; needs max_policy_lag: 0); trainer = the trainer’s own at the current parameters, so the ratio is 1 and nothing is clipped.

QeRL noise scheduler (noise_scheduler: block)

Section titled “QeRL noise scheduler (noise_scheduler: block)”
OptionTypeDefaultDescription
enabled#boolfalseAdd Gaussian noise to inference-model RMSNorm weights before rollouts.
sigma_start#float5e-2Initial noise standard deviation.
sigma_end#float5e-4Final noise standard deviation.
num_stages#int10Number of geometric decay intervals between the two.

Keys most often set; see the RL Training guide for the full table.

OptionTypeDefaultDescription
model#string(required)HuggingFace model ID or local path. Must match train.yaml and orch.yaml.
tp / dpint1 / 1GPUs per replica (the engine splits the layers across them) and replicas (one whole model per GPU). At most one of them may exceed 1.
max_model_len#intnullMaximum context length.
max_num_seqs#intnullCap on concurrent sequences. Sizes the CUDA-graph and activation buffers, so it is the knob that decides whether a large model plus LoRA fits. null uses the engine’s default.
kv_cache_dtype#stringnullKV cache dtype. fp8 halves KV bytes per token and raises sustainable concurrency, at the cost of perturbing sampled logprobs — watch mismatch_kl. null uses the engine’s default.
enable_lora#booltrueEnable LoRA hot-reload, which is how the trainer’s adapter reaches the server.
max_lora_rank#intnullLargest adapter rank the server accepts.

resume_from_checkpoint (default true) and checkpoint_dir behave as they do for SFT: re-running grpo-train picks up the latest checkpoint instead of starting over. A checkpoint at step S means “trained through batch S”, so the resumed run starts at S + 1. That single resume point drives which batch is packed, which batch is read from the transport, the LR schedule position, the save cadence, and the step number weights are broadcast under. An orchestrator already waiting on the step-S broadcast is therefore unblocked instead of falling out of sync. Set resume_from_checkpoint: false to force a fresh run.

adapter_path is honored by GRPO: the adapter is applied before weight import (adapter_init_mode: merge) or loaded as the initial trainable adapter (adapter_init_mode: trainable), matching the SFT trainer.

OptionTypeDefaultDescription
lmhead_chunks#int1Split LM-head computation into N chunks to reduce logit tensor size by factor of N.
attn_bwd_chunks#int1Split attention backward pass into N chunks to save workspace memory.
long_context#boolfalseTile dense SwiGLU MLPs during forward and backward, plus GLM’s routed/shared experts in resident BF16 training with ep_size: 1. Bounds wide intermediates by the tile size; routing and residual buffers remain proportional to context. Requires lora_dropout: 0; eligible surrounding ops can still use CUDA graphs. See long context.
init_projections_to_zero#boolfalseInitialize projection weights (FFN down and attention out) to zero. Only used when training from scratch.
OptionTypeDefaultDescription
lora#booltrueWhether to use LoRA adapters for training.
lora_rank#int16Rank for LoRA adapters.
lora_alpha#int32Alpha value for LoRA adapters.
lora_dropout#float0.05Dropout rate for LoRA adapters.
lora_dtype#string"fp32"Data type for LoRA adapters: "bf16" or "fp32".
lora_fp32_forward#boolfalseThe forward computes its LoRA products from the FP32 masters (lora_dtype: fp32), not their BF16 work copies. Fine-tuning and GRPO alike.
lora_target_modules#list["all"]List of module names to apply LoRA adapters to.
train_router#boolfalseTrain MoE router gate during LoRA fine-tuning. Only applies to MoE models.
adapter_path#stringnullPath to a PEFT adapter directory to merge into base weights before training. Requires lora: true. Not supported with pre-quantized models.
adapter_init_mode#string"merge"How adapter_path is applied: merge folds it into the base weights and trains a fresh adapter; trainable loads it as the initial trainable adapter and continues training it. Honored by SFT, DPO, and GRPO.
merge_adapter#boolfalseWhether to merge LoRA adapters into the base model after training.

lora_target_modules: ["all"] adapts every linear projection the model declares for LoRA: attention (q_proj, k_proj, v_proj, o_proj), MLP (gate_proj, up_proj, down_proj, or the fused names a model uses) and, on models with Gated DeltaNet linear attention (the Qwen3.5 family, Qwen3.8), the mixer’s in_proj_qkv, in_proj_z, in_proj_a, in_proj_b and out_proj, exported as ...layers.N.linear_attn.<proj> (HF/PEFT names). On such a model out_proj names the linear-attention output projection; the attention output stays o_proj. Adapters trained with all before linear-attention LoRA (surogate <= 1.5.3) cover only [q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj]: load or resume them with that explicit list, since an import that lacks any adapter tensor the trainer allocates is refused (as is optimizer state of another geometry). Serving stacks without linear-attention LoRA support need such adapters merged into the weights.

These settings control the router loss coefficients that balance load across experts during MoE (Mixture-of-Experts) training. The MoE guide covers MoE training end to end.

OptionTypeDefaultDescription
router_aux_loss_coef#floatnullMoE auxiliary (load balancing) loss coefficient. null uses model config default.
router_z_loss_coef#floatnullMoE z-loss (router logit regularization) coefficient. null uses model config default.

Understanding MoE Losses:

  • Auxiliary Loss (aux_loss): encourages balanced load across experts. Higher values spread tokens more evenly but may reduce model capacity. Typical range: 0.001-0.1.
  • Z-Loss (z_loss): keeps router logits from growing too large, which can cause routing collapse. Typical range: 0.0001-0.01.
OptionTypeDefaultDescription
qlora_fp4#boolfalseEnable NVFP4 QLoRA mode (base weights quantized to FP4 E2M1). Requires Blackwell GPU (SM100+).
qlora_fp8#boolfalseEnable FP8 QLoRA mode (base weights quantized to FP8 with per-block scales).
qlora_bnb#boolfalseEnable BitsAndBytes NF4 QLoRA mode (base weights quantized to NF4 with per-block absmax). Works on any CUDA GPU.
qlora_block_size#int128Block size for FP8 QLoRA quantization. Valid values: 64, 128, 256.
qlora_bnb_block_size#int64Block size for BnB NF4 QLoRA quantization. Valid values: 64, 128, 256, 512.
qlora_bnb_double_quant#booltrueEnable double quantization for BnB (quantize absmax values to INT8 for extra memory savings).
qlora_four_over_six#booltrueEnable Four Over Six (4/6) adaptive block scaling for NVFP4 QLoRA quantization. Evaluates both max=4 and max=6 scaling per block and selects lower error option.
qlora_selective_expert_dequant#boolfalseEnable selective expert dequantization for MoE models to reduce dequant buffer memory. When enabled, it only dequantizes the experts that are actually selected by the router for each forward pass, rather than dequantizing all experts.
qlora_offload_experts#boolfalseOffload expert weights in QLoRA MoE models to host memory. Works at the layer level (loads/unloads entire layer’s experts as groups).

These settings control how conversations are formatted for training and inference.

OptionTypeDefaultDescription
use_chat_template#booltrueWhether to use chat template for training.
template#stringautoThe chat template to use. Automatically detected from model if not specified. Available templates defined in CHAT_TEMPLATE_MAPPING.
system#stringnullOverride the default system prompt in the template. Use \n for newlines.
max_length#intnullMaximum length for tokenized conversations. Defaults to sequence_len if not specified.
truncation_strategy#string"delete"How to handle conversations exceeding max_length. Options: "delete" (skip sample), "left" (truncate from start), "right" (truncate from end), "split" (split into multiple samples).
padding_side#string"right"Which side to pad sequences on. Options: "left", "right".
padding_free#boolfalseEnable padding-free training for more efficient packing.
loss_scale#string"default"Loss scaling strategy. Options: "default", or custom scaling configuration.
sequence_parallel_size#int1Sequence parallelism size for distributed training across sequence dimension.
response_prefix#stringnullPrefix to add before model responses during inference. Use \n for newlines.
max_pixels#intnullMaximum number of pixels for vision models (multimodal only).
norm_bbox#stringnullBounding box normalization strategy for vision models. Options: "norm1000", "none", null.
agent_template#stringnullTemplate for agent-style conversations (advanced usage).
OptionTypeDefaultDescription
report_to#listnullReport results and logs to specified platforms. Options: "wandb", "aim".
log_file#stringnullWhere to save the training log. If null, no log file is written.
log_gpu_util#int100Interval for logging GPU utilization.
OptionTypeDefaultDescription
wandb_project#stringnullWandB project name for logging.
wandb_name#stringrun_nameWandB run name for logging. Defaults to the value of run_name.
OptionTypeDefaultDescription
aim_experiment#stringnullAim experiment name for logging.
aim_repo#stringnullAim repository path for logging. Uses default if not specified.
aim_name#stringrun_nameAim run name for logging. Defaults to the value of run_name.
OptionTypeDefaultDescription
debug_time_breakdown#boolfalseEnable detailed training timing breakdown for debugging.
debug_memory_breakdown#boolfalsePrint detailed memory breakdown after model allocation (useful for QLoRA optimization).

These options add automatic training monitoring, early stopping and compute-optimal adjustments. All are off by default and safe to turn on: they only add diagnostics or automation on top of the normal training loop.

OptionTypeDefaultDescription
auto_lr_reduction#boolfalseDetect loss spikes and gradient explosions, then permanently reduce the learning rate. Monitors a rolling window of loss/grad-norm values; when an anomaly is detected (loss > mean + 3σ, or grad_norm > 10× average), the LR schedule is scaled down by 50%. Up to 5 reductions.
early_stop#boolfalseMulti-criteria early stopping. Stops training when ANY of: (1) convergence score > 0.85 for 5 consecutive evals, (2) compute efficiency (loss reduction per FLOP) drops below 50% of peak, (3) training diverges for 200+ consecutive steps, (4) loss plateaus for 500+ consecutive steps. Uses the 6N approximation for FLOPs/token.
epoch_adjustment#boolfalseAutomatically adjust num_epochs to match the Chinchilla-optimal token budget (20× model parameters). If the dataset is smaller than the budget, increases epochs; if larger, decreases them. Only applies when max_steps is not explicitly set.

Always-on diagnostics (no config flag required):

  • Plateau detection: warns when training loss stops improving over a rolling window. It takes no action on its own.
  • Phase detection: classifies training into WARMUP / CONVERGING / PLATEAU / UNSTABLE / DIVERGING phases. Transitions are logged, and the current phase appears in the step log.
  • Chinchilla token budget: printed at training start. It shows the Chinchilla-optimal token count (20 × params) next to the planned tokens, so you can see whether you are training long enough.
RecipeFormatGPU RequirementUse Case
bf16#BF16 forward/backwardAny CUDA GPUBaseline, maximum compatibility
fp8_hybrid#FP8 E4M3 fwd / E5M2 bwdSM89+ (Ada, Hopper, Blackwell)2x throughput, minimal accuracy loss
nvfp4#FP4 E2M1 with block scalingSM100+ (Blackwell only)Maximum memory efficiency
yaml
# Model
model: Qwen/Qwen3-0.6B
model_type: qwen # auto-detected if not specified
sequence_len: 2048
max_model_len: 2048
torch_dtype: bfloat16 # auto-detected if not specified
# Output
output_dir: ./output
save_steps: 100
save_total_limit: 3
# Training
num_epochs: 3
per_device_train_batch_size: 2
gradient_accumulation_steps: 4
learning_rate: 2e-4
lr_scheduler_type: cosine
warmup_ratio: 0.03
# Dataset
datasets:
# Conversation dataset (most common for fine-tuning)
- path: "mlabonne/FineTome-100k"
type: conversation
messages_field: conversations
split: train
# Or use instruction dataset format
# - path: "yahma/alpaca-cleaned"
# type: instruction
# instruction_field: instruction
# input_field: input
# output_field: output
validation_split_ratio: 0.1
train_seed: 1234
eval_seed: 1234
sample_packing: true
dataloader_num_workers: 4
# Chat Template
use_chat_template: true
template: qwen # auto-detected if not specified
truncation_strategy: delete
padding_side: right
# LoRA
lora: true
lora_rank: 16
lora_alpha: 32
lora_dropout: 0.05
lora_dtype: fp32
# Memory optimization
recompute: true
recipe: bf16
# Hardware
gpus: 1
use_cuda_graphs: true

Next: the CLI reference shows how to run a config like this one, and Precision & Recipes helps you pick a recipe.