Configuration Reference
EngineSurogate EngineThis page lists every configuration option in Surogate, with what it does, its default and the values it accepts.
General Settings
Section titled “General Settings”| Option | Type | Default | Description |
|---|---|---|---|
run_name# | string | auto-generated | A descriptor for the run. If not provided, a unique name is generated automatically. |
apply_recommended_values# | bool | false | Whether to apply recommended configuration values. |
num_epochs# | int | 3 | Total number of training epochs to perform. |
output_dir# | string | "output" | The output directory where the model predictions and checkpoints will be written. |
checkpoint_dir# | string | null | Directory to save checkpoints during training. If None, defaults to output_dir. |
resume_from_checkpoint# | bool | true | Continue from checkpoint. If enabled, uses the latest checkpoint. |
save_steps# | int | 50 | Number of steps between saving checkpoints. |
save_total_limit# | int | 5 | Limit the total amount of checkpoints. Deletes older checkpoints in output_dir. |
from_scratch# | bool | false | Train from scratch (random initialization) instead of fine-tuning a pre-trained model. |
Model Settings
Section titled “Model Settings”| Option | Type | Default | Description |
|---|---|---|---|
model# | string | required | Path or HuggingFace model identifier (e.g., "Qwen/Qwen3-0.6B"). |
model_type# | string | auto-detect | Type of the model group. Automatically detected from model config if not specified. |
sequence_len# | int | 1024 | Maximum sequence length for training. Samples exceeding this length are truncated. |
max_model_len# | int | null | Maximum model length for rope scaling. Automatically detected from model config if not specified. |
rope_scaling# | string | null | Type 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# | string | auto-detect | PyTorch data type for model weights. Options: "bfloat16", "float16", "float32". Automatically detected from model config if not specified. |
Recomputation
Section titled “Recomputation”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.
| Option | Type | Default | Description |
|---|---|---|---|
recompute# | bool | true | Enable activation recomputation. false saves all activations (fastest, most memory). true recomputes intermediates from checkpoints (saves VRAM, small compute overhead). |
qlora_recompute# | bool | true | QLoRA 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).
| Option | Type | Default | Description |
|---|---|---|---|
sequence_chunks# | int | 1 | Process sequence_len as N chunks of sequence_len / N tokens (must divide evenly). 1 = normal dense training. |
CPU-RAM Centric Training
Section titled “CPU-RAM Centric 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).
| Option | Type | Default | Description |
|---|---|---|---|
cpu_training# | bool | false | Enable 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:
| Component | Without cpu_training | With cpu_training |
|---|---|---|
| Model weights | All 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 state | On GPU (8-bit quantized) | On CPU (FP32, unlimited RAM) |
| Activations | Per recompute settings | Same |
| LoRA adapters | On GPU | On 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_expertsinstead. - Mutually exclusive with ZeRO sharding (
zero_level > 1).
Example:
model: Qwen/Qwen3-8Bcpu_training: truelora: truelora_rank: 16per_device_train_batch_size: 2sequence_len: 2048Tuning knobs (environment variables)
Section titled “Tuning knobs (environment variables)”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.
| Variable | Default | Effect |
|---|---|---|
SUROGATE_DISPATCH_PREFETCH_BLOCKS# | 2 | Number 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# | 0 | Keep 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# | unset | Reverts 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# | unset | Restores 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-dependent | Force 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# | unset | NVFP4 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:
| Configuration | s/micro-batch |
|---|---|
| defaults | 7.175 |
PREFETCH_BLOCKS=3 | 7.117 (−0.8%) |
PREFETCH_BLOCKS=3 + RESIDENT_LAYERS=16 | 6.832 (−4.8%) |
PREFETCH_BLOCKS=3 + RESIDENT_LAYERS=20 | 6.748 (−6.0%) |
RESIDENT_LAYERS=24 and above | out 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):
| Configuration | s/micro-batch |
|---|---|
nvfp4 before this work | 9.338 (and OOM’d under cpu_training at all) |
stream_fp4# | 7.151 (−23.4%) |
+ FP4_DERIVE_WT | 6.834 (−26.8%) |
+ RESIDENT_LAYERS=40 | 6.420 (−31.2%) |
RESIDENT_LAYERS=52 and above | out 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.
Offloading Options (Legacy)
Section titled “Offloading Options (Legacy)”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.
| Option | Type | Default | Description |
|---|---|---|---|
offload_residual# | bool | false | Offload residuals (of the FFN block) to pinned host memory. Combined with recompute, total activation memory becomes independent of network depth. |
offload_master# | bool | false | Legacy — use cpu_training instead. Store master weights in pinned host memory. |
offload_quants# | bool | false | Store quantized weights in pinned host memory. Requires persistent_quants. |
offload_optimizer# | bool | false | Legacy — use cpu_training instead. Store optimizer state in pinned host memory. |
offload_grads# | bool | false | Legacy — use cpu_training instead. Offload gradients to pinned host memory. |
persistent_quants# | bool | false | Avoid 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# | bool | false | Legacy — use cpu_training instead. Use ZeroCopy memory access for offloaded optimizer states. |
use_write_combined# | bool | false | Legacy — use cpu_training instead. Use write-combined memory for offloaded tensors. |
Multi-GPU Training (ZeRO) Options
Section titled “Multi-GPU Training (ZeRO) Options”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.
| Option | Type | Default | Description |
|---|---|---|---|
zero_level# | int | 1 | ZeRO redundancy optimization level: 1 = sharded optimizer states (default), 2 = sharded gradients + optimizer states, 3 = sharded weights + gradients + optimizer states. |
shard_weights# | bool | false | Shard model weights across data-parallel processes. Enables more effective offloading and reduces memory consumption. |
shard_gradients# | bool | false | Shard gradients across data-parallel processes. Enables more effective offloading and reduces memory consumption. |
use_all_to_all_reduce# | bool | false | Use all-to-all-based reduce algorithm (combine with memcpy_send_recv). |
memcpy_all_gather# | bool | false | Use memcpy for all-gather operations (threads backend only). Generally gets better bandwidth utilization on PCIe and does not consume SM resources. |
memcpy_send_recv# | bool | false | Use memcpy for send/receive operations (threads backend only). |
Expert Parallelism (MoE) Options
Section titled “Expert Parallelism (MoE) Options”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.
| Option | Type | Default | Description |
|---|---|---|---|
ep_size# | int | 1 | Number of GPUs per expert-parallel group. Must divide gpus and num_experts. 1 disables EP. |
ep_load_balance_threshold# | float | 1.3 | Imbalance 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# | int | 16 | LLEP 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.
| Option | Type | Default | Description |
|---|---|---|---|
parallelism# | str | unset | Set to dispatch_pp to enable Dispatch Pipeline Parallelism (or ddp/unset for the default data-parallel path). |
offload_master# | bool | false | Required for dispatch-PP on models that can’t sit resident: streams the frozen base weights from pinned CPU per block. |
recipe# | str | bf16 | bf16 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).
Multi-Node Distributed Training
Section titled “Multi-Node Distributed Training”Settings for training across several machines with Ray and NCCL. The Multi-Node Training Guide walks through the setup.
| Option | Type | Default | Description |
|---|---|---|---|
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# | int | 1 | Total number of nodes to use for training. Set to > 1 to enable multi-node training. |
distributed.gpus_per_node# | int | 0 | Number of GPUs per node. If 0, uses the value from gpus config parameter. |
distributed.worker_output_dir# | string | null | Base 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:
distributed: ray_address: "auto" num_nodes: 2 gpus_per_node: 8 worker_output_dir: /shared/surogate-dataKnowledge Distillation
Section titled “Knowledge Distillation”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.
| Option | Type | Default | Description |
|---|---|---|---|
distillation.teacher_model# | string | null | Teacher model id or path. Required by distill-capture; ignored at train time. |
distillation.top_k# | int | 32 | Teacher logprobs stored per token. Range [1, 1024]; training validates that sidecars were captured with this exact value. |
distillation.temperature# | float | 1.0 | Distillation temperature τ (> 0). |
distillation.kd_weight# | float | 0.5 | Weight of the KD (KL) term (≥ 0). |
distillation.ce_weight# | float | 1 - kd_weight | Weight of the CE term (≥ 0). Must be set explicitly when kd_weight > 1. |
distillation.teacher_batch_size# | int | 4 | Capture-time only (local backend): windows of sequence_len tokens per teacher forward pass (≥ 1). |
distillation.kd_dir# | string | null | Sidecar 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# | string | null | Capture-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# | int | 8 | Capture-time only: concurrent in-flight API capture requests (≥ 1). |
distillation.teacher_api_timeout# | int | 1200 | Capture-time only: per-request API timeout in seconds (≥ 1). |
Example configuration:
distillation: teacher_model: Qwen/Qwen3-1.7B top_k: 64 temperature: 1.0 kd_weight: 0.5Hardware Settings
Section titled “Hardware Settings”| Option | Type | Default | Description |
|---|---|---|---|
gpus# | int | 1 | Number of GPUs to use for training. Use 0 for all available GPUs. |
use_cuda_graphs# | bool | true | Enable CUDA graphs for performance. |
Mixed Precision & Recipe Options
Section titled “Mixed Precision & Recipe Options”| Option | Type | Default | Description |
|---|---|---|---|
recipe# | string | "bf16" | Mixed precision training recipe. Options: "bf16" (default), "fp8_hybrid", "nvfp4". |
gradient_dtype# | string | null | Dtype for activation gradients / backward matmul policy. Defaults to matmul-dtype. Note: recipes may override backward dtype. |
master_dtype# | string | null | Master weight dtype for optimizer updates (e.g., FP32 for stable full fine-tuning). Defaults to model-dtype. |
use_fused_rope# | bool | false | Use fused RoPE kernel with on-the-fly cos/sin computation (saves memory, reduces bandwidth). |
FP8 Recipe Options
Section titled “FP8 Recipe Options”| Option | Type | Default | Description |
|---|---|---|---|
fp8_amax_history# | int | 16 | FP8 delayed scaling amax history length (for fp8_hybrid recipe). |
fp8_pow2_scales# | bool | false | Under 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# | string | auto | Keep 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. |
FP4/NVFP4 Recipe Options
Section titled “FP4/NVFP4 Recipe Options”| Option | Type | Default | Description |
|---|---|---|---|
fp4_backend# | string | "cutlass" | FP4 matmul backend: "cutlass" (default) or "cudnn" (for nvfp4 recipe). |
Layer Quantization Skip Options
Section titled “Layer Quantization Skip Options”| Option | Type | Default | Description |
|---|---|---|---|
skip_quant_first_layers# | int | 0 | Skip quantization for the first N transformer decoder layers. (embedding layers are always kept in BF16). |
skip_quant_last_layers# | int | 0 | Skip quantization for the last N transformer decoder layers (lm_head layers are always kept in BF16). |
Optimizer Settings
Section titled “Optimizer Settings”| Option | Type | Default | Description |
|---|---|---|---|
optimizer# | string | "adamw_8bit" | Optimizer type. Options: "adamw_8bit" (8-bit AdamW), "normuon" (NorMuon hybrid) |
learning_rate# | float | 2e-4 | The initial learning rate for the optimizer. |
lr_scheduler_type# | string | "linear" | Learning rate schedule function: "linear", "cosine", or "wsd". |
warmup_ratio# | float | 0.0 | Ratio of total training steps used for linear warmup from 0 to learning_rate. |
warmup_steps# | int | 0 | Number of steps for linear warmup. Overrides warmup_ratio if set. |
cooldown_steps# | int | 0 | Number of steps for linear cooldown from learning_rate to final_lr_fraction * learning_rate. |
final_lr_fraction# | float | 0.0 | Final learning rate as a fraction of the initial learning rate. |
weight_decay# | float | 0.1 | Weight decay applied to all layers except bias and LayerNorm weights. |
max_grad_norm# | float | 1.0 | Maximum gradient norm for gradient clipping. 0.0 disables clipping. |
AdamW 8-bit Optimizer Parameters
Section titled “AdamW 8-bit Optimizer Parameters”Used when optimizer: "adamw_8bit" (default).
| Option | Type | Default | Description |
|---|---|---|---|
adamw_beta1# | float | 0.9 | The beta1 parameter for AdamW optimizer. |
adamw_beta2# | float | 0.999 | The beta2 parameter for AdamW optimizer. |
adamw_epsilon# | float | 1e-8 | The epsilon parameter for AdamW optimizer. |
NorMuon Optimizer Parameters
Section titled “NorMuon Optimizer Parameters”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.
| Option | Type | Default | Description |
|---|---|---|---|
normuon_momentum# | float | 0.95 | Momentum coefficient for orthogonalized momentum updates in 2D weight matrices. |
normuon_beta2# | float | 0.95 | Second moment coefficient for variance tracking in NorMuon optimizer. |
normuon_cautious_wd# | bool | true | Enable cautious weight decay that only applies decay when gradient and momentum align. |
Training Loop Settings
Section titled “Training Loop Settings”| Option | Type | Default | Description |
|---|---|---|---|
per_device_train_batch_size# | int | 2 | Batch size per device during training/evaluation. |
gradient_accumulation_steps# | int | 4 | Number of update steps to accumulate gradients before performing backward/update pass. Effective batch size = batch_size × grad_accumulation × num_gpus. |
max_steps# | int | -1 | Total number of training steps. -1 derives from epochs and dataset size. |
eval_steps# | int | 100 | Run evaluation every N optimizer steps. |
train_vision# | bool | null | If 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. |
Dataset Settings
Section titled “Dataset Settings”| Option | Type | Default | Description |
|---|---|---|---|
datasets# | list | null | List of datasets for training. Each dataset should specify path, type, and other dataset-specific options. See Dataset Configuration Options below. |
validation_datasets# | list | null | List 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# | float | 0.1 | Ratio of training data to use for validation if no validation_datasets are provided. Value between 0.0 and 1.0. |
train_seed# | int | 1234 | Random seed for the training dataloader. Controls shuffling and sampling order. |
eval_seed# | int | 1234 | Random seed for the evaluation dataloader. Controls shuffling and sampling order. |
dataloader_num_workers# | int | auto | Number 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# | bool | true | Whether 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# | bool | false | Train-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
Section titled “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_stepsloader calls, so the data-loader position saved in checkpoints, epoch boundaries andSUROGATE_AUDIT_TRAIN_BATCHESaudits 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: withrecipe: bf16a 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.
Dataset Configuration Options
Section titled “Dataset Configuration Options”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.
Base Dataset Options (All Types)
Section titled “Base Dataset Options (All Types)”| Option | Type | Default | Description |
|---|---|---|---|
path# | string | required | HuggingFace dataset repo, s3:// URL, gs:// URL, or path to local file or directory. |
type# | string | required | Dataset type. Options: "text", "instruction", "conversation", "preference" (DPO), "auto" (auto-detect format). |
subset# | string | null | HuggingFace 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# | int | null | Limit the number of samples to use from this dataset. If not specified, uses all available samples. |
Text Dataset Options (type: "text")
Section titled “Text Dataset Options (type: "text")”For pre-training or continued pre-training on raw text data.
| Option | Type | Default | Description |
|---|---|---|---|
text_field# | string | "text" | Name of the column in the dataset that contains the raw text content. |
Example:
datasets: - path: "HuggingFaceFW/fineweb-edu" type: text text_field: text split: train samples: 100000Instruction Dataset Options (type: "instruction")
Section titled “Instruction Dataset Options (type: "instruction")”For instruction-following datasets with system/instruction/input/output format.
| Option | Type | Default | Description |
|---|---|---|---|
instruction_field# | string | required | Name of the column containing the instruction/question. |
output_field# | string | required | Name of the column containing the expected output/answer. |
input_field# | string | null | Name of the column containing additional input context (optional). |
system_prompt_type# | string | null | How to provide system prompt. Options: "field" (from dataset column), "fixed" (same for all samples), null. |
system_prompt_field# | string | null | Name of the column containing system prompts (required when system_prompt_type: "field"). |
system_prompt# | string | null | Fixed system prompt text to use for all samples (required when system_prompt_type: "fixed"). |
prompt_format# | string | null | Custom prompt format template. Use {system}, {instruction}, {input}, {output} as placeholders. |
prompt_format_no_input# | string | null | Custom prompt format when no input field. Use {system}, {instruction}, {output} as placeholders. |
Example:
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.
| Option | Type | Default | Description |
|---|---|---|---|
messages_field# | string | "messages" | Name of the column containing the list of conversation messages. |
system_field# | string | null | Name of the column containing the system prompt for the conversation (optional). |
tools_field# | string | null | Name 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:
datasets: - path: "HuggingFaceH4/ultrachat_200k" type: conversation messages_field: messages split: train_sftPreference 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.
| Option | Type | Default | Description |
|---|---|---|---|
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. |
{"prompt": "...", "chosen": "preferred response", "rejected": "dispreferred response"}Example:
datasets: - path: ./pairs.jsonl type: preference - path: "org/hf-preference-dataset" type: preference split: train chosen_field: preferred rejected_field: dispreferredDPO Settings
Section titled “DPO Settings”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:
| Option | Type | Default | Description |
|---|---|---|---|
type# | string | "dpo" | Loss type. Must be "dpo". |
dpo_beta# | float | 0.1 | KL temperature β. The implicit reward is β · (logπθ − logπref); higher β pushes harder from the reference. |
length_norm# | bool | false | Divide each response’s log-prob sum by its length (SimPO-style). Leave off for minimal/equal-length pairs. |
span_mask# | bool | false | Score only the disjoint token spans that differ; rows without surviving edits on both sides are dropped. |
reference_free# | bool | false | Optimize the chosen/rejected likelihood gap directly and skip the frozen-reference forward. |
target_margin# | float | 0.0 | Non-negative beta-scaled target gap for reference-free training. Requires reference_free: true. |
Example:
loss: type: dpo dpo_beta: 0.1 length_norm: false span_mask: false reference_free: false target_margin: 0.0datasets: - path: ./pairs.jsonl type: preferenceDPO 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.
GRPO (RL) Settings
Section titled “GRPO (RL) Settings”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.
Trainer config (train.yaml)
Section titled “Trainer config (train.yaml)”| Option | Type | Default | Description |
|---|---|---|---|
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# | int | 1 | How many steps the orchestrator may run ahead of the trainer. 1 is one step of off-policy staleness. |
pad_to_multiple_of# | int | 1 | Padding multiple for packed micro-batches. |
doc_masking# | bool | true | Document-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# | bool | false | Pack 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# | bool | false | Route 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# | int | 1 | dispatch-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# | bool | false | The 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# | int | null | dispatch-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# | bool | false | dispatch-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.
GRPO loss (loss: block in train.yaml)
Section titled “GRPO loss (loss: block in train.yaml)”| Option | Type | Default | Description |
|---|---|---|---|
ipo_mask_low# | float | 0.2 | Low threshold for masking tokens by probability difference. |
ipo_mask_high# | float | 0.2 | High threshold for masking tokens by probability difference. |
adv_tau# | float | 1.0 | Advantage scaling. |
teacher_tau# | float | 0.0 | Weight on the teacher term for on-policy distillation. 0.0 disables it. |
kl_tau# | float | 1e-3 | KL penalty coefficient. Raise if the policy diverges from the reference too fast. |
ratio_clip# | float | 7.389056 | Hard 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# | float | 3e-4 | gspo: the sequence ratio’s clip below 1, 1 - seq_clip_low (the paper’s value). |
seq_clip_high# | float | 4e-4 | gspo: 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)”| Option | Type | Default | Description |
|---|---|---|---|
enabled# | bool | false | Add Gaussian noise to inference-model RMSNorm weights before rollouts. |
sigma_start# | float | 5e-2 | Initial noise standard deviation. |
sigma_end# | float | 5e-4 | Final noise standard deviation. |
num_stages# | int | 10 | Number of geometric decay intervals between the two. |
Inference server config (infer.yaml)
Section titled “Inference server config (infer.yaml)”Keys most often set; see the RL Training guide for the full table.
| Option | Type | Default | Description |
|---|---|---|---|
model# | string | (required) | HuggingFace model ID or local path. Must match train.yaml and orch.yaml. |
tp / dp | int | 1 / 1 | GPUs 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# | int | null | Maximum context length. |
max_num_seqs# | int | null | Cap 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# | string | null | KV 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# | bool | true | Enable LoRA hot-reload, which is how the trainer’s adapter reaches the server. |
max_lora_rank# | int | null | Largest adapter rank the server accepts. |
Checkpoint resume
Section titled “Checkpoint resume”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.
Memory Optimization Settings
Section titled “Memory Optimization Settings”| Option | Type | Default | Description |
|---|---|---|---|
lmhead_chunks# | int | 1 | Split LM-head computation into N chunks to reduce logit tensor size by factor of N. |
attn_bwd_chunks# | int | 1 | Split attention backward pass into N chunks to save workspace memory. |
long_context# | bool | false | Tile 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# | bool | false | Initialize projection weights (FFN down and attention out) to zero. Only used when training from scratch. |
LoRA Settings
Section titled “LoRA Settings”| Option | Type | Default | Description |
|---|---|---|---|
lora# | bool | true | Whether to use LoRA adapters for training. |
lora_rank# | int | 16 | Rank for LoRA adapters. |
lora_alpha# | int | 32 | Alpha value for LoRA adapters. |
lora_dropout# | float | 0.05 | Dropout rate for LoRA adapters. |
lora_dtype# | string | "fp32" | Data type for LoRA adapters: "bf16" or "fp32". |
lora_fp32_forward# | bool | false | The 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# | bool | false | Train MoE router gate during LoRA fine-tuning. Only applies to MoE models. |
adapter_path# | string | null | Path 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# | bool | false | Whether 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.
MoE Settings
Section titled “MoE Settings”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.
| Option | Type | Default | Description |
|---|---|---|---|
router_aux_loss_coef# | float | null | MoE auxiliary (load balancing) loss coefficient. null uses model config default. |
router_z_loss_coef# | float | null | MoE 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.
QLoRA Settings
Section titled “QLoRA Settings”| Option | Type | Default | Description |
|---|---|---|---|
qlora_fp4# | bool | false | Enable NVFP4 QLoRA mode (base weights quantized to FP4 E2M1). Requires Blackwell GPU (SM100+). |
qlora_fp8# | bool | false | Enable FP8 QLoRA mode (base weights quantized to FP8 with per-block scales). |
qlora_bnb# | bool | false | Enable BitsAndBytes NF4 QLoRA mode (base weights quantized to NF4 with per-block absmax). Works on any CUDA GPU. |
qlora_block_size# | int | 128 | Block size for FP8 QLoRA quantization. Valid values: 64, 128, 256. |
qlora_bnb_block_size# | int | 64 | Block size for BnB NF4 QLoRA quantization. Valid values: 64, 128, 256, 512. |
qlora_bnb_double_quant# | bool | true | Enable double quantization for BnB (quantize absmax values to INT8 for extra memory savings). |
qlora_four_over_six# | bool | true | Enable 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# | bool | false | Enable 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# | bool | false | Offload expert weights in QLoRA MoE models to host memory. Works at the layer level (loads/unloads entire layer’s experts as groups). |
Chat Template Settings
Section titled “Chat Template Settings”These settings control how conversations are formatted for training and inference.
| Option | Type | Default | Description |
|---|---|---|---|
use_chat_template# | bool | true | Whether to use chat template for training. |
template# | string | auto | The chat template to use. Automatically detected from model if not specified. Available templates defined in CHAT_TEMPLATE_MAPPING. |
system# | string | null | Override the default system prompt in the template. Use \n for newlines. |
max_length# | int | null | Maximum 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# | bool | false | Enable padding-free training for more efficient packing. |
loss_scale# | string | "default" | Loss scaling strategy. Options: "default", or custom scaling configuration. |
sequence_parallel_size# | int | 1 | Sequence parallelism size for distributed training across sequence dimension. |
response_prefix# | string | null | Prefix to add before model responses during inference. Use \n for newlines. |
max_pixels# | int | null | Maximum number of pixels for vision models (multimodal only). |
norm_bbox# | string | null | Bounding box normalization strategy for vision models. Options: "norm1000", "none", null. |
agent_template# | string | null | Template for agent-style conversations (advanced usage). |
Logging & Reporting
Section titled “Logging & Reporting”| Option | Type | Default | Description |
|---|---|---|---|
report_to# | list | null | Report results and logs to specified platforms. Options: "wandb", "aim". |
log_file# | string | null | Where to save the training log. If null, no log file is written. |
log_gpu_util# | int | 100 | Interval for logging GPU utilization. |
WandB (Weights & Biases) Settings
Section titled “WandB (Weights & Biases) Settings”| Option | Type | Default | Description |
|---|---|---|---|
wandb_project# | string | null | WandB project name for logging. |
wandb_name# | string | run_name | WandB run name for logging. Defaults to the value of run_name. |
Aim Settings
Section titled “Aim Settings”| Option | Type | Default | Description |
|---|---|---|---|
aim_experiment# | string | null | Aim experiment name for logging. |
aim_repo# | string | null | Aim repository path for logging. Uses default if not specified. |
aim_name# | string | run_name | Aim run name for logging. Defaults to the value of run_name. |
Debugging Options
Section titled “Debugging Options”| Option | Type | Default | Description |
|---|---|---|---|
debug_time_breakdown# | bool | false | Enable detailed training timing breakdown for debugging. |
debug_memory_breakdown# | bool | false | Print detailed memory breakdown after model allocation (useful for QLoRA optimization). |
Training Diagnostics & Automation
Section titled “Training Diagnostics & Automation”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.
| Option | Type | Default | Description |
|---|---|---|---|
auto_lr_reduction# | bool | false | Detect 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# | bool | false | Multi-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# | bool | false | Automatically 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.
Recipe Comparison
Section titled “Recipe Comparison”| Recipe | Format | GPU Requirement | Use Case |
|---|---|---|---|
bf16# | BF16 forward/backward | Any CUDA GPU | Baseline, maximum compatibility |
fp8_hybrid# | FP8 E4M3 fwd / E5M2 bwd | SM89+ (Ada, Hopper, Blackwell) | 2x throughput, minimal accuracy loss |
nvfp4# | FP4 E2M1 with block scaling | SM100+ (Blackwell only) | Maximum memory efficiency |
Example Configuration
Section titled “Example Configuration”# Modelmodel: Qwen/Qwen3-0.6Bmodel_type: qwen # auto-detected if not specifiedsequence_len: 2048max_model_len: 2048torch_dtype: bfloat16 # auto-detected if not specified
# Outputoutput_dir: ./outputsave_steps: 100save_total_limit: 3
# Trainingnum_epochs: 3per_device_train_batch_size: 2gradient_accumulation_steps: 4learning_rate: 2e-4lr_scheduler_type: cosinewarmup_ratio: 0.03
# Datasetdatasets: # 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: outputvalidation_split_ratio: 0.1train_seed: 1234eval_seed: 1234sample_packing: truedataloader_num_workers: 4
# Chat Templateuse_chat_template: truetemplate: qwen # auto-detected if not specifiedtruncation_strategy: deletepadding_side: right
# LoRAlora: truelora_rank: 16lora_alpha: 32lora_dropout: 0.05lora_dtype: fp32
# Memory optimizationrecompute: truerecipe: bf16
# Hardwaregpus: 1use_cuda_graphs: trueNext: the CLI reference shows how to run a config like this one, and
Precision & Recipes helps you pick a recipe.