⌨️ 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.
| Command | Purpose | Full example |
|---|---|---|
swift pt | Pretraining | Pretraining examples |
swift sft | Instruction fine-tuning and supervised tasks | SFT, Training examples |
swift rl | Preference learning, online RL, distillation | GRPO example, RL examples |
swift infer | Interactive inference, batch inference, and candidate data synthesis | Inference examples |
swift deploy | Deploy an OpenAI-compatible interface | Deployment examples |
swift eval | Model evaluation | Evaluation examples |
swift export | Model export and quantization | Export examples |
swift merge | Merge LoRA | Merge 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/mergerestore the model, template, and quantization settings by default fromargs.jsonin the--modeland--adaptersdirectories. Seeload_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
modelmodel id or local model path. Default: None. With
--mode remote, fill in the model name provided by the server.model_typemodel type. Models with the same architecture, model loading process, and template definition share one model_type. Default: None, selected automatically from the suffix of
--modeland the architectures in config.json.Note: this model_type is different from the model_type in config.json.
model_revisionmodel version. Default: None.
task_typetask 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_labelsand--problem_typeusually need to be set as well.torch_dtypedata type of the model weights. Supports
bfloat16,float16,float32. Default: None, read from config.json.attn_implattention 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_implattention implementation of the vision tower of a multimodal model. It can differ from the language tower. Default: None.
experts_implexpert implementation type of an MoE model. Options are
grouped_mm,batched_mm,eager. Default: None.enable_kernelwhether 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_tokensspecial tokens to add. Default:
[].num_labelsnumber of labels of a classification task (
--task_type seq_cls). Default: None.problem_typeproblem type of a classification task (
--task_type seq_cls). Options areregression,single_label_classification,multi_label_classification. Default: None, which meansregressionfor a reward model or when num_labels is 1, andsingle_label_classificationotherwise.rope_scalingrope type. Pass a string (
linear,dynamic,yarn) together withmax_model_lento 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_lenthe factor multiple used to compute rope when a
rope_scalingstring is passed. Default: None. When not None it overrides max_position_embeddings in config.json.max_memorymaximum GPU memory per device when weights are placed by device_map, for example
'{0: "20GB", 1: "20GB"}'. Passed through tofrom_pretrained. Default: None.local_repo_pathloading 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_kwargsextra 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_kwargsv5multimodal 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_onlybuild only the language tower of a multimodal checkpoint, for text-only training. Default: False.
init_strategyhow 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_layersnumber 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_factorMTP loss weight (mcore 0.1, RL commonly 0.2). Read only with
enable_mtp_training. Default: None.enable_mtp_trainingv5whether 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_freezev5exclude 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_detachcut 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_initallow training the MTP head with random initialization when the base model has no MTP weights. Default: False.
fp4_formatMegatron FP4 training format. Only
e2m1. Requires Blackwell and TransformerEngine>=2.7. Default: None.fp4_recipeFP4 scaling scheme. Only
nvfp4. Default:nvfp4.fp4_param_gatherparameters are also stored in FP4 and all-gathered in FP4. Requires fp4_format and the distributed optimizer. Default: False.
fp8_formatMegatron FP8 training format.
e4m3throughout, orhybrid(e4m3 forward, e5m2 backward). Mutually exclusive with FP4. Default: None.fp8_recipeFP8 scaling scheme. Options are
tensorwise,delayed(amax history),blockwise(DeepSeek FP8 checkpoint),mxfp8(Blackwell only). Default:delayed.fp8_param_gatherparameters are stored in FP8 and all-gathered in FP8. Requires the distributed optimizer. Default: False.
fp8_amax_history_lenlength of the amax history of the
delayedscheme. Default: 1024.fp8_amax_compute_algohow amax is computed. Options are
most_recent,max. Default:max.
⚙️ Data arguments
datasetlist 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 begit 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), andallto select all of them.Sample count: the full dataset is used by default.
<path>#1000means 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_datasetlist of validation set ids or paths. Default:
[].cached_datasetlist 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 splitstores input_ids, in which case export and training must set the samemax_lengthandtruncation_strategy.Sampling is supported with the syntax
<path>#<sample count>. The training type is distinguished by--template_modeand the task type by--task_type.cached_val_datasetlist of cached validation set folder paths. Default:
[].split_dataset_ratioratio of the validation set split from the training set when val_dataset is not specified. Default: 0.0, that is, no split.
data_seeddataset random seed. Default: 42.
dataset_num_procnumber 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_filewhether 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_shufflewhether 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_shufflewhether to shuffle val_dataset. Default: False.
streamingread and process the dataset in a streaming fashion. Default: False.
Note: the length of a streaming dataset cannot be obtained, so
--max_stepsmust 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_problist of sampling probabilities when combining several datasets. When set,
interleave_datasetsis used. By defaultconcatenate_datasetsis used. Does not take effect on--val_dataset. Default: None.stopping_strategystopping strategy of
interleave_datasets. Options arefirst_exhausted,all_exhausted. Default:first_exhausted.shuffle_buffer_sizeshuffle buffer size of a streaming dataset. Effective only when
dataset_shuffleis True. Default: 1000.download_modedataset download mode. Options are
reuse_dataset_if_exists,force_redownload. Default:reuse_dataset_if_exists. Set it toforce_redownloadwhen a hub dataset reports an error.columnscolumn mapping, json string, for example
'{"text1": "query", "text2": "response"}'. After mapping, the data is handled by AutoPreprocessor. Default: None.strictwhen True, a problematic row raises an error directly. Otherwise the erroneous sample is dropped. Default: False, usually used to troubleshoot errors.
remove_unused_columnswhether 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_mappingturn off automatic column-name mapping (
columnsstill 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_nameonly for the self-cognition task, and only effective for the
swift/self-cognitiondataset. Replaces{{NAME}}. Pass the Chinese and English names of the model, for example--model_name 小黄 'Xiao Huang'. Default: None.custom_dataset_infolist of json file paths for custom dataset registration. Default:
[].decision_drop_instructionsdata augmentation for the decision task. Blank out the instructions text of a sample with this probability. Default: 0.0.
decision_subsample_optionsdata 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_textdata augmentation for the decision task. Flatten a dict-form state into plain text with this probability. Default: 0.0.
decision_shuffle_fieldsdata augmentation for the decision task. Randomly shuffle the order of state fields and questions. Default: False.
use_hfcontrol 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_tokenhub token. Default: None.
trust_remote_codev5whether to execute .py scripts inside the repository (dataset script) when loading a dataset. A warning is printed once per dataset. Default: True.
packingpack 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_2to 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_lengthlength of packing. Default: None, that is,
max_length.packing_num_procnumber of packing processes. Default: 1. Different process counts give different packed datasets. Usually no need to change it.
packing_strategypacking algorithm. Options are
binpack(best-fit-decreasing, reordered by length) andsequential(order-preserving greedy, next-fit). Default:binpack.sequentialis recommended together withpacking_num_proc=1to keep the global order.lazy_tokenizewhether 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_shufflewhether the training dataloader shuffles. Default: True. Has no effect on IterableDataset (streaming datasets).
group_by_lengthgroup samples of similar length together to reduce padding, so that the load is balanced across nodes. Default: False.
data_shardingwhether to read the dataset in shards by rank. Default: False. Only effective for Megatron.
dataloader_num_workersnumber of worker processes of the dataloader. Default: None, selected automatically.
dataloader_pin_memoryDefault: True.
dataloader_persistent_workerswhether to keep worker processes across epochs. Default: True. Automatically False when
dataloader_num_workers=0.dataloader_multiprocessing_contexthow worker processes are started. Default: None, which keeps the platform default. spawn is used automatically when packing would deadlock under fork.
dataloader_prefetch_factornumber of batches prefetched by each worker process. Default: None, selected automatically.
dataloader_drop_lastwhether to drop the last incomplete batch. Default: False.
📝 Template arguments
These arguments act on encoding and are not sampler configuration. See Template.
templatechat template type. Default: None. The template of the matching model_type is selected automatically.
systemcustom 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_lengthmaximum 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_strategyhow to handle a sample that exceeds
max_length. Options aredelete,left,right,split(delete, trim on the left, trim on the right, split into several samples). Default: None, selected automatically.Note:
splitonly supports text-only pretraining datasets.Note: when a multimodal model uses
leftorright, all image_token and other multimodal tokens are kept, which may cause OOM.max_pixelsmaximum 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_templateagent 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_bboxhow bounding-box coordinates are scaled. Options are
norm1000(scale to per-mille coordinates) andnone. Default: None, selected automatically from the model.use_chat_templateuse the chat template or the generation template (for pretraining). Default: None, that is, True.
swift ptdefaults to False.padding_sidepadding direction when
batch_size>=2. Options areleft,right. Default:right. Inference defaults toleft.padding_freeflatten 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_scaleloss weight strategy for training tokens. Default:
default. RL defaults tolast_round.swift ptdefaults toall.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, agentreact/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_thinkwhether to disable the automatic addition of
ignore_empty_thinkfor 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_scalewhen loss_scale is only 0/1, express it with labels (-100) instead. Compatible with liger_kernel. Default: None, set automatically.
sequence_parallel_sizesequence 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_backendtemplate backend. Options are
swiftandjinja(transformers'apply_chat_template). Default:swift.Note: the jinja backend only supports inference, not training.
response_prefixprefix string of the response. Effective only at inference. Default: None, decided by
enable_thinkingand the template.enable_thinkingwhether 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 thanresponse_prefix.preserve_thinkingwhether 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_scaleis notlast_round.add_non_thinking_prefixwhether 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
tuneroptions are
lora,full,trainable_tokens. Default:lora. QLoRA, DoRA, and rsLoRA are switches of LoRA, not separate tuners.adapterslist 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 fromresume_from_checkpointis that it only reads the adapter weights, does not load the optimizer or the random seed, and does not skip the already-trained data.--modelis followed by the full weight directory (containing model.safetensors, tokenizer, config), and--adaptersis followed by the incremental adapter directory (containing adapter_model.safetensors).swift deploysupports--adapters name=pathto specify a service name for each adapter.freeze_llmonly effective for multimodal models. Freeze the LLM in full-parameter training. With LoRA and
target_modulesofall-linear, no LoRA is added on the LLM. Default: False.freeze_vitonly 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_aligneronly effective for multimodal models. Freeze the aligner (projector) in full-parameter training. No LoRA is added with LoRA. Default: True.
target_modulesmodules 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-linearof an LLM automatically finds all linear layers except lm_head. For multimodal LLMs, the default is to attach only on the LLM, controlled byfreeze_llm,freeze_vit, andfreeze_aligner.target_regexuse a regular expression to specify the modules the tuner attaches to. When passed,
target_modulesis ignored. Default: None.target_parameterslist of parameter names to replace with LoRA. Similar to
target_modules, but takes parameter names. Applies when MoE layers do not use nn.Linear. Requireslora_dropoutof 0. Default: None.modules_to_saveextra 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 inadapter_model.safetensors.lora_rankDefault:
8.lora_alphaDefault:
32.lora_dropoutDefault:
0.05.lora_biasoptions are
none,all.allmeans all biases are trainable. Default:none.use_rslorawhether to use RS-LoRA. Default: False.
use_dorawhether to use DoRA. Default: False.
init_weightspeft's init_lora_weights. Options are
true,false, or a strategy name (gaussian,pissa,olora, etc.).loftqandlora-gaare rejected. Default:true.lorap_lr_ratiolearning rate ratio of LoRA+ (lora_B and embedding). 10~16 is recommended. Default: None, that is, disabled.
lorap_emb_lrv5learning rate of the embedding in LoRA+. Default: 1e-6.
trainable_token_indicesv5embedding rows trained by
trainable_tokens, a common way to learn new special tokens. Default: None.
⚙️ Training arguments
learning_ratelearning rate. Default: 1e-5. LoRA training usually sets it to 1e-4.
Tip: setting
min_lrrequires--lr_scheduler cosine_with_min_lr(transformers) or Megatron'smin_lr.lr_schedulerlearning 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_kwargsother scheduler arguments, json string. Default: None.
warmup_ratioDefault: 0.0.
warmup_stepsDefault: 0.
per_device_train_batch_sizeDefault: 1.
per_device_eval_batch_sizeDefault: 1.
gradient_accumulation_stepsnumber 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_batchingv5whether twinkle plans micro-batches dynamically by token budget (the update size is still batch_size × DP × gradient accumulation). Default: False.
max_tokens_per_micro_batchv5token budget of each micro-batch with dynamic batching. Default: None.
packing_algorithmv5packing algorithm of dynamic batching. Options are
ffd,kk. Default:ffd.micro_batch_orderv5execution order of the micro-batches produced by dynamic batching. Options are
none,descending,ends_small. Default:none.max_stepsmaximum training steps. Must be set for streaming datasets. Default: -1.
num_train_epochsnumber of training epochs. Default: 3.0.
max_grad_normgradient clipping, shared by both backends. Default: 1.0.
Note: the grad_norm in the log is the value before clipping.
clip_gradalias of
max_grad_norm. Default: None.gradient_checkpointingwhether to use gradient checkpointing. Significantly lowers GPU memory usage but slows things down. Default: True.
gradient_checkpointing_kwargsarguments passed to
torch.utils.checkpoint, for example'{"use_reentrant": false}'. Default: None.vit_gradient_checkpointingwhether to enable gradient checkpointing for vit in multimodal models. Default: None.
vit_gradient_checkpointing_kwargsgradient checkpointing arguments for vit. Default: None.
optimoptimizer of the transformers backend. Default:
adamw_torch_fused. For the full list seeOptimizerNamesof transformers. The Megatron backend usesoptimizer.optim_argsextra arguments passed to the optimizer. Default: None.
weight_decayweight decay coefficient. Default: 0.1.
adam_beta1exponential decay rate of Adam's first moment. Default: 0.9.
adam_beta2exponential decay rate of Adam's second moment. Default: 0.95.
adam_epsilonAdam's epsilon. Default: 1e-8.
use_galorewhether to use GaLore (full-parameter low-rank gradient projection, transformers backend). Default: False.
galore_target_modulesmodules GaLore is applied to. Default: None, that is, attention and mlp.
galore_rankrank of GaLore. Default: 128.
galore_update_proj_gapupdate interval of the decomposition matrix. Default: 50.
galore_scalematrix weight coefficient. Default: 1.0.
galore_proj_typeGaLore matrix decomposition type. Default:
std.galore_optim_per_parameterwhether to set a separate optimizer for each GaLore target parameter (the transformers backend rejects this argument). Default: False.
galore_with_embeddingwhether to apply GaLore to the embedding. Default: False.
galore_quantizationwhether to use Q-GaLore. Default: False.
galore_proj_quantwhether to quantize the SVD decomposition matrix. Default: False.
galore_proj_bitsSVD quantization bits. Default: 4.
galore_proj_group_sizeSVD quantization group size. Default: 256.
galore_cos_thresholdcos similarity threshold for updating the projection matrix. Default: 0.4.
galore_gamma_projcoefficient that lengthens the update interval once the projection matrices are similar. Default: 2.
galore_queue_sizequeue length for computing the projection matrix similarity. Default: 5.
weight_decay_incr_stylehow weight decay changes during training. Options are
constant,linear,cosine. Default:constant. Megatron only.start_weight_decaystarting value of weight decay. Default: None.
end_weight_decayending value of weight decay. Default: None.
min_lrlower bound of the learning rate.
cosineschedule plusmin_lris equivalent tocosine_with_min_lr. Default: 0.0. Megatron only.optimizerMegatron optimizer. Options are
adam,sgd,muon,dist_muon(a sharded muon that can overlap with communication). Default:adam.muon_momentummomentum of Muon. Default: 0.9.
muon_split_qkvorthogonalize q/k/v separately. Default: True. Megatron only.
muon_use_nesterovwhether to use Nesterov momentum. Default: False.
muon_scale_modescaling mode of Muon. Options are
spectral,unit_rms_norm,shape_scaling. Default:spectral.muon_fp32_matmul_precprecision of the Newton-Schulz matmul. Options are
low,medium,high. Default:medium. Megatron only.muon_coefficient_typecoefficient type of Newton-Schulz. Default:
quintic.muon_num_ns_stepsnumber of Newton-Schulz iterations. The larger, the more precise the orthogonalization. Default: 5.
muon_tp_modeTP mode of Muon. Options are
blockwise(depends on the TP width),duplicated,distributed. Default:blockwise. Megatron only.muon_extra_scale_factorextra scaling coefficient of Muon. Default: 1.0.
muon_scalar_optimizeroptimizer that handles the parameters muon does not cover (scalars, bias, norm). Default:
adam.qk_clip_enabledv5whether 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_tauv5upper bound of the attention logit. Default: 10000.0.
sgd_momentummomentum for
optimizer=sgd. Default: 0.9.use_precision_aware_optimizerwhether to store optimizer state at a precision lower than fp32. Saves GPU memory but may change convergence. Default: False. Megatron only.
main_params_dtypemain parameter precision. Options are
fp32,fp16. Default:fp32.main_grads_dtypemain gradient precision. Options are
fp32,bf16. Default:fp32.exp_avg_dtypeAdam first moment precision. Options are
fp32,fp16,bf16,fp8. Default:fp32.exp_avg_sq_dtypeAdam second moment precision. Options are
fp32,fp16,bf16,fp8. Default:fp32.accumulate_allreduce_grads_in_fp32all-reduce gradients in fp32 during bf16 training. Consumes bandwidth but removes drift. Default: False.
optimizer_cpu_offloadput optimizer state in host memory and move it per step. Default: False.
optimizer_offload_fractionfraction offloaded to the host. Default: 1.0.
optimizer_cuda_graphcapture the optimizer step with a CUDA graph. Requires fixed shapes. Default: False.
global_batch_sizenumber 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_itersnumber of iterations per evaluation. Default: -1, that is, the whole validation set.
microbatch_group_size_per_vp_stagenumber of micro-batches grouped within a virtual pipeline stage. Default: None, chosen by Megatron.
lr_decay_styleMegatron learning rate decay style. Options are
constant,linear,cosine,inverse-square-root,WSD. Default:cosine. Derived fromlr_schedulerwhen not passed explicitly.lr_decay_itersnumber of decay iterations. Default: None, that is, the whole training process.
lr_warmup_initstarting learning rate of warmup. Default: 0.0.
lr_wsd_decay_itersnumber of iterations of the WSD decay segment. Read only with
lr_decay_style=WSD. Default: None.lr_wsd_decay_stylestyle of the WSD decay segment. Options are
exponential,linear,cosine,minus_sqrt. Default:exponential.seedglobal random seed. Default: 42.
Note: does not affect
data_seed, which controls the dataset shuffle, and vice versa.full_determinismmake training results reproducible. Lowers performance. Default: False.
use_liger_kernelwhether 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_alphanoise coefficient of neftune. Default: 0. It can usually be set to 5, 10, or 15.
dp_balancev5whether 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_coefweight of aux_loss in MoE training. Default: 0.0.
enable_dft_losswhether to use DFT loss in SFT. Default: False.
enable_channel_lossenable 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.
losssupervised 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_dimsMRL 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 withtask_type='embedding'. Default: None.acc_strategylevel at which acc is computed during training and validation. Options are
token,seq. Default:token.vit_lrlearning rate of vit in multimodal models. Default: None, equal to learning_rate. Usually used together with
--freeze_vitand--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_lrlearning rate of the aligner in multimodal models. Default: None, equal to learning_rate.
param_groups_pluginsv5extra param_groups plugins, appended after the built-in groups (vit/aligner/llm, LoRA+). Default:
[].freeze_parametersprefixes of parameters to freeze. Default:
[]. Full-parameter training only.freeze_parameters_regexregex of parameters to freeze. Default: None.
freeze_parameters_ratiofraction 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_parametersprefixes of extra trainable parameters. Default:
[].trainable_parameters_regexregex of extra trainable parameters. Default: None.
Note:
trainable_parametersandtrainable_parameters_regextake precedence overfreeze_parameters,freeze_parameters_regex, andfreeze_parameters_ratio.tf32whether to allow matmul/conv to use tf32. Default: None, which keeps the torch default.
torch_empty_cache_stepshow many steps between emptying the CUDA cache, to relieve GPU memory fragmentation. Default: None.
label_smoothing_factorlabel smoothing coefficient. 0 turns it off. Default: 0.0.
calculate_per_token_losswhether 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_layernormwhether to apply weight decay to the q/k layernorm parameters as well. Default: False.
liger_kernel_configkernel switches passed to liger, json object. Default: None.
eval_strategyevaluation strategy during training. Default: None, which follows
save_strategy, and isnowhen there is no validation set.eval_stepsevaluation interval, an integer or a ratio in (0, 1). Default: None, which follows
save_steps.eval_on_startevaluate once before training to make sure the evaluation pipeline works. Default: False.
eval_delaynumber of leading steps (or epochs) for which evaluation is skipped. Default: 0.
load_best_model_at_endreload the best checkpoint at the end of training. Default: False.
metric_for_best_modelmetric of the best model. Default: None:
losswhenpredict_with_generateis False, otherwiserouge-l(rewardfor GRPO).greater_is_betterwhether a larger metric is better. Default: None, False when the metric contains loss, True otherwise.
predict_with_generateuse generation at validation time. Default: False.
eval_datasetdataset for evaluation during training. Default:
[].eval_dataset_argsevaluation dataset arguments, json string. Default: None.
eval_limitsample count of the evaluation dataset. Default: None.
eval_generation_configgeneration configuration at evaluation time, json string. Default: None.
extra_eval_argsextra evaluation arguments, json string. Default: None.
eval_sampler_backendv5engine used by
predict_with_generate. Options aretransformers(in-process),vllm,sglang(deploy an engine on the same GPUs and sync weights, ray mode only). Default:transformers.early_stop_intervalearly stopping interval. Training stops when
metric_for_best_modeldoes not improve over this many periods (based onsave_steps). Default: None.callbacksnames of custom trainer callbacks. Default:
[].
⚙️ Distributed arguments
modehow to run. Options are
local,ray,remote. pt/sft/rl/infer/deploy/export default toray(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 toNPROC_PER_NODEor the number of visible devices.--mode localgoes back to in-process execution (torchrun multi-process or a single-process script). When--modeis 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.--modeltakes the server-side model name, and--backendspecifies the server-side engine.Note:
swift rlforcesrayfor online RL and preference learning;remotemode is the exception.nproc_per_nodev5number of processes per node (the width of the training group under ray). Default: None. With
localit is decided by the launcher. Withrayit takes theNPROC_PER_NODEenvironment variable, and the number of currently visible devices when that is not set.ray_exp_nameRay experiment name, used as the prefix of cluster and worker names. Default: None. Read only with
mode='ray'.server_base_urlv5gateway root address of twinkle-server when
mode='remote'(required, without/api/v1, which the client appends automatically). Default: None.server_api_keyv5Bearer token of the gateway when
mode='remote'. Default: None, that is, no authentication.backendv5training and inference backend. Options are
hf(transformers),megatron,unsloth. Default: None, that is, transformers.bridge_backendconversion bridge for Megatron checkpoints. Options are
mcore-bridge,megatron-bridge. Default:mcore-bridge.parallel_specv5DeviceMesh parallel layout, for example
dp4tp2pp2. Supports dp/fsdp/tp/pp/cp/ep/etp/epfsdp/vpp/sp, shared by transformers and Megatron. Default: None.deepspeedDeepSpeed configuration. Set to
zero0,zero1,zero2,zero3,zero2_offload, orzero3_offloadto use a built-in configuration, or pass the path of a custom configuration file. Default: None.zero_hpz_partition_sizeintra-node model shard size of ZeRO++. Default: None. Try
--torch_dtype float16when grad_norm NaN appears.deepspeed_autotp_sizetensor parallel size of DeepSpeed AutoTP. Requires
--deepspeedof zero0/1/2 and full-parameter training. Default: None.fsdpFSDP2 configuration. Set to
fsdp2to use the built-in configuration, or pass the path of a custom configuration file. Use either this or DeepSpeed. Default: None.fsdp_configFSDP's own configuration (wrap policy, sharding, offload), json object or file. Default: None.
ddp_timeoutcollective communication timeout (transformers backend), in seconds. Default: None.
ddp_find_unused_parametersDefault: None.
ddp_broadcast_buffersbroadcast buffers from rank 0 at every forward. Turning it off when there are no buffers can raise throughput. Default: None.
ddp_bucket_cap_mbbucket size for all-reduce. The larger, the better the communication overlap, but the first reduction comes later. Default: None.
ddp_static_graphfixed reduction order. Faster, but errors when the parameter set changes every step. Default: None.
local_rankrank of this process, set by the launcher. Default: -1.
tensor_model_parallel_sizeMegatron TP size. Default: 1.
pipeline_model_parallel_sizeMegatron PP size. Default: 1.
context_parallel_sizeMegatron CP size. Default: 1.
expert_model_parallel_sizeMegatron EP size. Default: 1.
expert_tensor_parallel_sizeTP size inside the MoE expert layers, which can differ from the dense layers. Default: 1.
sequence_parallelsequence 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_optimizerwhether to use the Megatron distributed optimizer. Default: True.
use_megatron_fsdpshard parameters with Megatron-FSDP. Requires the distributed optimizer and is incompatible with CP. Default: False.
recompute_granularityMegatron recompute granularity. Options are
selective,full,none. Default:selective.recompute_methodrecompute method for
full. Options areuniform,block. Default: None.recompute_num_layersnumber of layers per recompute block. Default: None.
recompute_modulesrecomputed submodules. Options are
core_attn,mlp,moe. Default:['core_attn'].cp_comm_typehow k/v are exchanged between CP ranks:
p2p,a2a,allgather, or a per-layer list. Default: None.cp_partition_modehow the sequence is split for CP.
zigzaggives every rank both early and late positions (load-balanced for causal attention), andcontiguousgives every rank one segment. Default:zigzag.data_parallel_sharding_strategywhat the Megatron DP optimizer shards.
optim_grads_paramsis equivalent to ZeRO-3. Default:optim_grads_params.virtual_pipeline_model_parallel_sizenumber 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_layoutexplicit assignment of layers to pipeline stages. Default: None.
decoder_first_pipeline_num_layersnumber of layers of the first pipeline stage. Default: None.
decoder_last_pipeline_num_layersnumber of layers of the last pipeline stage. Default: None.
account_for_embedding_in_pipeline_splitcount the embedding as one layer when splitting. Default: False.
account_for_loss_in_pipeline_splitcount the loss as one layer when splitting. Default: False.
overlap_grad_reduceoverlap gradient reduction with the backward. Rejected with
optimizer=muon, accepted withdist_muon. Default: False.overlap_param_gatheroverlap parameter gather with the forward. Default: False.
overlap_param_gather_with_optimizer_stepoverlap parameter gather with the optimizer step. Requires
overlap_param_gather. Default: False.overlap_p2p_commoverlap pipeline p2p communication. Default: True.
batch_p2p_commmerge the sends and receives of the pipeline into one call. Default: None, which takes the Megatron default.
align_grad_reducealign buckets so that every rank reduces at the same offset. Otherwise communication no longer overlaps. Default: True.
align_param_gathersame as
align_grad_reduce, acting on parameter gather. Default: True.tp_comm_overlapoverlap TP communication with GEMM. Requires Transformer Engine and userbuffer configuration. Default: False.
nccl_comm_warmuprun 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_fusionfuse the RoPE operator. Default: False.
bias_activation_fusionfuse bias and activation. Default: True.
bias_dropout_fusionfuse bias and dropout. Default: True.
cross_entropy_loss_fusionfuse the cross entropy. Default: True.
cross_entropy_fusion_implimplementation of the cross-entropy fusion,
nativeorte(requires Transformer Engine, faster). Default:native.gradient_accumulation_fusionfold gradient accumulation into the weight-gradient GEMM. Default: True.
masked_softmax_fusionfuse masked softmax. Default: True.
apply_dsa_kernel_fusionfuse the indexer kernel of DeepSeek sparse attention, only for models that have this indexer. Default: False.
attention_softmax_in_fp32softmax in fp32, so that long-sequence logits do not easily overflow. Default: True.
apply_query_key_layer_scalingwhether to scale q·k additionally by the number of layers (Megatron fp16 stability). Default: None, decided by Megatron.
linear_decoupled_in_projkeep the q/k/v projections as separate matrices instead of one fused weight. Default: False.
dsa_indexer_loss_coeffauxiliary loss weight of the DSA indexer. 0 means the indexer is not trained. Default: 0.0.
dsa_indexer_use_sparse_losscompute loss only on the sparsely selected part. Default: False.
use_fused_mhcuse the fused multi-head compression (MHC) kernel. Default: False.
mhc_recompute_layer_numnumber of MHC layers recomputed in the backward. Default: None, that is, no recompute.
csa_dense_moderun the CSA layer densely, to measure the cost of sparsification. Default: False.
perform_initializationwhether to initialize model parameters. Turn it off when loading a pretrained checkpoint, and on when training from scratch. Default: False.
use_cpu_initializationbuild the initial weights on CPU. Slower but saves GPU memory. Default: False.
data_parallel_random_initeach DP rank uses a different initialization seed. Only meaningful when there is no checkpoint. Default: False.
te_rng_trackertrack random numbers through Transformer Engine, so that dropout is reproducible. Default: False.
manual_gcmanual garbage collection at fixed steps, to avoid unplanned collections blocking collective communication. Default: False.
manual_gc_evalwhether to collect garbage manually at evaluation time. Default: True.
manual_gc_stepsinterval in steps of manual garbage collection. 0 disables it during training. Default: 0.
mlp_padding_freethe MLP also skips padding under
padding_free. Default: False.sequence_packing_schedulerdp_balancedbalances the token count across DP ranks, anddefault_dynamic_cpadjusts the CP split dynamically per batch. Default: None, which keeps Megatron's static behavior.megatron_extra_kwargsextra 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_coeffload-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_coeffz-loss weight, which keeps router logits small and routing stable. Default: None, that is, off.
moe_router_load_balancing_typeload-balancing strategy per layer (
aux_loss,seq_aux_loss,sinkhorn,none). Default: None, which takes the Megatron default.moe_router_dtyperouter precision. Options are
none,fp32,fp64. bf16 rounding flips discrete routing decisions. Default:fp32.moe_token_dispatcher_typetoken dispatch method.
alltoallscales with EP,allgatheronly suits small EP, andflexchooses by the situation. Default:alltoall.moe_token_drop_policythe basis for dropping tokens when expert capacity is exceeded. Options are
probs,position. Default:probs.moe_expert_capacity_factormultiple 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_capacitypad each expert's input to capacity to get static shapes. Default: False.
moe_grouped_gemmuse one grouped GEMM instead of small per-expert GEMMs. Default: True.
moe_permute_fusionfuse the expert grouping permutation into dispatch. Default: False.
moe_layer_recomputev5recompute the whole MoE layer in the backward. Default: False.
moe_enable_deepepenable 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_methodquantization 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_bitsquantization bits. Options are 1, 2, 3, 4, 8,
float8. Default: None.hqq_axisaxis of hqq quantization. Default: None.
bnb_4bit_compute_dtypebnb compute type. Options are
float16,bfloat16,float32. Default: None, equal totorch_dtype.bnb_4bit_quant_typebnb quantization type. Options are
fp4,nf4. Default:nf4.bnb_4bit_use_double_quantwhether to use double quantization. Default: True.
bnb_4bit_quant_storagebnb quantization storage type. Default: None.
✨ Generation arguments
See generation_config.
max_new_tokensmaximum number of generated tokens at inference. Default: None, no limit.
temperaturetemperature. The higher, the more randomness. Default: None, read from generation_config.json. Setting
--temperature 0or--top_k 1removes randomness.top_kkeep the top_k tokens with the highest probability. Default: None, read from generation_config.json.
top_pkeep the tokens whose cumulative probability reaches top_p. Default: None, read from generation_config.json.
repetition_penaltyrepetition penalty. 1.0 means no penalty. Default: None, read from generation_config.json.
num_beamsnumber of beams kept in beam search. Default: 1.
streamstreaming output. Default: None. True for interactive inference, False for batch inference on a dataset.
stop_wordsstop words other than eos_token. Default:
[].Note: eos_token is removed from the output. Extra stop words are kept.
logprobswhether to output logprobs. Default: False.
top_logprobsnumber of top_logprobs to output. Default: None.
structured_outputs_regexregular expression for structured output (guided decoding). Effective only with the vLLM/SGLang sampler. Default: None.
generation_configv5path 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_typealgorithm type. Options are 'dpo', 'orpo', 'simpo', 'kto', 'cpo', 'rm', 'ppo', 'grpo', 'gkd', 'opsd', 'mopd', 'rft'. Default: 'dpo'.
ref_modelid 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_adapterslist 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_typesame as model_type, acting on the reference model. Default: None.
ref_model_revisionsame as model_revision, acting on the reference model. Default: None.
ref_parallel_specv5parallel spec of the reference model (same as parallel_spec). Default: None.
betaparameter 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_lengthmaximum number of generated tokens. Default: 512.
--response_lengthon the command line is its alias. In multi-turn training, the generation length per turn is controlled bymax_new_tokens. The two are independent.label_smoothinglabel smoothing coefficient of DPO. Default: 0.
rpo_alphafrom 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_alphafrom the LD-DPO paper. Weights the logps of the part beyond the common prefix to suppress length preference. Default: None.
discopop_tautemperature parameter from the DiscoPOP paper, used to scale the log-ratio. Default: 0.05. Effective when loss_type is discopop.
loss_typeloss 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_weightsweights of each loss term when several loss_types are set in DPO training.
cpo_alphacoefficient of the nll loss in CPO/SimPO loss. Default: 1.0.
simpo_gammareward margin term in the SimPO algorithm. The paper recommends 0.5 to 1.5. Default: 1.0.
desirable_weightweight 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_weightweight of the undesirable loss in the KTO algorithm. Default: 1.0.
center_rewards_coefficientcoefficient in RM training that drives the reward model to output rewards with zero mean. See the paper. Recommended value 0.01. Default: None.
calculate_KLwhether 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_typetype of KL divergence. Options are 'reverse_kl', 'forward_kl', 'js_divergence', 'alpha_divergence'. Default: 'reverse_kl'.
f_alpha_divergence_coefv5coefficient of the alpha divergence. Default: 0.5.
reference_freewhether to train without a reference model (reference-free training). Default: False.
real_tautemperature parameter when loss_type is real. Default: 0.5.
sync_ref_modelwhether 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_specv5parallel spec of the reference model. Default: None.
🎯 PPO arguments
For the meaning of the arguments see here.
num_ppo_epochsDefault: 4.
whiten_rewardsDefault: False.
kl_coefDefault: 0.05.
cliprangeDefault: 0.2.
vf_coefDefault: 0.1.
cliprange_valueDefault: 0.2.
gammaDefault: 1.0.
lamDefault: 0.95.
lam_alphav5Default: None.
🎯 GRPO arguments
num_generationsnumber of samples per prompt, the G value in the paper. generation_batch_size must be divisible by num_generations. Default: 8.
generation_batch_sizenumber of prompts per rollout round. See the sampling arguments.
num_iterationsnumber of updates per sample, the $\mu$ value in the paper. Default: 1.
epsilonclip coefficient. Default: 0.2.
epsilon_highupper clip coefficient. Default: None. When set, it forms the clip range [epsilon, epsilon_high] together with epsilon.
deltaupper clip value of two-sided GRPO in INTELLECT-2. If set, a value greater than 1 + epsilon is recommended. Default: None.
advantage_estimatoradvantage 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_normv5coefficient of advantage normalization. Default: 1.0.
segment_discountv5discount coefficient across turns in multi-turn training. Default: 1.0.
kl_in_rewardcontrols 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_rewardsreward 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_levelgranularity 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_samplefilter out data whose within-group reward std is 0 and sample new data. Default: False.
max_resample_timesupper limit of resampling times under dynamic_sample. Default: 3.
overlong_filterskip samples truncated for being overly long. They do not take part in the loss computation. Default: False.
dro_betav5coefficient of the dro loss. Default: 0.1.
clip_ratio_cv5Default: 20.0.
clip_cov_ratiov5Default: 0.0002.
clip_cov_lbv5Default: 1.0.
clip_cov_ubv5Default: 5.0.
kl_cov_ratiov5Default: 0.0002.
ppo_kl_coefv5Default: 1.0.
dis_detach_importance_weightv5whether to detach the importance weight in the dis loss. Default: True.
log_completionswhether to record the model generations during training. Use together with
--report_to wandb/swanlab. Default: False.Tip: if
--report_to wandb/swanlabis not set, a completions.jsonl is created in the checkpoint directory to store the generations.log_entropyrecord the change of entropy during training. Default: False.
top_entropy_quantileonly 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_postemperature 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_negtemperature 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_rateFIPO Future-KL discount half-life parameter. The actual discount is
2 ** (-1 / fipo_decay_rate). Default: 32.0.fipo_clip_rangeclip range of the FIPO influence weight. Default: 0.2. No clipping when set to None or 0.
fipo_clip_high_onlywhether to clip the FIPO influence weight only to [1.0, 1.0 + fipo_clip_range]. Default: True.
fipo_safety_thresholdwhen 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_coefcoefficient of the teacher KL in OPD-RL, that is,
adv_t = base_adv + teacher_kl_coef * teacher_kl. Default: 1.0.advantage_reweightadvantage 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_modelis set, it is a frozen local teacher.rlsd_lambdaRLSD mixing weight. 0 degenerates into plain GRPO, and 1 is full reweighting. The value range is [0, 1]. Default: 0.5.
rlsd_reweight_clip_rangeevidence weight clip range.
w_tis clipped to [1 - eps_w, 1 + eps_w]. Default: 0.2.rlsd_lambda_warmup_stepsnumber of steps that warm up λ linearly from 0 to rlsd_lambda. Default: 0, no warmup.
rlsd_lambda_decay_stepsnumber of steps after warmup that decay λ linearly from rlsd_lambda to 0. Default: 0, no decay.
rlsd_negative_onlywhether to reweight only the sequences with negative advantage. Sequences with non-negative advantage keep the plain GRPO advantage. Default: False.
sdar_loss_coefcoefficient 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, whereL_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_betatemperature coefficient of the SDAR sigmoid gate. The larger, the sharper the gate. Default: 5.0.
rollout_importance_sampling_modetraining-inference mismatch correction mode. Options are 'token_truncate', 'token_mask', 'sequence_truncate', 'sequence_mask'. Default: None, correction disabled.
rollout_importance_sampling_thresholdthreshold of the importance sampling weight, used to truncate or mask extreme weights. Default: 2.0.
log_rollout_offpolicy_metricswhen 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_deltaOff-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_moderouter replay mode when training an MoE model. Options are 'disabled', 'R2', 'R3'. Default: 'disabled'.
actor_param_dtypev5storage 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_replayv5whether to enable sampling replay. Default: False.
🎯 CHORD arguments
chord_sft_datasetlist of SFT datasets used by CHORD. Same format as dataset. Default:
[].chord_sft_per_device_train_batch_sizeper-device batch size of the SFT data in CHORD. Default: None, the same as per_device_train_batch_size.
chord_enable_phi_functionwhether to enable the phi function. Default: False.
chord_mu_warmup_stepswarmup steps of mu. Default: None.
chord_mu_decay_stepsdecay steps of mu. Default: None.
chord_mu_peakpeak value of mu. Default: None.
chord_mu_valleyvalley value of mu. Default: None.
🎯 GKD arguments
lmbdaparameter 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_alphaweight of sft_loss added in GKD. The final loss is
gkd_loss + sft_alpha * sft_loss. Default: 0.gkd_logits_topkuse 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_temperaturev5distillation temperature. Default: 0.9.
sampling_temperaturev5temperature of student sampling. Default: None.
⚙️ Teacher model arguments
The teacher model arguments are used in gkd, opsd, mopd, rft, and grpo (rlsd, sdar).
teacher_modellist of teacher model ids or paths. Several teachers correspond to teacher_weights in list order. Default: None.
teacher_adapterslist 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_typesame as model_type, acting on the teacher model. Default: None.
teacher_model_revisionsame as model_revision, acting on the teacher model. Default: None.
teacher_deepspeedsame as deepspeed, acting on the teacher model. Default: None, which uses the deepspeed configuration of the training model.
offload_teacher_modeloffload 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_weightsv5list of weights of several teachers. Default: None, with equal weights for all teachers.
teacher_parallel_specv5parallel spec of the teacher model. Default: None.
auxiliary_placementv5placement 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_reversev5whether to reverse the roles of teacher and student in the opsd algorithm. Default: True.
🎯 RFT arguments
rft_num_samplesv5number of samples per prompt. Default: None, which uses num_generations.
rft_selectv5selection 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_thresholdv5threshold when rft_select is threshold. Default: 0.0.
rft_top_kv5value of k when rft_select is top_k. Default: 1.
rft_iterationsv5number of iterations. Each iteration trains on the samples selected in the previous round and then samples again. Default: 1.
rft_max_samples_per_promptv5upper 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.
ormlist 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_weightsweights of the orms. The count must match orm. Default: None, with equal weights for all rewards.
orm_adaptersv5list of adapter paths loaded by each orm. Default: None.
orm_model_typev5list of model_types of the orms. Default: None.
orm_task_typev5list of task_types of the orms. Options are 'seq_cls', 'reward_model', etc. Default: None.
orm_model_revisionv5list of model versions of the orms. Default: None.
orm_templatev5list of templates used by the orms. Default: None.
orm_parallel_specv5parallel spec of the reward model. Default: None.
prmlist of process reward sources. Same format as orm. Default:
[].prm_weightsv5weights of the prms. Default: None.
prm_adaptersv5list of adapter paths loaded by each prm. Default: None.
prm_model_typev5list of model_types of the prms. Default: None.
prm_task_typev5list of task_types of the prms. Default: None.
prm_model_revisionv5list of model versions of the prms. Default: None.
prm_templatev5list of templates used by the prms. Default: None.
prm_parallel_specv5parallel spec of the process reward model. Default: None.
prm_scorerv5scoring 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_delimiterv5delimiter that splits the steps when prm_scorer is delimiter. Default: None.
prm_orm_mixv5mixing 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_weightv5weight of the environment reward (the reward returned by the sandbox in multi-turn interaction). Default: 1.0.
judge_templatev5template used when a model serves as the judge (LLM-as-a-judge). Default: None.
🏅 cosine reward arguments
cosine_min_len_value_wrongreward value corresponding to the minimum length when a wrong answer is generated. Default: -0.5.
cosine_max_len_value_wrongreward value corresponding to the maximum length when a wrong answer is generated. Default: 0.0.
cosine_min_len_value_correctreward value corresponding to the minimum length when a correct answer is generated. Default: 1.0.
cosine_max_len_value_correctreward value corresponding to the maximum length when a correct answer is generated. Default: 0.5.
cosine_max_lenmaximum length of the generated text. Default: equal to max_completion_length.
🏅 repetition reward arguments
repetition_n_gramsn-gram size used to detect repetition. Default: 3.
repetition_max_penaltymaximum penalty value, used to control the penalty strength. Default: -1.0.
🏅 soft overlong reward arguments
soft_max_lengthL_max in the paper, the maximum generation length of the model. Default: equal to max_completion_length.
soft_cache_lengthL_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_languagev5code language. Default: 'python'.
code_timeoutv5code execution timeout, in seconds. Default: 10.
code_max_concurrencyv5maximum number of concurrent executions. Default: 8.
code_memory_limit_gbv5memory limit of each execution (GB). Default: 2.0.
code_sandbox_templatev5sandbox 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_utilizationGPU memory ratio, ranging from 0 to 1. Default: 0.9.
vllm_tensor_parallel_sizetp parallel size. Default: 1.
vllm_pipeline_parallel_sizepp parallel size. Default: 1.
vllm_data_parallel_sizedp parallel size. Default: 1.
vllm_enable_expert_parallelenable expert parallelism for MoE models. Default: False.
vllm_max_num_seqsmaximum number of sequences processed in one iteration. Default: None, which takes the vLLM default.
vllm_max_model_lenmaximum length supported by the model. Default: None, read from config.json.
vllm_disable_custom_all_reducedisable the custom all-reduce kernel and fall back to NCCL. Default: True, for stability.
vllm_enforce_eagerwhether 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_gbmultimodal 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_configspeculative decoding configuration, json string. Default: None.
vllm_disable_cascade_attnwhether 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_promptcontrol the number of multimodal inputs in a single request, for example
--vllm_limit_mm_per_prompt '{"image": 5, "video": 2}'. Default: None.vllm_quantizationvLLM quantizes the model internally. For the options see the vLLM docs. Default: None.
vllm_enable_prefix_cachingenable vLLM's automatic prefix caching, which saves the processing time of repeated query prefixes. Default: True.
vllm_reasoning_parserreasoning 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_kwargsextra vLLM arguments, json string. Default: None.
⚙️ SGLang arguments
sglang_tp_sizetp size. Default: 1.
sglang_pp_sizepp size. Default: 1.
sglang_dp_sizedp size. Default: 1.
sglang_ep_sizeep size. Default: 1.
sglang_enable_ep_moewhether to enable ep moe. Default: False.
sglang_enable_dp_attentionenable 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_staticGPU 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_lengthmaximum context length of the model. Default: None, which uses the value in the model's config.json.
sglang_disable_cuda_graphdisable the CUDA graph. Default: False.
sglang_quantizationquantization method. Default: None.
sglang_kv_cache_dtypedata 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_reducedisable the custom all-reduce kernel and fall back to NCCL. Default: True, for stability.
sglang_speculative_algorithmspeculative algorithm. Options are None, 'EAGLE', 'EAGLE3', 'NEXTN', 'STANDALONE', 'NGRAM'. Default: None.
sglang_speculative_num_stepsnumber of steps sampled from the draft model in speculative decoding. Default: None.
sglang_speculative_eagle_topknumber of tokens sampled from the draft model per step in the EAGLE2 algorithm. Default: None.
sglang_speculative_num_draft_tokensnumber of tokens sampled from the draft model in speculative decoding. Default: None.
⏱️ Scheduling and resource arguments
sampler_modeGPU 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_samplerv5inference engine used by the standalone sampling process. Options are 'vllm', 'sglang'. Default: 'vllm'.
async_modev5degree 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_generateequivalent to
--async_mode one_step_off. When set together with async_mode, the two must be consistent. Default: False.max_stalenessv5under 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_backendv5transport 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_timeoutv5time 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_stepv5interval in steps at which weights are published. 1 syncs every step. Default: 1.
sleep_levelrelease 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_optimizerwhether 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_modelwhether to offload the training model weights during rollout in colocate mode. Default: False.
resource_modev5resource 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_gpusv5total number of physical GPUs available to the whole job. Default: None, obtained from the cluster.
resource_gpu_memory_gibv5GPU memory of a single card (GiB). Default: None, which takes the smallest GPU memory visible to Ray.
resource_flex_gpusv5number of GPUs reserved at initialization for run-time role switching. Default: 0.
resource_window_stepsv5number of sliding-window steps for evaluating the GPU memory pressure of each role under adaptive mode. Default: 3.
resource_min_hold_stepsv5number of syncs to wait after moving a replica under adaptive mode. Default: 5.
resource_overridesv5explicitly override the estimation results, json string. Keys are validated before actors are built. Default: None.
rollout_num_workersv5number of Ray CPU replicas used by rollout. Episodes are routed to replicas by id. Default: 1.
generation_batch_sizenumber 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
toolsv5list of tools callable in multi-turn rollout, selected from 'tool' plugins. Default:
[].max_turnsmaximum number of turns in multi-turn training. Setting it turns on multi-turn training. Default: None, single turn.
max_trajectory_tokensv5maximum number of tokens of the whole trajectory (all turns). Default: None, no limit.
sandbox_kindv5sandbox 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_namev5name of the OpenEnv environment package, for example 'coding_env' (corresponding to
pip install openenv-coding_env). Default: None.sandbox_env_kwargsv5construction arguments of the OpenEnv environment class, json string, for example
'{"game_name": "blackjack"}'. Default: None, which uses the environment package defaults.sandbox_templatev5AgentENV template name or id. Default: None, which uses the local LocalEnv.
sandbox_workspace_rootv5root directory of the LocalEnv session workspace. Default: None, which uses a temporary directory.
sandbox_num_envsv5upper limit of the total number of sessions held at the same time across all environment replicas. Default: 1.
sandbox_num_workersv5number of Ray CPU replicas used by the sandbox environment. Each replica holds sandbox_num_envs / sandbox_num_workers sessions. Default: 1.
sandbox_session_waitv5timeout in seconds for the environment reset to wait for a free session. None waits forever, and 0 does not wait. Default: 600.
sandbox_api_urlv5address of the AgentENV service. Default: None, read from E2B_API_URL by the SDK.
sandbox_timeoutv5idle timeout in seconds of the AgentENV sandbox. Default: None, which uses the AgentEnv default.
sandbox_command_timeoutv5execution timeout in seconds of a single command. Effective for both LocalEnv and AgentEnv. Default: 60.
sandbox_memory_limit_gbv5address space limit (GB) of a single LocalEnv call. Default: 2.0.
segment_policyv5how 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'.
harnessv5name 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.
samplerinference 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/completionsrequests to the OpenAI-compatible service at--infer_url(swift deployor any OpenAI service), and replies are re-encoded by the local template, symmetric with--eval_urlof evaluation. Default: 'transformers'.infer_urlv5service address when sampler is 'openai', for example
http://127.0.0.1:8000/v1. Required.--modelis both the model name in the request and the source of the local template/tokenizer.infer_api_keyv5api_key required by the infer_url service. Default: None. Can be omitted for a local service.
max_batch_sizebatch inference size when sampler is 'transformers'. Default: 1. -1 means no limit.
val_dataset_samplesample count of the inference dataset. Default: None.
result_pathstorage 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_formatv5format of the inference results. Options are 'all' (save both inputs and outputs) and 'dpo' (save as preference data format). Default: 'all'.
store_formatv5format of the inference result file. Default: 'jsonl'.
store_fieldsv5whitelist of fields saved in the results. Default: None, which saves all fields.
metricevaluate the inference results. 'acc' and 'rouge' are currently supported. Default: None, no evaluation.
reranker_use_activationwhether to apply sigmoid after the score in reranker inference. Default: True.
engine_kwargsextra arguments passed to the sampling engine, json string. Default: None.
num_samplesv5number of candidates generated per sample, used for the subsequent reward scoring and filtering. Default: 1.
num_return_sequencessame as num_samples.
n_best_to_keepnumber of best candidates kept per sample after scoring. Default: 5.
reward_thresholdcandidates whose reward is below this value are filtered out. Default: None, no filtering.
easy_query_thresholdwhen 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_rewardsv5whether to normalize the rewards. Default: False.
score_ground_truthv5whether to score the reference answers of the dataset as well. Default: False.
orm_channel_weightv5weight of the reward channel. Default: 1.0.
batch_sizev5batch size for reward scoring. Default: 1.
max_batchesv5maximum number of batches to process, for debugging. Default: None, no limit.
num_sampling_batch_sizebatch_size of each sampling round. Default: None.
num_sampling_batcheshow many batches to sample in total. Default: None.
resumewhether to resume from an existing result_path and skip the already-processed data. Default: False.
override_exist_filewhether to overwrite when result_path already exists. Default: False.
cache_fileslist 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.
--datasetstill needs to be passed. Records in cache_files are aligned with the dataset by the md5 of the original data. Default:[].generation_strictv5whether to raise an error directly when inference fails. Default: True.
eval_humanv5enter the interactive command-line chat. Default: False.
multi_roundv5whether 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_loramerge the LoRA weights into the base model before deployment. Default: False.
hostservice host. Default: '0.0.0.0'.
portport number. Default: 8000.
api_keyapi_key required to access the service. Default: None, no validation.
ssl_keyfileSSL private key file path. Default: None.
ssl_certfileSSL certificate file path. Default: None.
served_model_namemodel name provided by the service. Default: the suffix of model.
owned_byowned_by field in the response body. Default: 'swift'.
max_logprobsmaximum number of logprobs returned to the client. Default: 20.
max_concurrencyv5maximum number of requests processed at the same time on the server side. Default: 64.
ray_addressv5address of the Ray cluster to connect to. Default: None, which uses the local Ray.
ray_namespacev5Ray namespace. Default: 'swift'.
route_prefixv5service route prefix. Default: '/v1'. twinkle_client requires '/api/v1'.
sampler_typesampler 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_replicasv5number of sampler replicas. Default: None, one replica per model.
autoscalingv5whether to scale the sampler replicas automatically by load. Default: False.
detachv5run in the background after starting the service. Default: False.
stopv5stop 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_datasetlist of evaluation dataset ids or paths. Same format as dataset.
eval_limitsample count of each evaluation set. Default: None.
eval_dataset_argsevaluation dataset arguments, json string. Arguments can be set per dataset name. Default: empty.
eval_generation_configmodel inference configuration at evaluation time, json string, for example
'{"max_new_tokens": 512}'. Default: empty.eval_output_dirstorage directory of the evaluation results. Default: 'eval_output'.
eval_num_procmaximum client concurrency at evaluation time. Default: 16.
extra_eval_argsextra evaluation arguments, json string, passed through to the evaluation backend. Default: empty.
result_jsonlv5storage path of the evaluation details (the input, output, and score of each sample). Default: None, saved to eval_output_dir.
eval_urladdress 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--modelis used as the model name in the request. Default: None, which deploys locally for evaluation.eval_api_keyv5api_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_dirstorage path of the export results, also used for
--push_to_hub. Default: 'output'.exist_okdo not raise an exception when output_dir already exists, and overwrite directly. Default: False.
merge_loramerge the LoRA weights into the base weights and save as a complete model. Default: False.
to_peft_formatsave the adapter in PEFT's directory structure, for downstream use that only uses PEFT, without merging. Default: False.
quant_methodquantization method. Options are 'gptq', 'gptq_v2', 'awq', 'bnb', 'hqq', 'eetq', 'quanto', 'fp8'. Default: None, no quantization.
to_cached_datasettokenize and export the dataset in advance, for use with
--cached_dataset. Default: False.Tip: the validation set content can be specified with
--split_dataset_ratioor--val_dataset.template_modetraining 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_encodedv5whether to save input_ids and labels when exporting the cached dataset. When saved, encoding is skipped at training time. Default: False.
store_formatv5storage format of the cached dataset. Default: 'arrow'. Options are 'jsonl' and formats registered through plugins.
store_fieldsv5columns kept in the cached dataset. Default: None, which keeps all columns produced by encoding.
to_mcoreconvert HF-format weights to Megatron format. When mcore_model is set, it means re-sharding or merging existing Megatron weights. Default: False.
to_hfconvert Megatron-format weights to HF format. Default: False.
mcore_modelpath of the Megatron-format model. Default: None.
mcore_adapterpath of the Megatron-format LoRA weights, merged into the base weights before conversion. Default: None.
thread_countnumber 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_precisionafter conversion, feed the same sample to both models and compare the outputs, to test the precision error. Default: False.
test_convert_dtypedtype used for the precision test. Options are 'float16', 'bfloat16', 'float32'. Default: 'float32'.
commit_messagecommit 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_dirstorage path of the merged model. Default: None, which uses the first adapter path plus the suffix
-merged.replace_if_existsv5whether to overwrite when output_dir already exists. Default: False.
weight_transform_parallel_sizev5see the run arguments.
💾 Save arguments
Used by swift pt/sft/rl/export.
output_diroutput directory. Checkpoints are saved under this directory. Default: 'output'.
add_versioncreate an extra
<version>-<timestamp>subdirectory under output_dir, to prevent weights from being overwritten. Default: True.save_strategysave strategy. Options are 'steps' (by steps), 'epoch' (by epochs), 'no' (do not save), and 'best' (save only the best). Default: 'steps'.
save_stepsinterval in steps between saves. It can be a float (0.5 means every half epoch). Default: 500.
save_total_limitmaximum number of checkpoints to keep. The oldest are deleted when exceeded. Default: None, no limit.
save_only_modelsave only the model weights, without the optimizer state and the random number state (resume is not possible). Default: False.
safe_serializationwhether to save in safetensors format. Default: True.
save_safetensorssame as safe_serialization.
max_shard_sizemaximum size of a single weight file. Default: '5GB'.
async_savesave checkpoints asynchronously. Default: False.
no_save_optimdo not save the optimizer state. Default: False.
no_save_rngdo not save the random number state. Default: False.
no_load_optimdo not load the optimizer state when loading a checkpoint. Default: False.
no_load_rngdo not load the random number state when loading a checkpoint. Default: False.
resume_from_checkpointcheckpoint 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_modelload only the model weights when resuming. Default: False.
ignore_data_skipdo not skip the already-trained part of the dataset when resuming. Default: False.
push_to_hubwhether to push the model to the hub. Default: False.
hub_model_idmodel_id to push, in the format
'<user name>/<model name>'. Default: None.hub_private_repowhether it is a private repo. Default: False.
hub_strategypush 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_revisionbranch to push to. Default: None.
hub_always_pushpush even when the remote already has the same content. Default: False.
load_argsread the training-time arguments from args.json in the
--model,--adapters, or--resume_from_checkpointdirectory. Default: False.load_data_argswhether 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_pluginswhether to allow loading plugins that are not in the whitelist. Default: False.
📝 Logging arguments
report_tolist of backends to report training metrics to. Options are 'tensorboard', 'swanlab', 'wandb', 'none'. Default:
['tensorboard'].logging_dirlog directory. Default: None, which uses the runs directory under output_dir.
run_nameexperiment name. Default: None, which uses output_dir.
logging_stepsinterval in steps between log records. Default: 5.
logging_first_stepwhether to log at the first step. Default: True.
logging_nan_inf_filterfilter nan and inf in the logs. Default: False.
logging_strategylogging strategy. Options are 'steps', 'epoch', 'no'. Default: 'steps'.
tensorboard_dirtensorboard log directory. Default: None.
tensorboard_queue_sizetensorboard write queue size. Default: 50.
⚙️ SWANLAB
swanlab_tokenSwanLab api-key. Can also be specified with the environment variable SWANLAB_API_KEY. Default: None.
swanlab_projectswanlab project. Default: 'ms-swift'.
swanlab_workspaceDefault: None, which uses the username of the api-key.
swanlab_exp_nameexperiment name. Default: None, which uses output_dir.
swanlab_modeoptions are 'cloud' and 'local', cloud mode or local mode. Default: 'cloud'.
swanlab_notification_methodhow to notify when training completes or an error occurs. Supports 'dingtalk', 'lark', 'email', 'discord', 'wxwork', 'slack'. See here. Default: None.
swanlab_webhook_urlwebhook url matching swanlab_notification_method. Default: None.
swanlab_secretsecret matching swanlab_notification_method. Default: None.
swanlab_smtp_serverSMTP server for email notification. Default: None.
swanlab_smtp_portSMTP port for email notification. Default: None.
swanlab_sender_emailsender email address. Default: None.
swanlab_receiver_emailreceiver email address. Default: None.
swanlab_email_languageemail language. Default: 'zh'.
⚙️ WANDB
wandb_projectwandb project. Default: 'ms-swift'.
wandb_exp_nameexperiment name. Default: None.
wandb_log_unique_promptswhether to log only unique prompts. Default: None.
▶️ Run arguments
seedglobal random seed. Default: 42. Does not affect data_seed, which controls the dataset shuffle, and vice versa.
weight_transform_parallel_sizev5parallel size for weight conversion (
--to_hf/--to_mcore). Default: 1.external_pluginslist 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_DEVICEScontrol which GPUs are used. By default all GPUs are used.
ASCEND_RT_VISIBLE_DEVICEScontrol which NPUs are used. Only effective for Ascend cards. By default all cards are used.
NPROC_PER_NODEnumber of processes per machine. The infer/export commands and training commands with
--mode localor 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.NNODESnumber of nodes in multi-node training.
NODE_RANKindex of the current node in multi-node training.
MASTER_ADDRaddress of the master node in multi-node training.
MASTER_PORTtorchrun communication port. Default: 29500.
RAY_ADDRESSRay cluster address. After this variable is set,
--mode rayconnects to that cluster directly.PYTORCH_CUDA_ALLOC_CONFrecommended to be set to
'expandable_segments:True'to reduce GPU memory fragmentation. See the torch docs.OMP_NUM_THREADSnumber of CPU threads per process. Setting it to 1 is recommended for multi-process training, to avoid thread contention.
SWIFT_SINGLE_DEVICE_MODEsingle-device mode. Options are '0' or '1'. When set to '1', each process can only see one device. Default: '0'.
⚙️ Download and cache
USE_HFdownload models and datasets from HuggingFace. Options are '0' or '1'. Default: '0', which uses ModelScope.
USE_HF_TRANSFERuse hf_transfer to speed up HuggingFace downloads. Requires hf_transfer to be installed. Default: '0'.
HF_ENDPOINTHuggingFace mirror address, for example
https://hf-mirror.com.HF_DATASETS_OFFLINE / HF_HUB_OFFLINEwhen set to '1', do not access the HuggingFace network and use only the local cache.
MODELSCOPE_CACHEModelScope cache path. Recommended to set in multi-node training, to make sure that different nodes use the same dataset cache.
MODELSCOPE_DOMAINModelScope domain. When accessing from outside China, it can be set to 'www.modelscope.ai' to use the international version.
MODELSCOPE_API_TOKENModelScope access token, used to download private models or push models. See here.
SWIFT_TIMEOUTdownload timeout in seconds for the image, video, and audio URLs in multimodal datasets. Default: 20.
📝 Logging and debugging
LOG_LEVELlog level. Default: 'INFO'. Can be set to 'WARNING', 'ERROR', etc.
LOG_ONLY_MASTERprint 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_PATCHswitch 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_PERFwhen set to '1', output the time statistics of each twinkle stage. Default: '0'.
OPENAI_API_KEYapi_key used when calling an OpenAI-compatible model service (for example LLM-as-a-judge).
🔒 Security
SWIFT_TRUST_REMOTE_PLUGINSwhen 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_PIXELSmaximum/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_PIXELSmaximum/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_NUMthe 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_SIZEnumber of adjacent tokens merged for the Qwen3-VL series. Default: 2.
ENABLE_AUDIO_OUTPUTwhether 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_INTERVALthinking token budget, whether to enable thinking, and budget interval for the thinking models of the Seed series.
GENERATIVE_RERANKER_POSITIVE_TOKEN / GENERATIVE_RERANKER_NEGATIVE_TOKENtokens 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_URLtwinkle service address. Default: 'http://127.0.0.1:8000'.
TWINKLE_SERVER_TOKENtoken for accessing the twinkle service. Default: the 'EMPTY_TOKEN' placeholder, i.e. no real token configured.
TWINKLE_SERVER_CONFIGpath of the YAML configuration file read when the twinkle server starts. Default: None.
TWINKLE_RAY_NAMESPACERay namespace used by twinkle. Default: None.
TWINKLE_TRUST_REMOTE_CODEwhether twinkle trusts remote code. When set to '0', Callable and Type inputs are rejected. Default: '1'.
TWINKLE_DEFAULT_SAVE_DIRDefault: './outputs'.
Default output directory when submitting training through twinkle
TWINKLE_PER_USER_PROCESSOR_LIMITmaximum number of processors per user on the twinkle server. Default: 20.
TWINKLE_POLL_INTERVALinterval in seconds at which the client polls the task status. Default: 0.05.
TWINKLE_LONG_POLL_TIMEOUTclient long-polling timeout in seconds. Default: 30.
TWINKLE_AUTO_VISIBLE_DEVICES_FROM_ENVwhether twinkle automatic training uses the devices specified by CUDA_VISIBLE_DEVICES. Default: '1'.
TWINKLE_PERSISTENCE_MODEhow server state is stored. Options are 'memory' or 'redis'. Default: 'memory'.
TWINKLE_PERSISTENCE_REDIS_URL / TWINKLE_PERSISTENCE_KEY_PREFIXRedis address and key prefix when TWINKLE_PERSISTENCE_MODE is redis.
TWINKLE_SERVER_STATE_EXPIRATION_TIMEOUTexpiration time of server state, in seconds.
TWINKLE_SERVER_STATE_CLEANUP_INTERVALcleanup interval of expired state, in seconds.
TWINKLE_SERVER_STATE_PER_TOKEN_MODEL_LIMITupper limit of the number of models that a single token (user) can create.
TWINKLE_SERVER_STATE_METRICS_UPDATE_INTERVALupdate interval of metrics, in seconds.
TWINKLE_RUN_IDid of the current training run, set automatically by the launcher.
TWINKLE_PRINT_FORMATformat of twinkle command-line output. Options are 'yaml' or 'json'. Default: 'yaml'.
TWINKLE_DIST_TIMEOUT_SECONDStimeout in seconds for the twinkle local launcher to initialize the process group.
🤖 Agentic Training
Multi-turn online RL - per-sample scheduling in StreamingDriver, heterogeneous placement and colocate, four kinds of env, harness, the ORM/PRM reward channels, portability across Ray and the training service, automatic resource scaling, and a complete AgentENV RL program.
📚 Custom Datasets
Pass files directly, declare a dataset_info.json, or write a custom preprocessor to connect training data, plus the standard data format for each task.