Skip to Content
MS-SWIFT × TWINKLE
🧩 Interfaces and Components
DOCUMENTATION5.0.0.dev

⌨️ Command-line Arguments

⌨️ Commands

Each command corresponds to a set of Configs, and the command-line arguments are the fields of those Configs. ms-swift parses, validates, and assembles the components.

CommandPurposeFull example
swift ptPretrainingPretraining examples
swift sftInstruction fine-tuning and supervised tasksSFT, Training examples
swift rlPreference learning, online RL, distillationGRPO example, RL examples
swift inferInteractive inference, batch inference, and candidate data synthesisInference examples
swift deployDeploy an OpenAI-compatible interfaceDeployment examples
swift evalModel evaluationEvaluation examples
swift exportModel export and quantizationExport examples
swift mergeMerge LoRAMerge examples

swift rlhf is the compatible command name of swift rl. For installing and starting TrainBench see TrainBench quick start.

The full argument list can be viewed through the help of the corresponding command:

swift pt --help
swift sft --help
swift rl --help
swift infer --help
swift deploy --help
swift eval --help
swift export --help
swift merge --help

🛠️ Argument syntax

  • Pass multiple values to a list, for example --dataset train.jsonl extra.jsonl.
  • Pass booleans explicitly, for example --packing true, --gradient_checkpointing false.
  • Use JSON strings for dictionaries, with shell quotes. Unknown arguments are rejected, not silently ignored.
--columns '{"question":"query","answer":"response"}'
--model_kwargs '{"trust_remote_code":true}'
  • Arguments marked with 🔥 are important arguments
  • Arguments marked with "[v5]" are newly introduced in v5 and have no counterpart in older versions. For renamed or merged arguments see Quick migration to v5.
  • The defaults below are the declared values of the Config. Fields that say "automatic" are derived from the model, the task, or the execution environment.
  • swift infer/deploy/eval/export/merge restore the model, template, and quantization settings by default from args.json in the --model and --adapters directories. See load_args.

Arguments can also be put into a YAML or JSON file and passed to the command:

model: Qwen/Qwen3.5-4B
model_type: qwen3_5
template: qwen3_5
torch_dtype: bfloat16
attn_impl: flash_attention_2
dataset:
  - swift/self-cognition#600
tuner: lora
num_train_epochs: 3
output_dir: output/sft
ENV:
  MAX_PIXELS: '1003520'

Save it as sft.yaml and run swift sft sft.yaml. The ENV section is written into environment variables (existing environment variables take precedence). yaml/json and the command line can be mixed: put arguments that rarely change in the yaml and arguments that change often on the command line.

⚙️ Model arguments

model

model id or local model path. Default: None. With --mode remote, fill in the model name provided by the server.

model_type

model type. Models with the same architecture, model loading process, and template definition share one model_type. Default: None, selected automatically from the suffix of --model and the architectures in config.json.

Note: this model_type is different from the model_type in config.json.

model_revision

model version. Default: None.

task_type

task type. Options are causal_lm, seq_cls, embedding, reranker, generative_reranker, decision. Default: None, selected automatically from the model.

If set to seq_cls, --num_labels and --problem_type usually need to be set as well.

torch_dtype

data type of the model weights. Supports bfloat16, float16, float32. Default: None, read from config.json.

attn_impl

attention implementation. Options include sdpa, eager, flash_attention_2, flash_attention_3, etc. Default: None, read from config.json.

Note: the available implementations depend on the model and the hardware.

vit_attn_impl

attention implementation of the vision tower of a multimodal model. It can differ from the language tower. Default: None.

experts_impl

expert implementation type of an MoE model. Options are grouped_mm, batched_mm, eager. Default: None.

enable_kernel

whether to enable twinkle kernel optimizations. At model build time, twinkle's kernelize() is called to replace the operator implementations it supports. Default: False.

new_special_tokens

special tokens to add. Default: [].

num_labels

number of labels of a classification task (--task_type seq_cls). Default: None.

problem_type

problem type of a classification task (--task_type seq_cls). Options are regression, single_label_classification, multi_label_classification. Default: None, which means regression for a reward model or when num_labels is 1, and single_label_classification otherwise.

rope_scaling

rope type. Pass a string (linear, dynamic, yarn) together with max_model_len to set it automatically, or pass a json string (for example '{"factor":2.0, "type":"yarn"}') to override rope_scaling in config.json directly. Default: None.

max_model_len

the factor multiple used to compute rope when a rope_scaling string is passed. Default: None. When not None it overrides max_position_embeddings in config.json.

max_memory

maximum GPU memory per device when weights are placed by device_map, for example '{0: "20GB", 1: "20GB"}'. Passed through to from_pretrained. Default: None.

local_repo_path

loading some models depends on a github repo (for example deepseek-vl2). A local repo path can be passed to avoid the network problems of git clone. Default: None.

model_kwargs

extra model loading arguments (json string or json file). Passed through to from_pretrained. Default: None. For the meaning of model-specific arguments (for example '{"fps_max_frames": 12}') see the official repo of the model. Arguments specified at training time should also be set at inference time.

vision_process_kwargsv5

multimodal vision preprocessing arguments (min_pixels, max_pixels, fps, etc.). Keys are the constant names (lowercase) in the model's vision_process module. Takes precedence over the environment variables of the same name. Default: None.

language_model_only

build only the language tower of a multimodal checkpoint, for text-only training. Default: False.

init_strategy

how to initialize all uninitialized parameters when loading a model (for custom model architectures). Options are zero, uniform, normal, xavier_uniform, xavier_normal, kaiming_uniform, kaiming_normal, orthogonal. Default: None.

mtp_num_layers

number of MTP (multi-token prediction) layers of Megatron, read from the checkpoint. If not set, MTP weights are dropped at load time. Default: None.

mtp_loss_scaling_factor

MTP loss weight (mcore 0.1, RL commonly 0.2). Read only with enable_mtp_training. Default: None.

enable_mtp_trainingv5

whether to train the MTP head together with the main model. One extra transformer layer and a full-vocabulary projection are added at each depth. Default: False.

mtp_freezev5

exclude the MTP head from the optimizer (it is kept at export, produces no Adam state, and is not affected by weight decay). Default: False.

mtp_decoder_input_detach

cut off the MTP gradient at the main hidden states, so that only the MTP head is trained and the policy model is not affected. Safer for RL. Default: False.

mtp_allow_random_init

allow training the MTP head with random initialization when the base model has no MTP weights. Default: False.

mtp_shared_weights

the output weights of the MTP head are shared with the main output embedding. Default: False.

fp4_format

Megatron FP4 training format. Only e2m1. Requires Blackwell and TransformerEngine>=2.7. Default: None.

fp4_recipe

FP4 scaling scheme. Only nvfp4. Default: nvfp4.

fp4_param_gather

parameters are also stored in FP4 and all-gathered in FP4. Requires fp4_format and the distributed optimizer. Default: False.

fp8_format

Megatron FP8 training format. e4m3 throughout, or hybrid (e4m3 forward, e5m2 backward). Mutually exclusive with FP4. Default: None.

fp8_recipe

FP8 scaling scheme. Options are tensorwise, delayed (amax history), blockwise (DeepSeek FP8 checkpoint), mxfp8 (Blackwell only). Default: delayed.

fp8_param_gather

parameters are stored in FP8 and all-gathered in FP8. Requires the distributed optimizer. Default: False.

fp8_amax_history_len

length of the amax history of the delayed scheme. Default: 1024.

fp8_amax_compute_algo

how amax is computed. Options are most_recent, max. Default: max.

⚙️ Data arguments

dataset

list of dataset ids or paths. Default: []. The format of each dataset is '<dataset id or path>:<subset>#<sample count>', where the subset and the sample count are optional. Local datasets support jsonl, csv, json, folders, etc. Open-source datasets on the hub can be git cloned locally and used offline. For custom dataset formats see Custom datasets.

Subset: takes effect only when the dataset is an id or a folder. Default: the single subset specified at registration, otherwise default. Use / to select several (id:subset1/subset2), and all to select all of them.

Sample count: the full dataset is used by default. <path>#1000 means sampling 1000 rows. When the sample count is smaller than the total number of samples, sampling is random without replacement. When it is larger, the data is repeated in whole multiples of 采样数//样本总数 plus extra random sampling. Streaming datasets are only sampled sequentially. With --dataset_shuffle false, non-streaming datasets are also sampled sequentially.

val_dataset

list of validation set ids or paths. Default: [].

cached_dataset

list of paths to cached dataset folders produced by swift export --to_cached_dataset true, to avoid tokenize taking up GPU time. Default: [].

Tip: the cache only stores the extra length field and filters out samples that would raise errors. The actual preprocessing runs synchronously during training. --truncation_strategy split stores input_ids, in which case export and training must set the same max_length and truncation_strategy.

Sampling is supported with the syntax <path>#<sample count>. The training type is distinguished by --template_mode and the task type by --task_type.

cached_val_dataset

list of cached validation set folder paths. Default: [].

split_dataset_ratio

ratio of the validation set split from the training set when val_dataset is not specified. Default: 0.0, that is, no split.

data_seed

dataset random seed. Default: 42.

dataset_num_proc

number of processes for dataset preprocessing. Default: 1.

Tip: a larger value is recommended for text-only models to speed up preprocessing. A large value is not recommended for multimodal models. If CPU utilization is 100% but processing is extremely slow, set OMP_NUM_THREADS.

load_from_cache_file

whether to load the dataset from the cache. Default: False. For real training, True is recommended. Set it to False when debugging. The cache path is controlled by MODELSCOPE_CACHE.

dataset_shuffle

whether to shuffle the dataset. Default: True.

Note: shuffling in CPT/SFT has two parts: the shuffle of the dataset (dataset_shuffle) and the shuffle of the dataloader (train_dataloader_shuffle).

val_dataset_shuffle

whether to shuffle val_dataset. Default: False.

streaming

read and process the dataset in a streaming fashion. Default: False.

Note: the length of a streaming dataset cannot be obtained, so --max_steps must be set.

Note: preprocessing of a streaming dataset runs only on rank0 and is distributed to the other processes. With a large world_size, preprocessing becomes the bottleneck.

interleave_prob

list of sampling probabilities when combining several datasets. When set, interleave_datasets is used. By default concatenate_datasets is used. Does not take effect on --val_dataset. Default: None.

stopping_strategy

stopping strategy of interleave_datasets. Options are first_exhausted, all_exhausted. Default: first_exhausted.

shuffle_buffer_size

shuffle buffer size of a streaming dataset. Effective only when dataset_shuffle is True. Default: 1000.

download_mode

dataset download mode. Options are reuse_dataset_if_exists, force_redownload. Default: reuse_dataset_if_exists. Set it to force_redownload when a hub dataset reports an error.

columns

column mapping, json string, for example '{"text1": "query", "text2": "response"}'. After mapping, the data is handled by AutoPreprocessor. Default: None.

strict

when True, a problematic row raises an error directly. Otherwise the erroneous sample is dropped. Default: False, usually used to troubleshoot errors.

remove_unused_columns

whether to delete the columns of the dataset that are not used. Default: True. When set to False, extra columns are passed to compute_loss, which makes them available to custom loss functions.

disable_auto_column_mapping

turn off automatic column-name mapping (columns still takes effect). Default: False. Automatic mapping rules:

images: image, images. videos: video, videos. audios: audio, audios.

system: system, system_prompt. query: query, prompt, input, instruction, question, problem. response: response, answer, output, targets, target, answer_key, answers, solution, text, completion, content.

model_name

only for the self-cognition task, and only effective for the swift/self-cognition dataset. Replaces {{NAME}}. Pass the Chinese and English names of the model, for example --model_name 小黄 'Xiao Huang'. Default: None.

model_author

only for the self-cognition task, and only effective for the swift/self-cognition dataset. Replaces {{AUTHOR}}. For example --model_author '魔搭' 'ModelScope'. Default: None.

custom_dataset_info

list of json file paths for custom dataset registration. Default: [].

decision_drop_instructions

data augmentation for the decision task. Blank out the instructions text of a sample with this probability. Default: 0.0.

decision_subsample_options

data augmentation for the decision task. Keep only the correct answer and N distractors in a multiple-choice question. Default: 0, no subsampling.

decision_state_as_text

data augmentation for the decision task. Flatten a dict-form state into plain text with this probability. Default: 0.0.

decision_shuffle_fields

data augmentation for the decision task. Randomly shuffle the order of state fields and questions. Default: False.

use_hf

control whether model download, dataset download, and model push use ModelScope or Hugging Face. Default: False, which uses ModelScope.

Tip: to access ModelScope from outside China, set the environment variable MODELSCOPE_DOMAIN='www.modelscope.ai'.

hub_token

hub token. Default: None.

trust_remote_codev5

whether to execute .py scripts inside the repository (dataset script) when loading a dataset. A warning is printed once per dataset. Default: True.

packing

pack samples of different lengths into approximately equal-length samples with padding_free (without splitting complete sequences), so that the load is balanced across nodes and processes. Requires --attn_impl flash_attention_2 to keep the sequences inside a pack invisible to each other. Default: False. Supported for CPT/SFT/DPO/KTO/GKD and embedding/reranker/seq_cls.

Note: packing reduces the number of samples. Adjust the gradient accumulation steps and the learning rate accordingly.

packing_length

length of packing. Default: None, that is, max_length.

packing_num_proc

number of packing processes. Default: 1. Different process counts give different packed datasets. Usually no need to change it.

packing_strategy

packing algorithm. Options are binpack (best-fit-decreasing, reordered by length) and sequential (order-preserving greedy, next-fit). Default: binpack. sequential is recommended together with packing_num_proc=1 to keep the global order.

lazy_tokenize

whether to tokenize only at training time. Default: None, selected automatically.

Default True for multimodal models to save memory

Note: to do image data augmentation, set lazy_tokenize (or streaming) to True and modify the encode method of the Template.

train_dataloader_shuffle

whether the training dataloader shuffles. Default: True. Has no effect on IterableDataset (streaming datasets).

group_by_length

group samples of similar length together to reduce padding, so that the load is balanced across nodes. Default: False.

data_sharding

whether to read the dataset in shards by rank. Default: False. Only effective for Megatron.

dataloader_num_workers

number of worker processes of the dataloader. Default: None, selected automatically.

dataloader_pin_memory

Default: True.

dataloader_persistent_workers

whether to keep worker processes across epochs. Default: True. Automatically False when dataloader_num_workers=0.

dataloader_multiprocessing_context

how worker processes are started. Default: None, which keeps the platform default. spawn is used automatically when packing would deadlock under fork.

dataloader_prefetch_factor

number of batches prefetched by each worker process. Default: None, selected automatically.

dataloader_drop_last

whether to drop the last incomplete batch. Default: False.

📝 Template arguments

These arguments act on encoding and are not sampler configuration. See Template.

template

chat template type. Default: None. The template of the matching model_type is selected automatically.

system

custom system field. A string or a txt file path can be passed. Default: None, which uses the template's default_system.

Note: the system in the dataset has the highest priority, then --system, then the template's default_system.

max_length

maximum number of tokens of a sample after encoding. Longer samples are handled by truncation_strategy. Default: None, that is, the maximum length supported by the model. For PPO, GRPO, GKD, and inference it stands for max_prompt_length.

truncation_strategy

how to handle a sample that exceeds max_length. Options are delete, left, right, split (delete, trim on the left, trim on the right, split into several samples). Default: None, selected automatically.

Note: split only supports text-only pretraining datasets.

Note: when a multimodal model uses left or right, all image_token and other multimodal tokens are kept, which may cause OOM.

max_pixels

maximum number of pixels (H\*W) of a multimodal input image. Larger images are scaled down. Default: None, no limit. Applies to all multimodal models.

agent_template

agent template: how to turn the tools list into a system, how to extract tool calls from the reply, and the format of tool_call/tool_response messages. Options include react_en, hermes, glm4, qwen_en, toolbench, etc. Default: None, selected automatically from the model.

norm_bbox

how bounding-box coordinates are scaled. Options are norm1000 (scale to per-mille coordinates) and none. Default: None, selected automatically from the model.

use_chat_template

use the chat template or the generation template (for pretraining). Default: None, that is, True. swift pt defaults to False.

padding_side

padding direction when batch_size>=2. Options are left, right. Default: right. Inference defaults to left.

padding_free

flatten the data of a batch to avoid padding, which lowers GPU memory and speeds things up (sequences inside a batch are invisible to each other). Default: False.

Note: requires --attn_impl flash_attn. Compared with packing, it needs no preprocessing time, but packing trains faster with more stable GPU memory.

loss_scale

loss weight strategy for training tokens. Default: default. RL defaults to last_round. swift pt defaults to all.

default: all responses (history included) compute loss with weight 1. system/user/multimodal tokens and tool_response compute no loss (SFT default).

last_round: compute loss only on the response of the last round (RL default).

all: compute loss on all tokens (pretraining default).

Other strategies: ignore_empty_think, ignore_think_prefix, agent react/hermes/qwen (tool_call weight 2), etc. They can be mixed with the basic strategy, for example 'last_round+hermes+ignore_empty_think'.

disable_ignore_empty_think

whether to disable the automatic addition of ignore_empty_think for hybrid thinking models. Default: False, that is, it is added automatically so that an empty '<think>\n\n</think>\n\n' does not take part in the loss.

is_binary_loss_scale

when loss_scale is only 0/1, express it with labels (-100) instead. Compatible with liger_kernel. Default: None, set automatically.

sequence_parallel_size

sequence parallel (Ulysses) size. Default: 1.

Tip: local SFT supports FSDP2 + Ulysses SP, for example --mode ray --nproc_per_node 2 --fsdp <config file> --parallel_spec dp1fsdp2ul2 --sequence_parallel_size 2. FSDP and SP share the same set of GPUs and require right padding. packing/padding-free needs a supported FlashAttention backend.

template_backend

template backend. Options are swift and jinja (transformers' apply_chat_template). Default: swift.

Note: the jinja backend only supports inference, not training.

response_prefix

prefix string of the response. Effective only at inference. Default: None, decided by enable_thinking and the template.

enable_thinking

whether to enable thinking mode. Effective only at inference. Default: None, decided by the template (False for hybrid thinking/non-thinking templates, True for thinking templates). When False, the non-thinking prefix is added (for example '<think>\n\n</think>\n\n' for Qwen3-8B). When True, the thinking prefix '<think>\n' is added. Lower priority than response_prefix.

preserve_thinking

whether to keep the thinking content of historical rounds. Default: None: False for thinking models at inference and training, which keeps only the last round. At training time it is True when the basic strategy of loss_scale is not last_round.

add_non_thinking_prefix

whether to add the non-thinking prefix at training time to assistant replies that do not start with '<think>', so that built-in datasets can train hybrid thinking models. Default: True.

⚙️ Fine-tuning arguments

tuner

options are lora, full, trainable_tokens. Default: lora. QLoRA, DoRA, and rsLoRA are switches of LoRA, not separate tuners.

adapters

list of adapter ids/paths. Default: []. Usually used in inference/deployment commands: swift infer --model <model_id_or_path> --adapters <adapter_id_or_path>. Also used to continue training. The difference from resume_from_checkpoint is that it only reads the adapter weights, does not load the optimizer or the random seed, and does not skip the already-trained data.

--model is followed by the full weight directory (containing model.safetensors, tokenizer, config), and --adapters is followed by the incremental adapter directory (containing adapter_model.safetensors).

swift deploy supports --adapters name=path to specify a service name for each adapter.

freeze_llm

only effective for multimodal models. Freeze the LLM in full-parameter training. With LoRA and target_modules of all-linear, no LoRA is added on the LLM. Default: False.

freeze_vit

only effective for multimodal models. Freeze vit in full-parameter training. No LoRA is added with LoRA. Default: True.

Note: vit here also includes audio_tower.

freeze_aligner

only effective for multimodal models. Freeze the aligner (projector) in full-parameter training. No LoRA is added with LoRA. Default: True.

target_modules

modules the tuner attaches to. Default: ['all-linear']. Module suffixes can also be passed, for example --target_modules q_proj k_proj v_proj.

Note: all-linear of an LLM automatically finds all linear layers except lm_head. For multimodal LLMs, the default is to attach only on the LLM, controlled by freeze_llm, freeze_vit, and freeze_aligner.

target_regex

use a regular expression to specify the modules the tuner attaches to. When passed, target_modules is ignored. Default: None.

target_parameters

list of parameter names to replace with LoRA. Similar to target_modules, but takes parameter names. Applies when MoE layers do not use nn.Linear. Requires lora_dropout of 0. Default: None.

modules_to_save

extra original model modules that are trained and saved after the tuner is attached. Default: [], for example --modules_to_save embed_tokens lm_head. The weights are saved in adapter_model.safetensors.

lora_rank

Default: 8.

lora_alpha

Default: 32.

lora_dropout

Default: 0.05.

lora_bias

options are none, all. all means all biases are trainable. Default: none.

use_rslora

whether to use RS-LoRA. Default: False.

use_dora

whether to use DoRA. Default: False.

init_weights

peft's init_lora_weights. Options are true, false, or a strategy name (gaussian, pissa, olora, etc.). loftq and lora-ga are rejected. Default: true.

lorap_lr_ratio

learning rate ratio of LoRA+ (lora_B and embedding). 10~16 is recommended. Default: None, that is, disabled.

lorap_emb_lrv5

learning rate of the embedding in LoRA+. Default: 1e-6.

trainable_token_indicesv5

embedding rows trained by trainable_tokens, a common way to learn new special tokens. Default: None.

⚙️ Training arguments

learning_rate

learning rate. Default: 1e-5. LoRA training usually sets it to 1e-4.

Tip: setting min_lr requires --lr_scheduler cosine_with_min_lr (transformers) or Megatron's min_lr.

lr_scheduler

learning rate scheduler. Resolved by name. An external class or source can also be passed. Common choices are linear, constant, cosine_with_min_lr. Default: cosine.

lr_scheduler_kwargs

other scheduler arguments, json string. Default: None.

warmup_ratio

Default: 0.0.

warmup_steps

Default: 0.

per_device_train_batch_size

Default: 1.

per_device_eval_batch_size

Default: 1.

gradient_accumulation_steps

number of gradient accumulation steps. Default: 1. Derived automatically when Megatron sets global_batch_size.

Tip: in CPT/SFT, gradient accumulation is equivalent to a larger batch_size. In RLHF it is not equivalent.

dynamic_batchingv5

whether twinkle plans micro-batches dynamically by token budget (the update size is still batch_size × DP × gradient accumulation). Default: False.

max_tokens_per_micro_batchv5

token budget of each micro-batch with dynamic batching. Default: None.

packing_algorithmv5

packing algorithm of dynamic batching. Options are ffd, kk. Default: ffd.

micro_batch_orderv5

execution order of the micro-batches produced by dynamic batching. Options are none, descending, ends_small. Default: none.

max_steps

maximum training steps. Must be set for streaming datasets. Default: -1.

num_train_epochs

number of training epochs. Default: 3.0.

max_grad_norm

gradient clipping, shared by both backends. Default: 1.0.

Note: the grad_norm in the log is the value before clipping.

clip_grad

alias of max_grad_norm. Default: None.

gradient_checkpointing

whether to use gradient checkpointing. Significantly lowers GPU memory usage but slows things down. Default: True.

gradient_checkpointing_kwargs

arguments passed to torch.utils.checkpoint, for example '{"use_reentrant": false}'. Default: None.

vit_gradient_checkpointing

whether to enable gradient checkpointing for vit in multimodal models. Default: None.

vit_gradient_checkpointing_kwargs

gradient checkpointing arguments for vit. Default: None.

optim

optimizer of the transformers backend. Default: adamw_torch_fused. For the full list see OptimizerNames of transformers. The Megatron backend uses optimizer.

optim_args

extra arguments passed to the optimizer. Default: None.

weight_decay

weight decay coefficient. Default: 0.1.

adam_beta1

exponential decay rate of Adam's first moment. Default: 0.9.

adam_beta2

exponential decay rate of Adam's second moment. Default: 0.95.

adam_epsilon

Adam's epsilon. Default: 1e-8.

use_galore

whether to use GaLore (full-parameter low-rank gradient projection, transformers backend). Default: False.

galore_target_modules

modules GaLore is applied to. Default: None, that is, attention and mlp.

galore_rank

rank of GaLore. Default: 128.

galore_update_proj_gap

update interval of the decomposition matrix. Default: 50.

galore_scale

matrix weight coefficient. Default: 1.0.

galore_proj_type

GaLore matrix decomposition type. Default: std.

galore_optim_per_parameter

whether to set a separate optimizer for each GaLore target parameter (the transformers backend rejects this argument). Default: False.

galore_with_embedding

whether to apply GaLore to the embedding. Default: False.

galore_quantization

whether to use Q-GaLore. Default: False.

galore_proj_quant

whether to quantize the SVD decomposition matrix. Default: False.

galore_proj_bits

SVD quantization bits. Default: 4.

galore_proj_group_size

SVD quantization group size. Default: 256.

galore_cos_threshold

cos similarity threshold for updating the projection matrix. Default: 0.4.

galore_gamma_proj

coefficient that lengthens the update interval once the projection matrices are similar. Default: 2.

galore_queue_size

queue length for computing the projection matrix similarity. Default: 5.

weight_decay_incr_style

how weight decay changes during training. Options are constant, linear, cosine. Default: constant. Megatron only.

start_weight_decay

starting value of weight decay. Default: None.

end_weight_decay

ending value of weight decay. Default: None.

min_lr

lower bound of the learning rate. cosine schedule plus min_lr is equivalent to cosine_with_min_lr. Default: 0.0. Megatron only.

optimizer

Megatron optimizer. Options are adam, sgd, muon, dist_muon (a sharded muon that can overlap with communication). Default: adam.

muon_momentum

momentum of Muon. Default: 0.9.

muon_split_qkv

orthogonalize q/k/v separately. Default: True. Megatron only.

muon_use_nesterov

whether to use Nesterov momentum. Default: False.

muon_scale_mode

scaling mode of Muon. Options are spectral, unit_rms_norm, shape_scaling. Default: spectral.

muon_fp32_matmul_prec

precision of the Newton-Schulz matmul. Options are low, medium, high. Default: medium. Megatron only.

muon_coefficient_type

coefficient type of Newton-Schulz. Default: quintic.

muon_num_ns_steps

number of Newton-Schulz iterations. The larger, the more precise the orthogonalization. Default: 5.

muon_tp_mode

TP mode of Muon. Options are blockwise (depends on the TP width), duplicated, distributed. Default: blockwise. Megatron only.

muon_extra_scale_factor

extra scaling coefficient of Muon. Default: 1.0.

muon_scalar_optimizer

optimizer that handles the parameters muon does not cover (scalars, bias, norm). Default: adam.

qk_clip_enabledv5

whether to enable QK-Clip (scale the Q/K weights when the attention logit peak exceeds tau, Kimi K2). Default: False. Do not enable it casually on pretrained models. A small tau damages Q/K.

qk_clip_tauv5

upper bound of the attention logit. Default: 10000.0.

sgd_momentum

momentum for optimizer=sgd. Default: 0.9.

use_precision_aware_optimizer

whether to store optimizer state at a precision lower than fp32. Saves GPU memory but may change convergence. Default: False. Megatron only.

main_params_dtype

main parameter precision. Options are fp32, fp16. Default: fp32.

main_grads_dtype

main gradient precision. Options are fp32, bf16. Default: fp32.

exp_avg_dtype

Adam first moment precision. Options are fp32, fp16, bf16, fp8. Default: fp32.

exp_avg_sq_dtype

Adam second moment precision. Options are fp32, fp16, bf16, fp8. Default: fp32.

accumulate_allreduce_grads_in_fp32

all-reduce gradients in fp32 during bf16 training. Consumes bandwidth but removes drift. Default: False.

optimizer_cpu_offload

put optimizer state in host memory and move it per step. Default: False.

optimizer_offload_fraction

fraction offloaded to the host. Default: 1.0.

optimizer_cuda_graph

capture the optimizer step with a CUDA graph. Requires fixed shapes. Default: False.

global_batch_size

number of samples per Megatron step, from which the gradient accumulation steps are derived. Must be divisible by per_device_train_batch_size × DP. Default: None.

eval_iters

number of iterations per evaluation. Default: -1, that is, the whole validation set.

microbatch_group_size_per_vp_stage

number of micro-batches grouped within a virtual pipeline stage. Default: None, chosen by Megatron.

lr_decay_style

Megatron learning rate decay style. Options are constant, linear, cosine, inverse-square-root, WSD. Default: cosine. Derived from lr_scheduler when not passed explicitly.

lr_decay_iters

number of decay iterations. Default: None, that is, the whole training process.

lr_warmup_init

starting learning rate of warmup. Default: 0.0.

lr_wsd_decay_iters

number of iterations of the WSD decay segment. Read only with lr_decay_style=WSD. Default: None.

lr_wsd_decay_style

style of the WSD decay segment. Options are exponential, linear, cosine, minus_sqrt. Default: exponential.

seed

global random seed. Default: 42.

Note: does not affect data_seed, which controls the dataset shuffle, and vice versa.

full_determinism

make training results reproducible. Lowers performance. Default: False.

use_liger_kernel

whether to enable Liger kernels to speed up training and reduce GPU memory. Default: False.

Note: liger_kernel does not support device_map and only supports task_type='causal_lm'.

neftune_noise_alpha

noise coefficient of neftune. Default: 0. It can usually be set to 5, 10, or 15.

dp_balancev5

whether to reorder the batch after rollout and the forwards of ref/teacher/old-logps, so that the load is balanced across DP ranks (online RL, distillation, RFT). Default: True.

router_aux_loss_coef

weight of aux_loss in MoE training. Default: 0.0.

enable_dft_loss

whether to use DFT loss in SFT. Default: False.

enable_channel_loss

enable channel loss. Loss is aggregated by the channel field of the dataset (rows without that field fall into the default channel). Compatible with packing/padding_free/loss_scale. Default: False.

loss

supervised loss name. Effective for pretraining/SFT, embedding, reranker, and decision tasks. Takes the built-in name of each task or a custom loss name registered with @register_loss. For built-in names and how to write custom ones see Plugins. Default: None, which uses the default loss of each task.

mrl_dims

MRL dimension configuration for embedding training. Keys are truncated embedding dimensions and values are loss weights, for example '{"32": 1.0, "64": 1.0, "128": 1.0}'. Keys above hidden_size are ignored. Effective only with task_type='embedding'. Default: None.

acc_strategy

level at which acc is computed during training and validation. Options are token, seq. Default: token.

vit_lr

learning rate of vit in multimodal models. Default: None, equal to learning_rate. Usually used together with --freeze_vit and --freeze_aligner.

Tip: the learning_rate in the log is the learning rate of param_groups[0]. The order of param_groups is vit, aligner, llm.

aligner_lr

learning rate of the aligner in multimodal models. Default: None, equal to learning_rate.

param_groups_pluginsv5

extra param_groups plugins, appended after the built-in groups (vit/aligner/llm, LoRA+). Default: [].

freeze_parameters

prefixes of parameters to freeze. Default: []. Full-parameter training only.

freeze_parameters_regex

regex of parameters to freeze. Default: None.

freeze_parameters_ratio

fraction of parameters frozen from the bottom up. Default: 0. It can be set to 1 to freeze everything and then turn some parameters back on with trainable_parameters.

trainable_parameters

prefixes of extra trainable parameters. Default: [].

trainable_parameters_regex

regex of extra trainable parameters. Default: None.

Note: trainable_parameters and trainable_parameters_regex take precedence over freeze_parameters, freeze_parameters_regex, and freeze_parameters_ratio.

tf32

whether to allow matmul/conv to use tf32. Default: None, which keeps the torch default.

torch_empty_cache_steps

how many steps between emptying the CUDA cache, to relieve GPU memory fragmentation. Default: None.

label_smoothing_factor

label smoothing coefficient. 0 turns it off. Default: 0.0.

calculate_per_token_loss

whether to average over the real token count of the whole global batch (instead of per micro-batch). Affects packing/padding_free. Default: None, which takes the Megatron default.

apply_wd_to_qk_layernorm

whether to apply weight decay to the q/k layernorm parameters as well. Default: False.

liger_kernel_config

kernel switches passed to liger, json object. Default: None.

eval_strategy

evaluation strategy during training. Default: None, which follows save_strategy, and is no when there is no validation set.

eval_steps

evaluation interval, an integer or a ratio in (0, 1). Default: None, which follows save_steps.

eval_on_start

evaluate once before training to make sure the evaluation pipeline works. Default: False.

eval_delay

number of leading steps (or epochs) for which evaluation is skipped. Default: 0.

load_best_model_at_end

reload the best checkpoint at the end of training. Default: False.

metric_for_best_model

metric of the best model. Default: None: loss when predict_with_generate is False, otherwise rouge-l (reward for GRPO).

greater_is_better

whether a larger metric is better. Default: None, False when the metric contains loss, True otherwise.

predict_with_generate

use generation at validation time. Default: False.

eval_dataset

dataset for evaluation during training. Default: [].

eval_dataset_args

evaluation dataset arguments, json string. Default: None.

eval_limit

sample count of the evaluation dataset. Default: None.

eval_generation_config

generation configuration at evaluation time, json string. Default: None.

extra_eval_args

extra evaluation arguments, json string. Default: None.

eval_sampler_backendv5

engine used by predict_with_generate. Options are transformers (in-process), vllm, sglang (deploy an engine on the same GPUs and sync weights, ray mode only). Default: transformers.

early_stop_interval

early stopping interval. Training stops when metric_for_best_model does not improve over this many periods (based on save_steps). Default: None.

callbacks

names of custom trainer callbacks. Default: [].

⚙️ Distributed arguments

mode

how to run. Options are local, ray, remote. pt/sft/rl/infer/deploy/export default to ray (eval/merge do not take this argument): this process only drives, and the model / sampler / GPU-resident reward models are Ray actors in their own DeviceGroups. The width defaults to NPROC_PER_NODE or the number of visible devices. --mode local goes back to in-process execution (torchrun multi-process or a single-process script). When --mode is written explicitly, the written value is used.

remote: the training/inference process runs inside twinkle-server, and this process is a single-process twinkle_client driver. --model takes the server-side model name, and --backend specifies the server-side engine.

Note: swift rl forces ray for online RL and preference learning; remote mode is the exception.

nproc_per_nodev5

number of processes per node (the width of the training group under ray). Default: None. With local it is decided by the launcher. With ray it takes the NPROC_PER_NODE environment variable, and the number of currently visible devices when that is not set.

ray_exp_name

Ray experiment name, used as the prefix of cluster and worker names. Default: None. Read only with mode='ray'.

server_base_urlv5

gateway root address of twinkle-server when mode='remote' (required, without /api/v1, which the client appends automatically). Default: None.

server_api_keyv5

Bearer token of the gateway when mode='remote'. Default: None, that is, no authentication.

backendv5

training and inference backend. Options are hf (transformers), megatron, unsloth. Default: None, that is, transformers.

bridge_backend

conversion bridge for Megatron checkpoints. Options are mcore-bridge, megatron-bridge. Default: mcore-bridge.

parallel_specv5

DeviceMesh parallel layout, for example dp4tp2pp2. Supports dp/fsdp/tp/pp/cp/ep/etp/epfsdp/vpp/sp, shared by transformers and Megatron. Default: None.

deepspeed

DeepSpeed configuration. Set to zero0, zero1, zero2, zero3, zero2_offload, or zero3_offload to use a built-in configuration, or pass the path of a custom configuration file. Default: None.

zero_hpz_partition_size

intra-node model shard size of ZeRO++. Default: None. Try --torch_dtype float16 when grad_norm NaN appears.

deepspeed_autotp_size

tensor parallel size of DeepSpeed AutoTP. Requires --deepspeed of zero0/1/2 and full-parameter training. Default: None.

fsdp

FSDP2 configuration. Set to fsdp2 to use the built-in configuration, or pass the path of a custom configuration file. Use either this or DeepSpeed. Default: None.

fsdp_config

FSDP's own configuration (wrap policy, sharding, offload), json object or file. Default: None.

ddp_timeout

collective communication timeout (transformers backend), in seconds. Default: None.

ddp_find_unused_parameters

Default: None.

ddp_broadcast_buffers

broadcast buffers from rank 0 at every forward. Turning it off when there are no buffers can raise throughput. Default: None.

ddp_bucket_cap_mb

bucket size for all-reduce. The larger, the better the communication overlap, but the first reduction comes later. Default: None.

ddp_static_graph

fixed reduction order. Faster, but errors when the parameter set changes every step. Default: None.

local_rank

rank of this process, set by the launcher. Default: -1.

tensor_model_parallel_size

Megatron TP size. Default: 1.

pipeline_model_parallel_size

Megatron PP size. Default: 1.

context_parallel_size

Megatron CP size. Default: 1.

expert_model_parallel_size

Megatron EP size. Default: 1.

expert_tensor_parallel_size

TP size inside the MoE expert layers, which can differ from the dense layers. Default: 1.

sequence_parallel

sequence parallelism inside Megatron TP. Effective only when tp is greater than 1. Different from sequence_parallel_size (Ulysses) in the template arguments. Default: False.

use_distributed_optimizer

whether to use the Megatron distributed optimizer. Default: True.

use_megatron_fsdp

shard parameters with Megatron-FSDP. Requires the distributed optimizer and is incompatible with CP. Default: False.

recompute_granularity

Megatron recompute granularity. Options are selective, full, none. Default: selective.

recompute_method

recompute method for full. Options are uniform, block. Default: None.

recompute_num_layers

number of layers per recompute block. Default: None.

recompute_modules

recomputed submodules. Options are core_attn, mlp, moe. Default: ['core_attn'].

cp_comm_type

how k/v are exchanged between CP ranks: p2p, a2a, allgather, or a per-layer list. Default: None.

cp_partition_mode

how the sequence is split for CP. zigzag gives every rank both early and late positions (load-balanced for causal attention), and contiguous gives every rank one segment. Default: zigzag.

data_parallel_sharding_strategy

what the Megatron DP optimizer shards. optim_grads_params is equivalent to ZeRO-3. Default: optim_grads_params.

virtual_pipeline_model_parallel_size

number of interleaved (virtual) pipeline stages per rank. Reduces the pipeline bubble and costs one extra copy of activations per stage. Default: None.

pipeline_model_parallel_layout

explicit assignment of layers to pipeline stages. Default: None.

decoder_first_pipeline_num_layers

number of layers of the first pipeline stage. Default: None.

decoder_last_pipeline_num_layers

number of layers of the last pipeline stage. Default: None.

account_for_embedding_in_pipeline_split

count the embedding as one layer when splitting. Default: False.

account_for_loss_in_pipeline_split

count the loss as one layer when splitting. Default: False.

overlap_grad_reduce

overlap gradient reduction with the backward. Rejected with optimizer=muon, accepted with dist_muon. Default: False.

overlap_param_gather

overlap parameter gather with the forward. Default: False.

overlap_param_gather_with_optimizer_step

overlap parameter gather with the optimizer step. Requires overlap_param_gather. Default: False.

overlap_p2p_comm

overlap pipeline p2p communication. Default: True.

batch_p2p_comm

merge the sends and receives of the pipeline into one call. Default: None, which takes the Megatron default.

align_grad_reduce

align buckets so that every rank reduces at the same offset. Otherwise communication no longer overlaps. Default: True.

align_param_gather

same as align_grad_reduce, acting on parameter gather. Default: True.

tp_comm_overlap

overlap TP communication with GEMM. Requires Transformer Engine and userbuffer configuration. Default: False.

nccl_comm_warmup

run a warmup collective for every NCCL communicator. Default: False.

Training runs on Ray by default: CUDA_VISIBLE_DEVICES=0,1 swift sft sft.yaml starts a training group on the two visible GPUs. The width can also be specified explicitly with NPROC_PER_NODE=2 or --nproc_per_node 2. For local torchrun multi-process, write --mode local, for example NPROC_PER_NODE=2 CUDA_VISIBLE_DEVICES=0,1 swift sft --mode local sft.yaml. For remote deployment see Server and client.

⚙️ Megatron arguments

Effective only with --backend megatron.

apply_rope_fusion

fuse the RoPE operator. Default: False.

bias_activation_fusion

fuse bias and activation. Default: True.

bias_dropout_fusion

fuse bias and dropout. Default: True.

cross_entropy_loss_fusion

fuse the cross entropy. Default: True.

cross_entropy_fusion_impl

implementation of the cross-entropy fusion, native or te (requires Transformer Engine, faster). Default: native.

gradient_accumulation_fusion

fold gradient accumulation into the weight-gradient GEMM. Default: True.

masked_softmax_fusion

fuse masked softmax. Default: True.

apply_dsa_kernel_fusion

fuse the indexer kernel of DeepSeek sparse attention, only for models that have this indexer. Default: False.

attention_softmax_in_fp32

softmax in fp32, so that long-sequence logits do not easily overflow. Default: True.

apply_query_key_layer_scaling

whether to scale q·k additionally by the number of layers (Megatron fp16 stability). Default: None, decided by Megatron.

linear_decoupled_in_proj

keep the q/k/v projections as separate matrices instead of one fused weight. Default: False.

dsa_indexer_loss_coeff

auxiliary loss weight of the DSA indexer. 0 means the indexer is not trained. Default: 0.0.

dsa_indexer_use_sparse_loss

compute loss only on the sparsely selected part. Default: False.

use_fused_mhc

use the fused multi-head compression (MHC) kernel. Default: False.

mhc_recompute_layer_num

number of MHC layers recomputed in the backward. Default: None, that is, no recompute.

csa_dense_mode

run the CSA layer densely, to measure the cost of sparsification. Default: False.

perform_initialization

whether to initialize model parameters. Turn it off when loading a pretrained checkpoint, and on when training from scratch. Default: False.

use_cpu_initialization

build the initial weights on CPU. Slower but saves GPU memory. Default: False.

data_parallel_random_init

each DP rank uses a different initialization seed. Only meaningful when there is no checkpoint. Default: False.

te_rng_tracker

track random numbers through Transformer Engine, so that dropout is reproducible. Default: False.

manual_gc

manual garbage collection at fixed steps, to avoid unplanned collections blocking collective communication. Default: False.

manual_gc_eval

whether to collect garbage manually at evaluation time. Default: True.

manual_gc_steps

interval in steps of manual garbage collection. 0 disables it during training. Default: 0.

mlp_padding_free

the MLP also skips padding under padding_free. Default: False.

sequence_packing_scheduler

dp_balanced balances the token count across DP ranks, and default_dynamic_cp adjusts the CP split dynamically per batch. Default: None, which keeps Megatron's static behavior.

megatron_extra_kwargs

extra arguments passed directly to the Megatron argument namespace, json object or file. Default: None.

🧠 MoE arguments

Effective only for MoE models on the Megatron backend. For parallel sizes see the distributed arguments.

moe_aux_loss_coeff

load-balancing loss weight. A list can be passed to set it per layer. 0 risks routing collapse to a few experts. Default: 0.0.

moe_z_loss_coeff

z-loss weight, which keeps router logits small and routing stable. Default: None, that is, off.

moe_router_load_balancing_type

load-balancing strategy per layer (aux_loss, seq_aux_loss, sinkhorn, none). Default: None, which takes the Megatron default.

moe_router_dtype

router precision. Options are none, fp32, fp64. bf16 rounding flips discrete routing decisions. Default: fp32.

moe_token_dispatcher_type

token dispatch method. alltoall scales with EP, allgather only suits small EP, and flex chooses by the situation. Default: alltoall.

moe_token_drop_policy

the basis for dropping tokens when expert capacity is exceeded. Options are probs, position. Default: probs.

moe_expert_capacity_factor

multiple of expert capacity relative to uniform assignment. Default: None, that is, no cap, and GPU memory is decided by the busiest expert.

moe_pad_expert_input_to_capacity

pad each expert's input to capacity to get static shapes. Default: False.

moe_grouped_gemm

use one grouped GEMM instead of small per-expert GEMMs. Default: True.

moe_permute_fusion

fuse the expert grouping permutation into dispatch. Default: False.

moe_shared_expert_overlap

overlap the computation of the shared experts with the communication of the routed experts (requires shared experts). Default: False.

moe_layer_recomputev5

recompute the whole MoE layer in the backward. Default: False.

moe_enable_deepep

enable DeepEP (requires a separate installation). Default: False.

🧮 Quantization arguments

Quantization arguments when loading a model. For the meaning see the transformers quantization docs. For gptq/awq quantization in swift export see the export arguments.

quant_method

quantization method when loading a model. Options are bnb, hqq, eetq, quanto, fp8. Default: None.

Note: QLoRA training of an awq/gptq-quantized model needs no quantization arguments.

quant_bits

quantization bits. Options are 1, 2, 3, 4, 8, float8. Default: None.

hqq_axis

axis of hqq quantization. Default: None.

bnb_4bit_compute_dtype

bnb compute type. Options are float16, bfloat16, float32. Default: None, equal to torch_dtype.

bnb_4bit_quant_type

bnb quantization type. Options are fp4, nf4. Default: nf4.

bnb_4bit_use_double_quant

whether to use double quantization. Default: True.

bnb_4bit_quant_storage

bnb quantization storage type. Default: None.

✨ Generation arguments

See generation_config.

max_new_tokens

maximum number of generated tokens at inference. Default: None, no limit.

temperature

temperature. The higher, the more randomness. Default: None, read from generation_config.json. Setting --temperature 0 or --top_k 1 removes randomness.

top_k

keep the top_k tokens with the highest probability. Default: None, read from generation_config.json.

top_p

keep the tokens whose cumulative probability reaches top_p. Default: None, read from generation_config.json.

repetition_penalty

repetition penalty. 1.0 means no penalty. Default: None, read from generation_config.json.

num_beams

number of beams kept in beam search. Default: 1.

stream

streaming output. Default: None. True for interactive inference, False for batch inference on a dataset.

stop_words

stop words other than eos_token. Default: [].

Note: eos_token is removed from the output. Extra stop words are kept.

logprobs

whether to output logprobs. Default: False.

top_logprobs

number of top_logprobs to output. Default: None.

structured_outputs_regex

regular expression for structured output (guided decoding). Effective only with the vLLM/SGLang sampler. Default: None.

generation_configv5

path or directory of generation_config.json, used as the baseline configuration. The fields above override it. Default: None.

🎯 Reinforcement learning arguments

Used by swift rl. Besides this section, it also accepts training, sampling, and reward arguments.

rl_type

algorithm type. Options are 'dpo', 'orpo', 'simpo', 'kto', 'cpo', 'rm', 'ppo', 'grpo', 'gkd', 'opsd', 'mopd', 'rft'. Default: 'dpo'.

ref_model

id or path of the reference model. Needs to be passed when using dpo, kto, ppo, grpo, etc. with full-parameter training. Default: None, set to --model.

ref_adapters

list of adapter paths of the reference model. When using LoRA weights produced by SFT for DPO/KTO/GRPO, set --adapters <sft_ckpt> --ref_adapters <sft_ckpt>. When resuming training in that scenario, set --resume_from_checkpoint <rl_ckpt> --ref_adapters <sft_ckpt>. Default: [].

ref_model_type

same as model_type, acting on the reference model. Default: None.

ref_model_revision

same as model_revision, acting on the reference model. Default: None.

ref_parallel_specv5

parallel spec of the reference model (same as parallel_spec). Default: None.

beta

parameter that controls the deviation from the reference model. The higher the value, the smaller the deviation from the reference model. Default: None, taken per algorithm: 2.0 for simpo, 0.04 for grpo, 0.5 for gkd, 0.0 for opsd, mopd, rft, and 0.1 for the other algorithms. Under grpo, setting it to 0 does not load the reference model.

max_completion_length

maximum number of generated tokens. Default: 512. --response_length on the command line is its alias. In multi-turn training, the generation length per turn is controlled by max_new_tokens. The two are independent.

label_smoothing

label smoothing coefficient of DPO. Default: 0.

rpo_alpha

from the RPO paper. Controls the weight of the NLL term (that is, the SFT loss) in the loss, loss = dpo_loss + rpo_alpha * sft_loss. The paper recommends 1.0. Default: None, which introduces no SFT loss.

ld_alpha

from the LD-DPO paper. Weights the logps of the part beyond the common prefix to suppress length preference. Default: None.

discopop_tau

temperature parameter from the DiscoPOP paper, used to scale the log-ratio. Default: 0.05. Effective when loss_type is discopop.

loss_type

loss type. Default: None, taken per algorithm.

DPO: for the options see the documentation. Several values can be passed for mixed training (MPO), and loss_weights must be set when several values are passed. Default: sigmoid.

GRPO: loss normalization type. Options are 'grpo', 'bnpo', 'dr_grpo', 'dapo', 'cispo', 'sapo', 'real', 'fipo', 'dro', 'dis'. Default: 'grpo'.

loss_weights

weights of each loss term when several loss_types are set in DPO training.

cpo_alpha

coefficient of the nll loss in CPO/SimPO loss. Default: 1.0.

simpo_gamma

reward margin term in the SimPO algorithm. The paper recommends 0.5 to 1.5. Default: 1.0.

desirable_weight

weight of the desirable loss in the KTO algorithm, used to offset the effect of an imbalance between the numbers of desirable and undesirable samples. Default: 1.0.

undesirable_weight

weight of the undesirable loss in the KTO algorithm. Default: 1.0.

center_rewards_coefficient

coefficient in RM training that drives the reward model to output rewards with zero mean. See the paper. Recommended value 0.01. Default: None.

calculate_KL

whether to compute the KL divergence between the current model and the reference model and record it in the log. Default: None, decided automatically per algorithm.

f_divergence_type

type of KL divergence. Options are 'reverse_kl', 'forward_kl', 'js_divergence', 'alpha_divergence'. Default: 'reverse_kl'.

f_alpha_divergence_coefv5

coefficient of the alpha divergence. Default: 0.5.

reference_free

whether to train without a reference model (reference-free training). Default: False.

real_tau

temperature parameter when loss_type is real. Default: 0.5.

sync_ref_model

whether to sync the reference model periodically. Default: False.

ref_model_sync_steps: sync frequency. Default: 512.

ref_model_mixup_alpha: mixup coefficient between the model and the previous reference model at update time. The update formula is ref = mixup_alpha * model + (1 - mixup_alpha) * ref_prev. Default: 0.6.

reference_parallel_specv5

parallel spec of the reference model. Default: None.

🎯 PPO arguments

For the meaning of the arguments see here.

num_ppo_epochs

Default: 4.

whiten_rewards

Default: False.

kl_coef

Default: 0.05.

cliprange

Default: 0.2.

vf_coef

Default: 0.1.

cliprange_value

Default: 0.2.

gamma

Default: 1.0.

lam

Default: 0.95.

lam_alphav5

Default: None.

🎯 GRPO arguments

num_generations

number of samples per prompt, the G value in the paper. generation_batch_size must be divisible by num_generations. Default: 8.

generation_batch_size

number of prompts per rollout round. See the sampling arguments.

num_iterations

number of updates per sample, the $\mu$ value in the paper. Default: 1.

epsilon

clip coefficient. Default: 0.2.

epsilon_high

upper clip coefficient. Default: None. When set, it forms the clip range [epsilon, epsilon_high] together with epsilon.

delta

upper clip value of two-sided GRPO in INTELLECT-2. If set, a value greater than 1 + epsilon is recommended. Default: None.

advantage_estimator

advantage computation function. Options are 'grpo', 'rloo', 'reinforce_plus_plus', 'reinforce_plus_plus_baseline', 'remax', 'opo', 'gpg', 'grpo_passk'. Default: 'grpo', that is, the within-group relative advantage.

f_normv5

coefficient of advantage normalization. Default: 1.0.

segment_discountv5

discount coefficient across turns in multi-turn training. Default: 1.0.

kl_in_reward

controls where the KL divergence regularization term is handled. False means a separate regularization term in the loss function, and True means the KL is folded directly into the reward. The default is bound to advantage_estimator: False by default under grpo, and True by default under rloo and reinforce_plus_plus.

scale_rewards

reward scaling strategy. Options are 'group' (scale by the within-group std), 'batch' (scale by the std of the whole batch), 'none' (no scaling), and 'gdpo' (normalize within the group for each reward function separately and then aggregate by weight, see the paper). The default is bound to advantage_estimator: group for grpo, none for rloo, and batch for reinforce_plus_plus.

Note: gdpo mode does not support kl_in_reward=True. When both are set, kl_in_reward is automatically set to False.

importance_sampling_level

granularity at which the importance sampling ratio is computed. Options are 'token', 'sequence', 'sequence_token'. 'token' keeps the log-probability ratio of every token. 'sequence' averages the log-probability ratios of all valid tokens in the sequence (GSPO paper). Default: 'token'.

dynamic_sample

filter out data whose within-group reward std is 0 and sample new data. Default: False.

max_resample_times

upper limit of resampling times under dynamic_sample. Default: 3.

overlong_filter

skip samples truncated for being overly long. They do not take part in the loss computation. Default: False.

dro_betav5

coefficient of the dro loss. Default: 0.1.

clip_ratio_cv5

Default: 20.0.

clip_cov_ratiov5

Default: 0.0002.

clip_cov_lbv5

Default: 1.0.

clip_cov_ubv5

Default: 5.0.

kl_cov_ratiov5

Default: 0.0002.

ppo_kl_coefv5

Default: 1.0.

dis_detach_importance_weightv5

whether to detach the importance weight in the dis loss. Default: True.

log_completions

whether to record the model generations during training. Use together with --report_to wandb/swanlab. Default: False.

Tip: if --report_to wandb/swanlab is not set, a completions.jsonl is created in the checkpoint directory to store the generations.

log_entropy

record the change of entropy during training. Default: False.

top_entropy_quantile

only tokens whose entropy falls in the top specified quantile take part in the loss computation. Default: 1.0, that is, low-entropy tokens are not filtered.

tau_pos

temperature parameter for positive advantage in the SAPO algorithm. Controls the sharpness of the soft gating function. A larger value makes the gate sharper, and a smaller value makes it smoother. Default: 1.0.

tau_neg

temperature parameter for negative advantage in the SAPO algorithm. tau_neg is usually set larger than tau_pos to impose a stronger constraint on negative advantage. Default: 1.05.

fipo_decay_rate

FIPO Future-KL discount half-life parameter. The actual discount is 2 ** (-1 / fipo_decay_rate). Default: 32.0.

fipo_clip_range

clip range of the FIPO influence weight. Default: 0.2. No clipping when set to None or 0.

fipo_clip_high_only

whether to clip the FIPO influence weight only to [1.0, 1.0 + fipo_clip_range]. Default: True.

fipo_safety_threshold

when the IS ratio of a negative-advantage token exceeds this threshold, the FIPO influence weight is limited to [0.8, 1.0]. Default: 4.0.

teacher_kl_coef

coefficient of the teacher KL in OPD-RL, that is, adv_t = base_adv + teacher_kl_coef * teacher_kl. Default: 1.0.

advantage_reweight

advantage reweighting algorithm. Options are 'rlsd' (RLSD): it uses the difference between the log-probabilities of teacher and student on the same sampled tokens to redistribute the sequence-level advantage of GRPO along the token dimension, that is, delta_t = logP_T(y_t) - logP_S(y_t), w_t = exp(sign(A) * delta_t), reweight = (1 - λ) + λ * clip(w_t), A_hat_t = A * reweight. reweight is always positive and never flips the sign of the environment reward. Default: None, disabled.

When enabled, orm must already be set (the reweight direction depends on the sign of the advantage), and the dataset must contain a teacher_prompt column (a privileged prompt, such as the question plus the reference solution). Incompatible with use_liger_kernel, loss_type of real or fipo, and off_policy_sequence_mask_delta. When teacher_model is not set, it is dynamic self-distillation (the teacher is the current policy scoring on the privileged prompt). After --teacher_model is set, it is a frozen local teacher.

rlsd_lambda

RLSD mixing weight. 0 degenerates into plain GRPO, and 1 is full reweighting. The value range is [0, 1]. Default: 0.5.

rlsd_reweight_clip_range

evidence weight clip range. w_t is clipped to [1 - eps_w, 1 + eps_w]. Default: 0.2.

rlsd_lambda_warmup_steps

number of steps that warm up λ linearly from 0 to rlsd_lambda. Default: 0, no warmup.

rlsd_lambda_decay_steps

number of steps after warmup that decay λ linearly from rlsd_lambda to 0. Default: 0, no decay.

rlsd_negative_only

whether to reweight only the sequences with negative advantage. Sequences with non-negative advantage keep the plain GRPO advantage. Default: False.

sdar_loss_coef

coefficient of the confidence-gated teacher distillation auxiliary loss of SDAR (paper), added on top of the GRPO policy loss: loss = policy_loss + sdar_loss_coef * L_SDAR, where L_SDAR = token-mean(sigmoid(sdar_gate_beta * delta_t) * delta_t). Enabled when greater than 0. Incompatible with use_liger_kernel and advantage_reweight=rlsd. Default: 0.0, disabled.

sdar_gate_beta

temperature coefficient of the SDAR sigmoid gate. The larger, the sharper the gate. Default: 5.0.

rollout_importance_sampling_mode

training-inference mismatch correction mode. Options are 'token_truncate', 'token_mask', 'sequence_truncate', 'sequence_mask'. Default: None, correction disabled.

rollout_importance_sampling_threshold

threshold of the importance sampling weight, used to truncate or mask extreme weights. Default: 2.0.

log_rollout_offpolicy_metrics

when rollout_importance_sampling_mode is not set, whether to record the training-inference mismatch diagnostic metrics (KL, PPL, etc.). When the mode is set, the metrics are recorded automatically. Default: False.

off_policy_sequence_mask_delta

Off-Policy Sequence Masking threshold, from the paper. When set, mean(old_policy_logps - policy_logps) is computed for each sequence. If the value is greater than the threshold and the advantage of the sequence is negative, the sequence does not take part in the loss computation. Default: None.

router_replay_mode

router replay mode when training an MoE model. Options are 'disabled', 'R2', 'R3'. Default: 'disabled'.

actor_param_dtypev5

storage precision of the policy parameters during online training (grpo/ppo/real/gkd/opsd/mopd). Options are 'float32', 'float16', 'bfloat16'. Default: 'float32'. The compute precision is still decided by torch_dtype. The two are independent, and half-precision storage usually takes the same type as the compute precision (for example --torch_dtype float16 --actor_param_dtype float16). Under LoRA the base is frozen, and half precision saves about half of the GPU memory (for example, a 30B MoE). The cost is that the merged weights published to the sampling engine carry half-precision rounding. This argument does not take effect under full-parameter training, the megatron backend, or remote mode, and setting it explicitly is rejected.

enable_sampling_replayv5

whether to enable sampling replay. Default: False.

🎯 CHORD arguments

chord_sft_dataset

list of SFT datasets used by CHORD. Same format as dataset. Default: [].

chord_sft_per_device_train_batch_size

per-device batch size of the SFT data in CHORD. Default: None, the same as per_device_train_batch_size.

chord_enable_phi_function

whether to enable the phi function. Default: False.

chord_mu_warmup_steps

warmup steps of mu. Default: None.

chord_mu_decay_steps

decay steps of mu. Default: None.

chord_mu_peak

peak value of mu. Default: None.

chord_mu_valley

valley value of mu. Default: None.

🎯 GKD arguments

lmbda

parameter that controls the proportion of student data (that is, the proportion of outputs generated by the student within the policy). If 0, no student-generated data is used. Default: 0.5.

sft_alpha

weight of sft_loss added in GKD. The final loss is gkd_loss + sft_alpha * sft_loss. Default: 0.

gkd_logits_topk

use Top-K logits to compute the KL divergence, which effectively lowers the peak training GPU memory. Default: None, which computes over the full vocabulary.

distill_temperaturev5

distillation temperature. Default: 0.9.

sampling_temperaturev5

temperature of student sampling. Default: None.

⚙️ Teacher model arguments

The teacher model arguments are used in gkd, opsd, mopd, rft, and grpo (rlsd, sdar).

teacher_model

list of teacher model ids or paths. Several teachers correspond to teacher_weights in list order. Default: None.

teacher_adapters

list of LoRA weight paths loaded by teacher_model. Default: []. When specified explicitly together with teacher_model, an independent frozen teacher model is loaded even if teacher_model and model are the same, instead of reusing by disabling the adapter.

teacher_model_type

same as model_type, acting on the teacher model. Default: None.

teacher_model_revision

same as model_revision, acting on the teacher model. Default: None.

teacher_deepspeed

same as deepspeed, acting on the teacher model. Default: None, which uses the deepspeed configuration of the training model.

offload_teacher_model

offload the teacher model to save GPU memory, and load it when sampling or computing logps. Effective only when teacher_model is set. Default: False.

teacher_weightsv5

list of weights of several teachers. Default: None, with equal weights for all teachers.

teacher_parallel_specv5

parallel spec of the teacher model. Default: None.

auxiliary_placementv5

placement of auxiliary models (reference model, teacher model, reward model). 'pack' puts several auxiliary models on the same set of GPUs, and 'spread' spreads them across different GPUs. Default: 'pack'.

opsd_reversev5

whether to reverse the roles of teacher and student in the opsd algorithm. Default: True.

🎯 RFT arguments

rft_num_samplesv5

number of samples per prompt. Default: None, which uses num_generations.

rft_selectv5

selection strategy. Options are 'best_of_n' (keep the samples with the highest reward), 'threshold' (keep the samples whose reward is above the threshold), and 'top_k' (keep the k samples with the highest reward). Default: 'best_of_n'.

rft_thresholdv5

threshold when rft_select is threshold. Default: 0.0.

rft_top_kv5

value of k when rft_select is top_k. Default: 1.

rft_iterationsv5

number of iterations. Each iteration trains on the samples selected in the previous round and then samples again. Default: 1.

rft_max_samples_per_promptv5

upper limit of samples finally kept per prompt. Default: None, no limit.

🏅 Reward arguments

Used by swift rl. The two groups orm (outcome reward model) and prm (process reward model) have the same structure.

orm

list of outcome reward sources. Each item can be a built-in rule name, a model id or path, or a reward function name registered in a plugin. Built-in rules are 'accuracy', 'format', 'cosine', 'repetition', 'soft_overlong', 'code_execution'. Custom reward functions are registered through --external_plugins. Default: [].

orm_weights

weights of the orms. The count must match orm. Default: None, with equal weights for all rewards.

orm_adaptersv5

list of adapter paths loaded by each orm. Default: None.

orm_model_typev5

list of model_types of the orms. Default: None.

orm_task_typev5

list of task_types of the orms. Options are 'seq_cls', 'reward_model', etc. Default: None.

orm_model_revisionv5

list of model versions of the orms. Default: None.

orm_templatev5

list of templates used by the orms. Default: None.

orm_parallel_specv5

parallel spec of the reward model. Default: None.

prm

list of process reward sources. Same format as orm. Default: [].

prm_weightsv5

weights of the prms. Default: None.

prm_adaptersv5

list of adapter paths loaded by each prm. Default: None.

prm_model_typev5

list of model_types of the prms. Default: None.

prm_task_typev5

list of task_types of the prms. Default: None.

prm_model_revisionv5

list of model versions of the prms. Default: None.

prm_templatev5

list of templates used by the prms. Default: None.

prm_parallel_specv5

parallel spec of the process reward model. Default: None.

prm_scorerv5

scoring method of the process reward. 'turn' scores by conversation turn, and 'delimiter' splits the steps by a delimiter and scores them. Default: None.

prm_step_delimiterv5

delimiter that splits the steps when prm_scorer is delimiter. Default: None.

prm_orm_mixv5

mixing ratio of the process reward and the outcome reward. The final reward is prm_orm_mix * prm + (1 - prm_orm_mix) * orm. Default: 0.5.

env_reward_weightv5

weight of the environment reward (the reward returned by the sandbox in multi-turn interaction). Default: 1.0.

judge_templatev5

template used when a model serves as the judge (LLM-as-a-judge). Default: None.

🏅 cosine reward arguments

cosine_min_len_value_wrong

reward value corresponding to the minimum length when a wrong answer is generated. Default: -0.5.

cosine_max_len_value_wrong

reward value corresponding to the maximum length when a wrong answer is generated. Default: 0.0.

cosine_min_len_value_correct

reward value corresponding to the minimum length when a correct answer is generated. Default: 1.0.

cosine_max_len_value_correct

reward value corresponding to the maximum length when a correct answer is generated. Default: 0.5.

cosine_max_len

maximum length of the generated text. Default: equal to max_completion_length.

🏅 repetition reward arguments

repetition_n_grams

n-gram size used to detect repetition. Default: 3.

repetition_max_penalty

maximum penalty value, used to control the penalty strength. Default: -1.0.

🏅 soft overlong reward arguments

soft_max_length

L_max in the paper, the maximum generation length of the model. Default: equal to max_completion_length.

soft_cache_length

L_cache in the paper, which controls the length penalty interval. The interval is [soft_max_length - soft_cache_length, soft_max_length]. Default: None.

🏅 code_execution reward arguments

code_languagev5

code language. Default: 'python'.

code_timeoutv5

code execution timeout, in seconds. Default: 10.

code_max_concurrencyv5

maximum number of concurrent executions. Default: 8.

code_memory_limit_gbv5

memory limit of each execution (GB). Default: 2.0.

code_sandbox_templatev5

sandbox template used to execute code. Default: None.

🎲 Sampling arguments

Used by swift rl, swift infer, swift deploy, and swift eval. For the meaning of vLLM arguments see the vLLM docs, and for SGLang arguments see the SGLang docs.

⚙️ vLLM arguments

vllm_gpu_memory_utilization

GPU memory ratio, ranging from 0 to 1. Default: 0.9.

vllm_tensor_parallel_size

tp parallel size. Default: 1.

vllm_pipeline_parallel_size

pp parallel size. Default: 1.

vllm_data_parallel_size

dp parallel size. Default: 1.

vllm_enable_expert_parallel

enable expert parallelism for MoE models. Default: False.

vllm_max_num_seqs

maximum number of sequences processed in one iteration. Default: None, which takes the vLLM default.

vllm_max_model_len

maximum length supported by the model. Default: None, read from config.json.

vllm_disable_custom_all_reduce

disable the custom all-reduce kernel and fall back to NCCL. Default: True, for stability.

vllm_enforce_eager

whether to use pytorch eager mode or build a cuda graph. Default: False. Setting it to True saves GPU memory but affects efficiency.

vllm_mm_processor_cache_gb

multimodal processor cache size (GiB), used to cache processed multimodal inputs (such as images and videos) to avoid repeated processing. Setting it to 0 disables the cache but lowers performance. Effective only for multimodal models. Default: None, which takes the vLLM default.

vllm_speculative_config

speculative decoding configuration, json string. Default: None.

vllm_disable_cascade_attn

whether to forcibly disable the cascade attention implementation of the V1 engine to prevent potential numerical errors. Default: False. Whether it is used is decided by vLLM's internal logic.

vllm_limit_mm_per_prompt

control the number of multimodal inputs in a single request, for example --vllm_limit_mm_per_prompt '{"image": 5, "video": 2}'. Default: None.

vllm_quantization

vLLM quantizes the model internally. For the options see the vLLM docs. Default: None.

vllm_enable_prefix_caching

enable vLLM's automatic prefix caching, which saves the processing time of repeated query prefixes. Default: True.

vllm_reasoning_parser

reasoning parser type, used to parse the chain-of-thought content of thinking models. Only used by swift deploy. For the options see the vLLM docs. Default: None.

vllm_engine_kwargs

extra vLLM arguments, json string. Default: None.

⚙️ SGLang arguments

sglang_tp_size

tp size. Default: 1.

sglang_pp_size

pp size. Default: 1.

sglang_dp_size

dp size. Default: 1.

sglang_ep_size

ep size. Default: 1.

sglang_enable_ep_moe

whether to enable ep moe. Default: False.

sglang_enable_dp_attention

enable data parallelism for the attention and tensor parallelism for the feed-forward network. The dp size should equal the tp size. Currently supports DeepSeek-V2/V3 and Qwen2/Q3 MoE models. Default: False.

sglang_mem_fraction_static

GPU memory ratio used to statically allocate the model weights and the KV cache memory pool. Lower this value when GPU memory is insufficient. Default: None, which takes the SGLang default.

sglang_context_length

maximum context length of the model. Default: None, which uses the value in the model's config.json.

sglang_disable_cuda_graph

disable the CUDA graph. Default: False.

sglang_quantization

quantization method. Default: None.

sglang_kv_cache_dtype

data type used to store the k/v cache. 'auto' means using the model's data type. 'fp8_e5m2' and 'fp8_e4m3' apply to CUDA 11.8 and above. Default: 'auto'.

sglang_disable_custom_all_reduce

disable the custom all-reduce kernel and fall back to NCCL. Default: True, for stability.

sglang_speculative_algorithm

speculative algorithm. Options are None, 'EAGLE', 'EAGLE3', 'NEXTN', 'STANDALONE', 'NGRAM'. Default: None.

sglang_speculative_num_steps

number of steps sampled from the draft model in speculative decoding. Default: None.

sglang_speculative_eagle_topk

number of tokens sampled from the draft model per step in the EAGLE2 algorithm. Default: None.

sglang_speculative_num_draft_tokens

number of tokens sampled from the draft model in speculative decoding. Default: None.

⏱️ Scheduling and resource arguments

sampler_mode

GPU placement of the training process and the sampling process. 'colocate' shares the same set of GPUs, and 'disaggregated' uses disjoint GPUs. Default: None, that is, disaggregated.

rollout_samplerv5

inference engine used by the standalone sampling process. Options are 'vllm', 'sglang'. Default: 'vllm'.

async_modev5

degree of asynchrony of rollout relative to training. 'none' samples synchronously. 'one_step_off' samples with the model after the previous round's update, which speeds up training and does not support multi-turn scenarios. 'fully_async' samples fully asynchronously with training, and max_staleness limits the number of policy versions it lags behind. Default: 'none'.

async_generate

equivalent to --async_mode one_step_off. When set together with async_mode, the two must be consistent. Default: False.

max_stalenessv5

under fully_async mode, the maximum number of versions that in-progress trajectories lag behind the training policy. Fixed at 1 for one_step_off. Default: 1.

weight_sync_backendv5

transport of weight sync. 'full' transfers the full weights. 'delta_sharded' transfers only the changed elements, and the first sync still transfers the full weights. delta_sharded requires disaggregated placement and the vllm sampler. Default: 'full'.

weight_sync_timeoutv5

time limit in seconds of each weight sync call (sync weights, warm up, close). When the peer GPU is inside a communication collective, the call times out with an error instead of blocking the driver forever. None takes the default of each backend (one hour for full, 300 seconds for delta_sharded). It can be raised for very large models or slow links. Default: None.

parameter_sync_stepv5

interval in steps at which weights are published. 1 syncs every step. Default: 1.

sleep_level

release vLLM GPU memory during training in colocate mode. 0 releases nothing, 1 unloads the weights and drops the KV cache, and 2 drops both. Only 0 and 1 are accepted when resource_mode is adaptive. Default: 0.

offload_optimizer

whether to offload the optimizer state during rollout in colocate mode. When resource_mode is adaptive, at least one of offload_optimizer and offload_model must be on. Default: False.

offload_model

whether to offload the training model weights during rollout in colocate mode. Default: False.

resource_modev5

resource planning mode. 'manual' specifies manually with the arguments below. 'estimate' produces a static plan from the GPU memory estimate. 'adaptive' adjusts the number of sampling replicas dynamically during training. Default: 'manual'.

resource_total_gpusv5

total number of physical GPUs available to the whole job. Default: None, obtained from the cluster.

resource_gpu_memory_gibv5

GPU memory of a single card (GiB). Default: None, which takes the smallest GPU memory visible to Ray.

resource_flex_gpusv5

number of GPUs reserved at initialization for run-time role switching. Default: 0.

resource_window_stepsv5

number of sliding-window steps for evaluating the GPU memory pressure of each role under adaptive mode. Default: 3.

resource_min_hold_stepsv5

number of syncs to wait after moving a replica under adaptive mode. Default: 5.

resource_overridesv5

explicitly override the estimation results, json string. Keys are validated before actors are built. Default: None.

rollout_num_workersv5

number of Ray CPU replicas used by rollout. Episodes are routed to replicas by id. Default: 1.

generation_batch_size

number of prompts per rollout round. Default: None, derived from the training batch so that each sampling round fills exactly an integer number of optimizer steps.

⚙️ Multi-turn and sandbox arguments

toolsv5

list of tools callable in multi-turn rollout, selected from 'tool' plugins. Default: [].

max_turns

maximum number of turns in multi-turn training. Setting it turns on multi-turn training. Default: None, single turn.

max_trajectory_tokensv5

maximum number of tokens of the whole trajectory (all turns). Default: None, no limit.

sandbox_kindv5

sandbox type. 'local' is an in-process workspace. 'agentenv' is a microVM and requires sandbox_template. 'openenv' embeds the OpenEnv environment package in-process and requires sandbox_env_name. 'openenv_client' connects to a running OpenEnv service and requires sandbox_env_name and sandbox_api_url (or the environment variable OPENENV_BASE_URL). Default: 'local'.

sandbox_env_namev5

name of the OpenEnv environment package, for example 'coding_env' (corresponding to pip install openenv-coding_env). Default: None.

sandbox_env_kwargsv5

construction arguments of the OpenEnv environment class, json string, for example '{"game_name": "blackjack"}'. Default: None, which uses the environment package defaults.

sandbox_templatev5

AgentENV template name or id. Default: None, which uses the local LocalEnv.

sandbox_workspace_rootv5

root directory of the LocalEnv session workspace. Default: None, which uses a temporary directory.

sandbox_num_envsv5

upper limit of the total number of sessions held at the same time across all environment replicas. Default: 1.

sandbox_num_workersv5

number of Ray CPU replicas used by the sandbox environment. Each replica holds sandbox_num_envs / sandbox_num_workers sessions. Default: 1.

sandbox_session_waitv5

timeout in seconds for the environment reset to wait for a free session. None waits forever, and 0 does not wait. Default: 600.

sandbox_api_urlv5

address of the AgentENV service. Default: None, read from E2B_API_URL by the SDK.

sandbox_timeoutv5

idle timeout in seconds of the AgentENV sandbox. Default: None, which uses the AgentEnv default.

sandbox_command_timeoutv5

execution timeout in seconds of a single command. Effective for both LocalEnv and AgentEnv. Default: 60.

sandbox_memory_limit_gbv5

address space limit (GB) of a single LocalEnv call. Default: 2.0.

segment_policyv5

how context compression boundaries are handled. 'drop' keeps only the last segment trainable, one row per episode. 'collect' makes every segment an independent training row. Multiple rows of the same episode share the same outcome, and the advantage is computed once per episode and broadcast. Default: 'drop'.

harnessv5

name of the 'harness' plugin that runs an external agent program (codex, ms_agent, or a custom plugin registered through --external_plugins). Default: None, which uses the built-in tool-call loop.

🚀 Inference arguments

Used by swift infer. Besides this section, it also accepts model, data, template, fine-tuning, sampling, generation, and save arguments.

sampler

inference engine. Options are 'transformers', 'vllm', 'sglang', 'openai', 'no', or a registered sampler plugin name. 'pt' is equivalent to 'transformers'. 'no' does not run inference and only preprocesses the dataset (together with --to_cached_dataset). 'openai' does not load a local model. It sends /chat/completions requests to the OpenAI-compatible service at --infer_url (swift deploy or any OpenAI service), and replies are re-encoded by the local template, symmetric with --eval_url of evaluation. Default: 'transformers'.

infer_urlv5

service address when sampler is 'openai', for example http://127.0.0.1:8000/v1. Required. --model is both the model name in the request and the source of the local template/tokenizer.

infer_api_keyv5

api_key required by the infer_url service. Default: None. Can be omitted for a local service.

max_batch_size

batch inference size when sampler is 'transformers'. Default: 1. -1 means no limit.

val_dataset_sample

sample count of the inference dataset. Default: None.

result_path

storage path of the inference results (jsonl). Default: None, saved to result/<model>/infer_result/<timestamp>.jsonl. The final path is printed on the command line. An existing file is appended to.

output_formatv5

format of the inference results. Options are 'all' (save both inputs and outputs) and 'dpo' (save as preference data format). Default: 'all'.

store_formatv5

format of the inference result file. Default: 'jsonl'.

store_fieldsv5

whitelist of fields saved in the results. Default: None, which saves all fields.

metric

evaluate the inference results. 'acc' and 'rouge' are currently supported. Default: None, no evaluation.

reranker_use_activation

whether to apply sigmoid after the score in reranker inference. Default: True.

engine_kwargs

extra arguments passed to the sampling engine, json string. Default: None.

num_samplesv5

number of candidates generated per sample, used for the subsequent reward scoring and filtering. Default: 1.

num_return_sequences

same as num_samples.

n_best_to_keep

number of best candidates kept per sample after scoring. Default: 5.

reward_threshold

candidates whose reward is below this value are filtered out. Default: None, no filtering.

easy_query_threshold

when the ratio of candidates that the orm evaluates as correct among all candidates of a single query is above this value, the query is dropped, to keep overly easy queries out of the results. Default: None, no filtering.

normalize_rewardsv5

whether to normalize the rewards. Default: False.

score_ground_truthv5

whether to score the reference answers of the dataset as well. Default: False.

orm_channel_weightv5

weight of the reward channel. Default: 1.0.

batch_sizev5

batch size for reward scoring. Default: 1.

max_batchesv5

maximum number of batches to process, for debugging. Default: None, no limit.

num_sampling_batch_size

batch_size of each sampling round. Default: None.

num_sampling_batches

how many batches to sample in total. Default: None.

resume

whether to resume from an existing result_path and skip the already-processed data. Default: False.

override_exist_file

whether to overwrite when result_path already exists. Default: False.

cache_files

list of jsonl files output by the previous sampling step. When passed, sampler is automatically set to 'no', and these files are read directly for reward scoring and filtering. --dataset still needs to be passed. Records in cache_files are aligned with the dataset by the md5 of the original data. Default: [].

generation_strictv5

whether to raise an error directly when inference fails. Default: True.

eval_humanv5

enter the interactive command-line chat. Default: False.

multi_roundv5

whether to keep the multi-turn history in the interactive chat. Default: True.

🌐 Deployment arguments

Used by swift deploy. Besides this section, it also accepts model, data, template, fine-tuning, sampling, generation, and inference arguments.

merge_lora

merge the LoRA weights into the base model before deployment. Default: False.

host

service host. Default: '0.0.0.0'.

port

port number. Default: 8000.

api_key

api_key required to access the service. Default: None, no validation.

ssl_keyfile

SSL private key file path. Default: None.

ssl_certfile

SSL certificate file path. Default: None.

served_model_name

model name provided by the service. Default: the suffix of model.

owned_by

owned_by field in the response body. Default: 'swift'.

max_logprobs

maximum number of logprobs returned to the client. Default: 20.

max_concurrencyv5

maximum number of requests processed at the same time on the server side. Default: 64.

ray_addressv5

address of the Ray cluster to connect to. Default: None, which uses the local Ray.

ray_namespacev5

Ray namespace. Default: 'swift'.

route_prefixv5

service route prefix. Default: '/v1'. twinkle_client requires '/api/v1'.

sampler_type

sampler used for deployment. Options are 'mock', 'vllm', 'sglang', 'torch'. Default: None, derived from backend: vllm for vllm, sglang for sglang, and torch for the others.

num_replicasv5

number of sampler replicas. Default: None, one replica per model.

autoscalingv5

whether to scale the sampler replicas automatically by load. Default: False.

detachv5

run in the background after starting the service. Default: False.

stopv5

stop the background service started by swift deploy. Default: False.

📏 Evaluation arguments

Used by swift eval. Besides this section, it also accepts model, data, template, fine-tuning, sampling, generation, and inference arguments.

eval_dataset

list of evaluation dataset ids or paths. Same format as dataset.

eval_limit

sample count of each evaluation set. Default: None.

eval_dataset_args

evaluation dataset arguments, json string. Arguments can be set per dataset name. Default: empty.

eval_generation_config

model inference configuration at evaluation time, json string, for example '{"max_new_tokens": 512}'. Default: empty.

eval_output_dir

storage directory of the evaluation results. Default: 'eval_output'.

eval_num_proc

maximum client concurrency at evaluation time. Default: 16.

extra_eval_args

extra evaluation arguments, json string, passed through to the evaluation backend. Default: empty.

result_jsonlv5

storage path of the evaluation details (the input, output, and score of each sample). Default: None, saved to eval_output_dir.

eval_url

address of the OpenAI-compatible service to evaluate, for example http://127.0.0.1:8100/v1. When set, no local inference service is started, and --model is used as the model name in the request. Default: None, which deploys locally for evaluation.

eval_api_keyv5

api_key required by the eval_url service. Default: None.

📤 Export arguments

Used by swift export. Besides this section, it also accepts model, data, template, fine-tuning, quantization, distributed, Megatron, and MoE arguments.

output_dir

storage path of the export results, also used for --push_to_hub. Default: 'output'.

exist_ok

do not raise an exception when output_dir already exists, and overwrite directly. Default: False.

merge_lora

merge the LoRA weights into the base weights and save as a complete model. Default: False.

to_peft_format

save the adapter in PEFT's directory structure, for downstream use that only uses PEFT, without merging. Default: False.

quant_method

quantization method. Options are 'gptq', 'gptq_v2', 'awq', 'bnb', 'hqq', 'eetq', 'quanto', 'fp8'. Default: None, no quantization.

to_cached_dataset

tokenize and export the dataset in advance, for use with --cached_dataset. Default: False.

Tip: the validation set content can be specified with --split_dataset_ratio or --val_dataset.

template_mode

training type used when exporting the cached dataset. Options are 'train', 'rlhf', 'kto'. pt/sft use 'train', kto uses 'kto', and the other rl algorithms use 'rlhf'. Default: 'train'.

store_encodedv5

whether to save input_ids and labels when exporting the cached dataset. When saved, encoding is skipped at training time. Default: False.

store_formatv5

storage format of the cached dataset. Default: 'arrow'. Options are 'jsonl' and formats registered through plugins.

store_fieldsv5

columns kept in the cached dataset. Default: None, which keeps all columns produced by encoding.

to_mcore

convert HF-format weights to Megatron format. When mcore_model is set, it means re-sharding or merging existing Megatron weights. Default: False.

to_hf

convert Megatron-format weights to HF format. Default: False.

mcore_model

path of the Megatron-format model. Default: None.

mcore_adapter

path of the Megatron-format LoRA weights, merged into the base weights before conversion. Default: None.

thread_count

number of write threads when converting to the torch-dist format. Default: None, set automatically by model size (about one thread per 10GB, at least 2).

test_convert_precision

after conversion, feed the same sample to both models and compare the outputs, to test the precision error. Default: False.

test_convert_dtype

dtype used for the precision test. Options are 'float16', 'bfloat16', 'float32'. Default: 'float32'.

commit_message

commit message for --push_to_hub. Default: 'update files'.

🔀 Merge arguments

Used by swift merge. Besides this section, it also accepts model, data, template, fine-tuning, and save arguments.

output_dir

storage path of the merged model. Default: None, which uses the first adapter path plus the suffix -merged.

replace_if_existsv5

whether to overwrite when output_dir already exists. Default: False.

weight_transform_parallel_sizev5

see the run arguments.

💾 Save arguments

Used by swift pt/sft/rl/export.

output_dir

output directory. Checkpoints are saved under this directory. Default: 'output'.

add_version

create an extra <version>-<timestamp> subdirectory under output_dir, to prevent weights from being overwritten. Default: True.

save_strategy

save strategy. Options are 'steps' (by steps), 'epoch' (by epochs), 'no' (do not save), and 'best' (save only the best). Default: 'steps'.

save_steps

interval in steps between saves. It can be a float (0.5 means every half epoch). Default: 500.

save_total_limit

maximum number of checkpoints to keep. The oldest are deleted when exceeded. Default: None, no limit.

save_only_model

save only the model weights, without the optimizer state and the random number state (resume is not possible). Default: False.

safe_serialization

whether to save in safetensors format. Default: True.

save_safetensors

same as safe_serialization.

max_shard_size

maximum size of a single weight file. Default: '5GB'.

async_save

save checkpoints asynchronously. Default: False.

no_save_optim

do not save the optimizer state. Default: False.

no_save_rng

do not save the random number state. Default: False.

no_load_optim

do not load the optimizer state when loading a checkpoint. Default: False.

no_load_rng

do not load the random number state when loading a checkpoint. Default: False.

resume_from_checkpoint

checkpoint directory to resume from. Loads the model weights, the optimizer state, and the random number state, and skips the already-trained part of the dataset.

Note: to only read the adapter weights without resuming, use --adapters.

resume_only_model

load only the model weights when resuming. Default: False.

ignore_data_skip

do not skip the already-trained part of the dataset when resuming. Default: False.

push_to_hub

whether to push the model to the hub. Default: False.

hub_model_id

model_id to push, in the format '<user name>/<model name>'. Default: None.

hub_private_repo

whether it is a private repo. Default: False.

hub_strategy

push strategy. Options are 'end' (at the end of training), 'every_save' (at every save), 'checkpoint' (push to the checkpoint directory together with each checkpoint save), and 'all_checkpoints'. Default: 'every_save'.

hub_revision

branch to push to. Default: None.

hub_always_push

push even when the remote already has the same content. Default: False.

load_args

read the training-time arguments from args.json in the --model, --adapters, or --resume_from_checkpoint directory. Default: False.

load_data_args

whether to additionally read the data arguments in args.json, used to infer on the validation set split at training time, for example swift infer --adapters <ckpt> --load_data_args true --stream true --max_new_tokens 512. Default: False.

trust_remote_plugins

whether to allow loading plugins that are not in the whitelist. Default: False.

📝 Logging arguments

report_to

list of backends to report training metrics to. Options are 'tensorboard', 'swanlab', 'wandb', 'none'. Default: ['tensorboard'].

logging_dir

log directory. Default: None, which uses the runs directory under output_dir.

run_name

experiment name. Default: None, which uses output_dir.

logging_steps

interval in steps between log records. Default: 5.

logging_first_step

whether to log at the first step. Default: True.

logging_nan_inf_filter

filter nan and inf in the logs. Default: False.

logging_strategy

logging strategy. Options are 'steps', 'epoch', 'no'. Default: 'steps'.

tensorboard_dir

tensorboard log directory. Default: None.

tensorboard_queue_size

tensorboard write queue size. Default: 50.

⚙️ SWANLAB

swanlab_token

SwanLab api-key. Can also be specified with the environment variable SWANLAB_API_KEY. Default: None.

swanlab_project

swanlab project. Default: 'ms-swift'.

swanlab_workspace

Default: None, which uses the username of the api-key.

swanlab_exp_name

experiment name. Default: None, which uses output_dir.

swanlab_mode

options are 'cloud' and 'local', cloud mode or local mode. Default: 'cloud'.

swanlab_notification_method

how to notify when training completes or an error occurs. Supports 'dingtalk', 'lark', 'email', 'discord', 'wxwork', 'slack'. See here. Default: None.

swanlab_webhook_url

webhook url matching swanlab_notification_method. Default: None.

swanlab_secret

secret matching swanlab_notification_method. Default: None.

swanlab_smtp_server

SMTP server for email notification. Default: None.

swanlab_smtp_port

SMTP port for email notification. Default: None.

swanlab_sender_email

sender email address. Default: None.

swanlab_receiver_email

receiver email address. Default: None.

swanlab_email_language

email language. Default: 'zh'.

⚙️ WANDB

wandb_project

wandb project. Default: 'ms-swift'.

wandb_exp_name

experiment name. Default: None.

wandb_log_unique_prompts

whether to log only unique prompts. Default: None.

▶️ Run arguments

seed

global random seed. Default: 42. Does not affect data_seed, which controls the dataset shuffle, and vice versa.

weight_transform_parallel_sizev5

parallel size for weight conversion (--to_hf/--to_mcore). Default: 1.

external_plugins

list of external plugin.py files. These files are imported additionally. Paths of .py files that register custom models, chat templates, datasets, reward functions, or harnesses can be passed. See the plugin docs. Default: [].

🧰 Environment variables

Environment variables can be set before the launch command, or written in the ENV section of a YAML/JSON configuration file.

▶️ Launch and devices

CUDA_VISIBLE_DEVICES

control which GPUs are used. By default all GPUs are used.

ASCEND_RT_VISIBLE_DEVICES

control which NPUs are used. Only effective for Ascend cards. By default all cards are used.

NPROC_PER_NODE

number of processes per machine. The infer/export commands and training commands with --mode local or the megatron backend restart with torchrun once NPROC_PER_NODE or NNODES is set; pt/sft/rl default to ray mode and are not relaunched by this variable, and remote mode is never relaunched. Default: 1.

NNODES

number of nodes in multi-node training.

NODE_RANK

index of the current node in multi-node training.

MASTER_ADDR

address of the master node in multi-node training.

MASTER_PORT

torchrun communication port. Default: 29500.

RAY_ADDRESS

Ray cluster address. After this variable is set, --mode ray connects to that cluster directly.

PYTORCH_CUDA_ALLOC_CONF

recommended to be set to 'expandable_segments:True' to reduce GPU memory fragmentation. See the torch docs.

OMP_NUM_THREADS

number of CPU threads per process. Setting it to 1 is recommended for multi-process training, to avoid thread contention.

SWIFT_SINGLE_DEVICE_MODE

single-device mode. Options are '0' or '1'. When set to '1', each process can only see one device. Default: '0'.

⚙️ Download and cache

USE_HF

download models and datasets from HuggingFace. Options are '0' or '1'. Default: '0', which uses ModelScope.

USE_HF_TRANSFER

use hf_transfer to speed up HuggingFace downloads. Requires hf_transfer to be installed. Default: '0'.

HF_ENDPOINT

HuggingFace mirror address, for example https://hf-mirror.com.

HF_DATASETS_OFFLINE / HF_HUB_OFFLINE

when set to '1', do not access the HuggingFace network and use only the local cache.

MODELSCOPE_CACHE

ModelScope cache path. Recommended to set in multi-node training, to make sure that different nodes use the same dataset cache.

MODELSCOPE_DOMAIN

ModelScope domain. When accessing from outside China, it can be set to 'www.modelscope.ai' to use the international version.

MODELSCOPE_API_TOKEN

ModelScope access token, used to download private models or push models. See here.

SWIFT_TIMEOUT

download timeout in seconds for the image, video, and audio URLs in multimodal datasets. Default: 20.

📝 Logging and debugging

LOG_LEVEL

log level. Default: 'INFO'. Can be set to 'WARNING', 'ERROR', etc.

LOG_ONLY_MASTER

print logs only in the master process. The other processes print only ERROR, which makes it easier to troubleshoot problems that occur only in non-master processes. Default: True.

SWIFT_ENABLE_NPU_MODEL_PATCH

switch of the Ascend model layer patch. v5 sets it from the platform (on for Ascend, off for other hardware); an external value that disagrees with the platform is overridden with a warning, so setting '0' cannot disable the patch for comparison troubleshooting. See NPU support.

TWINKLE_PERF

when set to '1', output the time statistics of each twinkle stage. Default: '0'.

OPENAI_API_KEY

api_key used when calling an OpenAI-compatible model service (for example LLM-as-a-judge).

🔒 Security

SWIFT_TRUST_REMOTE_PLUGINS

when set to '1', allow loading plugins that are not in the whitelist, equivalent to --trust_remote_plugins true. Default: '0'.

⚙️ Model-specific

The resolution and frame count of multimodal inputs are preferably set through --vision_process_kwargs. The environment variables below override the global defaults of the model preprocessing.

MAX_PIXELS / MIN_PIXELS

maximum/minimum resolution of images for the Qwen-VL series. Multiples of 28*28 are recommended. MAX_PIXELS defaults to 16384 * 28 * 28. Lowering it can avoid OOM.

VIDEO_MAX_PIXELS / VIDEO_MIN_PIXELS

maximum/minimum resolution of a single video frame for the Qwen-VL series. The defaults are 768 * 28 * 28 and 128 * 28 * 28 respectively.

IMAGE_MAX_TOKEN_NUM / IMAGE_MIN_TOKEN_NUM / VIDEO_MAX_TOKEN_NUM / VIDEO_MIN_TOKEN_NUM

the Qwen3-VL series controls resolution and frame count by token count. Setting the PIXELS variables automatically converts them into the TOKEN_NUM variables.

SPATIAL_MERGE_SIZE

number of adjacent tokens merged for the Qwen3-VL series. Default: 2.

ENABLE_AUDIO_OUTPUT

whether the Qwen-Omni series creates and loads the audio output (talker) part. Default: the value in config.json. Setting it to False is recommended when only fine-tuning the thinker part, to lower GPU memory usage.

THINKING_BUDGET / SEED_USE_THINKING / SEED_USE_BUDGET_INTERVAL

thinking token budget, whether to enable thinking, and budget interval for the thinking models of the Seed series.

GENERATIVE_RERANKER_POSITIVE_TOKEN / GENERATIVE_RERANKER_NEGATIVE_TOKEN

tokens used by the generative reranker to output the Yes/No verdict. Default: 'yes' and 'no'.

📡 twinkle

Connection configuration of the twinkle server and client. For usage see Server and client.

TWINKLE_SERVER_URL

twinkle service address. Default: 'http://127.0.0.1:8000'.

TWINKLE_SERVER_TOKEN

token for accessing the twinkle service. Default: the 'EMPTY_TOKEN' placeholder, i.e. no real token configured.

TWINKLE_SERVER_CONFIG

path of the YAML configuration file read when the twinkle server starts. Default: None.

TWINKLE_RAY_NAMESPACE

Ray namespace used by twinkle. Default: None.

TWINKLE_TRUST_REMOTE_CODE

whether twinkle trusts remote code. When set to '0', Callable and Type inputs are rejected. Default: '1'.

TWINKLE_DEFAULT_SAVE_DIR

Default: './outputs'.

Default output directory when submitting training through twinkle

TWINKLE_PER_USER_PROCESSOR_LIMIT

maximum number of processors per user on the twinkle server. Default: 20.

TWINKLE_POLL_INTERVAL

interval in seconds at which the client polls the task status. Default: 0.05.

TWINKLE_LONG_POLL_TIMEOUT

client long-polling timeout in seconds. Default: 30.

TWINKLE_AUTO_VISIBLE_DEVICES_FROM_ENV

whether twinkle automatic training uses the devices specified by CUDA_VISIBLE_DEVICES. Default: '1'.

TWINKLE_PERSISTENCE_MODE

how server state is stored. Options are 'memory' or 'redis'. Default: 'memory'.

TWINKLE_PERSISTENCE_REDIS_URL / TWINKLE_PERSISTENCE_KEY_PREFIX

Redis address and key prefix when TWINKLE_PERSISTENCE_MODE is redis.

TWINKLE_SERVER_STATE_EXPIRATION_TIMEOUT

expiration time of server state, in seconds.

TWINKLE_SERVER_STATE_CLEANUP_INTERVAL

cleanup interval of expired state, in seconds.

TWINKLE_SERVER_STATE_PER_TOKEN_MODEL_LIMIT

upper limit of the number of models that a single token (user) can create.

TWINKLE_SERVER_STATE_METRICS_UPDATE_INTERVAL

update interval of metrics, in seconds.

TWINKLE_RUN_ID

id of the current training run, set automatically by the launcher.

TWINKLE_PRINT_FORMAT

format of twinkle command-line output. Options are 'yaml' or 'json'. Default: 'yaml'.

TWINKLE_DIST_TIMEOUT_SECONDS

timeout in seconds for the twinkle local launcher to initialize the process group.