๐ Quick Migration to ms-swift 5
ms-swift 5 builds on what v4 already had and adds stronger agentic RL and training-service capabilities. Users can usually move to v5 smoothly. Some arguments are no longer supported because the training mode changed. For example, the server RL mode of v4 was removed together with its arguments. This page summarizes the main improvements of v5 over v4 and the command changes that users will notice.
๐ฆ Installation
pip install 'ms-swift>=5.0.0'Notes:
- After installing ms-swift >= 5.0.0, the v4 code can still be used by setting
USE_SWIFT_V5=0. - New models and new features are developed on v5, and the v4 code moves to maintenance mode. After a few iterations the v4 code may be removed. Since v5 is an overall improvement over v4, we recommend that users use v5.
- If your production environment uses v4 and you are concerned about incompatibilities after v5 is released, use
USE_SWIFT_V5=0, or installpip install 'ms-swift<5.0'directly.
โจ New features in ms-swift 5
๐๏ธ Training
- Ray by default: when no
--modeis given, every command runs in ray mode and this process only drives.--mode localgoes back to in-process execution (torchrun multi-process or a single-process script). Under ray,--nproc_per_nodedefaults toNPROC_PER_NODEor the number of visible devices. - Remote training with the same command:
--mode remoteconnects to the training service (twinkle-server). Only the client driver runs locally. Model loading, data encoding, training, and saving all happen on the server. Use--server_base_urland--server_api_keyto specify the service, and put the server-side model name in--model. See Server and client. - Unified backend selection:
--backend hf|megatron|unsloth. Megatron is no longer a separate command, unsloth is no longer a backend switch of the tuner, and all arguments are shared with the transformers backend. - Unified parallel layout:
--parallel_spec(for exampledp4tp2pp2) is one DeviceMesh description covering dp/fsdp/tp/pp/cp/ep/etp/vpp/sp, shared by transformers and Megatron. Auxiliary models (--ref_parallel_spec,--reference_parallel_spec,--teacher_parallel_spec,--orm_parallel_spec,--prm_parallel_spec) each declare their own placement. The transformers backend adds FSDP2 (--fsdp,--fsdp_config) and Ulysses sequence parallelism (--sequence_parallel_size). - Dynamic batching by token budget:
--dynamic_batching,--max_tokens_per_micro_batch,--micro_batch_order. The update size is still decided by the batch, DP, and gradient accumulation.--packing_algorithmselects the packing algorithm. - New optimization knobs:
--trainable_token_indices(with--tuner trainable_tokens, to learn new special tokens),--param_groups_plugins(custom parameter grouping, for example per-tower learning rates),--lorap_emb_lr,--qk_clip_enabled/--qk_clip_tau,--dp_balance,--label_smoothing_factor,--acc_strategy. - MTP training is now an explicit switch (Megatron backend):
--enable_mtp_training, with--mtp_freeze,--mtp_decoder_input_detach, and--mtp_allow_random_initcontrolling the training scope. - Pluggable on-disk data format:
--store_formatsupports arrow, jsonl, orc, and lance.--store_fieldsselects the columns to save. New formats can be added through@register_storage.
๐ฏ Online RL and distillation
- Asynchronous sampling:
--async_mode one_step_off|fully_asyncwith--max_staleness. Sampling uses a policy that lags a few versions behind. - Weight sync control:
--weight_sync_backend delta_shardedtransfers only the changed weights, and--parameter_sync_stepcontrols the publishing cadence. - Resource scheduling:
--resource_mode manual|estimate|adaptiveestimates from GPU memory or adjusts the sampling replicas dynamically during training.--rollout_num_workerssplits rollout into CPU replicas. - Process reward (PRM) channel:
--prm,--prm_weights,--prm_scorer,--prm_step_delimiter,--prm_orm_mix. Blends with the outcome reward per token in proportion. - Multi-turn, sandbox, and harness:
--tools,--max_turns,--max_trajectory_tokens,--sandbox_kindand--sandbox_*(AgentENV, OpenEnv, local workspace),--harness(codex, ms_agent, and other external agent programs),--segment_policy. See Agentic training. - New algorithms and objectives:
--rl_typeaddsopsd,mopd, andrft. GRPO variants adddro,dppo_tv,dppo_kl,geo_mean,clip_cov, andkl_cov.--enable_sampling_replayreuses the sampled tokens for training. - Mixed reward sources: each item of
--orm/--prmcan be a rule name, a reward model id, or a plugin registration name. The LoRA, template, and type of a model id are given by the accompanying lists--orm_adapters,--orm_template,--orm_model_type, and so on.--judge_templateconfigures a generative judge model.--env_reward_weightand--code_*connect environment rewards and code-sandbox rewards.
๐ Inference
--num_samples,--n_best_to_keep,--reward_threshold,--easy_query_threshold, and--normalize_rewardsmerge the candidate sampling and reward filtering of the formerswift sampleintoswift infer.--output_format all|dpoproduces SFT/evaluation data or preference (DPO) data directly. GRPO is on-policy training:swift rlsamples on its own and does not consume offline data.swift infer --sampler openai --infer_url <base_url> [--infer_api_key <key>]runs inference against any OpenAI-compatible service, symmetric withswift eval --eval_url.--store_format,--store_fields, and--store_encodedcontrol the format and columns of result files and cached datasets.
๐ Deployment
--num_replicas,--autoscaling,--max_concurrency,--ray_address,--ray_namespace,--route_prefix: the sampler scales up and down by load as Ray replicas. twinkle_client connects directly with the/api/v1prefix.--detachand--stopstart or stop the service in the background.
๐ Evaluation and export
swift eval --eval_urlwith--eval_api_keyevaluates any OpenAI-compatible service, and--result_jsonlsaves per-sample details.swift mergeis now a standalone command.--replace_if_existsreplaces--exist_okat export.--weight_transform_parallel_sizeshards the converted weights by parallel size.
๐ Remote service and TrainBench
- twinkle-server provides multi-tenant remote training, inference, and checkpoint management.
- TrainBench (formerly swift webui) has three parts: training management, AutoResearch, and workflow orchestration. See TrainBench quick start. Workflow orchestration happens on a node canvas: drag model, dataset, training, evaluation, LoRA merge, deployment, and other nodes from the left panel, connect them by data flow to form a graph, and click a node to run all of its upstream nodes and stop at that node. The output of every node can be viewed on the page, which helps with stage-level control of training and with understanding the process.
- AutoResearch hands a tuning experiment over to a model: the user only provides the original requirement, and all subsequent training and experiment design and experiment management are done automatically by the model until completion.
๐ Breaking changes
โจ๏ธ Commands
| v4 | ms-swift 5 | Notes |
|---|---|---|
swift rlhf | swift rl | rlhf remains a compatible alias |
swift merge-lora | swift merge | The old name raises an error with a hint to the new command |
swift sample | swift infer | Candidate sampling and reward filtering are merged into infer |
swift app, swift rollout | None | For remote interaction, start an OpenAI-compatible service with swift deploy and call it with the OpenAI SDK |
swift megatron pt/sft/rlhf | swift pt/sft/rl --backend megatron | Megatron is no longer a separate entry point |
swift export --merge_lora true | swift merge | Merging is the command itself |
swift sample is merged into swift infer: candidate sampling, PRM/ORM scoring, and filtering are all done by swift infer. Argument mapping: --sampler_engine becomes --sampler, --num_return_sequences becomes --num_samples, --prm_model/--orm_model become one item of the --prm/--orm list (reward model id, rule name, or plugin registration name), --prm_threshold becomes --reward_threshold, and the result file is given by --result_path. The v4 example:
swift sample --model LLM-Research/Meta-Llama-3.1-8B-Instruct --sampler_engine lmdeploy \
--num_return_sequences 5 --n_best_to_keep 2 --dataset tastelikefeet/competition_math#5 \
--prm_model AI-ModelScope/GRM-llama3.2-3B-rewardmodel-ft --orm_model mathThe ms-swift 5 form:
swift infer --model LLM-Research/Meta-Llama-3.1-8B-Instruct --sampler vllm \
--num_samples 5 --n_best_to_keep 2 --output_format dpo --dataset tastelikefeet/competition_math#5 \
--prm AI-ModelScope/GRM-llama3.2-3B-rewardmodel-ft --orm math๐ Renamed arguments
The left column is folded into the right column at parse time. Use the right column directly in new commands.
| v4 | ms-swift 5 |
|---|---|
--rlhf_type | --rl_type |
--loss_type (supervised tasks such as pt/sft) | --loss (swift rl still uses --loss_type) |
--tuner_type, --train_type | --tuner (--train_type is not in the alias table and is rejected) |
--tuner_backend | --backend (rejected, with a hint to the new argument) |
--infer_backend, --sampler_engine | --sampler |
--vllm_mode | --sampler_mode |
--use_ray | --mode ray |
--bf16, --fp16 | --torch_dtype bfloat16, --torch_dtype float16 |
--attention_backend | --attn_impl |
--lr_scheduler_type | --lr_scheduler |
--lr, --train_iters, --micro_batch_size | --learning_rate, --max_steps, --per_device_train_batch_size |
--lr_warmup_fraction, --lr_warmup_iters, --adam_eps, --clip_grad | --warmup_ratio, --warmup_steps, --adam_epsilon, --max_grad_norm |
--response_length | --max_completion_length |
--reward_funcs, --reward_weights, --prm_funcs | --orm, --orm_weights, --prm |
--prm_threshold | --reward_threshold |
--finetune (Megatron) | --resume_only_model |
--custom_register_path | --external_plugins (rejected, with a hint to the new argument) |
๐ Changed defaults
--sampler_modecan be omitted and defaults todisaggregated. The--vllm_modeof v4 was required under--use_vllm.--packing_strategydefaults tobinpackand--packing_lengthdefaults to--max_length, the same as v4. Dynamic batching is off by default.
๐ Removed arguments
Passing these arguments raises an error directly with the replacement. The full validation logic is in swift.dev.cli.legacy_coverage.
Training and fine-tuning
| Removed argument | Replacement |
|---|---|
--orm_model, --prm_model, --reward_model | Reward model id as one item of --orm/--prm |
--reward_adapters, --reward_model_type, --reward_model_revision, --reward_template | --orm_adapters, --orm_model_type, --orm_model_revision, --orm_template (PRM uses the same names with the prm_* prefix) |
--reward_model_plugin | Reward model scoring is built in. Configure --orm/--prm directly |
--use_vllm | --rollout_sampler vllm |
--vllm_server_*, --teacher_model_server, --teacher_tag_key | RL jobs start the sampler and the teacher model inside the job by --parallel_spec and no longer point to an external rollout service |
--gym_env, --use_gym_env, --multi_turn_scheduler, --completion_length_limit_scope | --sandbox_*, --max_turns, --max_trajectory_tokens, --harness |
--steps_per_generation, --num_mini_batches | --num_iterations, --per_device_train_batch_size |
--seq_kd | Express sequence-level distillation with GKD (--rl_type gkd) |
--num_generations_eval | --eval_generation_config |
--generation_config, --temperature, --max_new_tokens, --top_p, and other generation arguments | No longer accepted by training commands. Decoding for evaluation during training goes into --eval_generation_config |
--train_type, --tuner_backend, --custom_register_path | --tuner, --backend, --external_plugins |
--device_map | The model is placed by the parallel strategy at run time |
--adalora_*, --lisa_*, --lora_ga_*, --fourier_*, --boft_*, --vera_*, --reft_*, --llamapro_* | These tuners are retired. --tuner only offers lora, full, and trainable_tokens |
--torch_compile*, --accelerator_config, --auto_find_batch_size, --ds3_gather_for_generation, --use_cpu, --debug, --ddp_backend, --device_groups | No equivalent |
--max_epochs, --do_eval, --is_binary_loss_scale, --template_backend, --preserve_thinking, --disable_ignore_empty_think, --lora_dtype, --check_model, --eval_metric, --label_names, --prediction_loss_only, --disable_tqdm, --average_tokens_across_devices, --use_logits_to_keep | --num_train_epochs, --eval_strategy, --loss_scale, --enable_thinking. The rest are fixed behavior of the current path |
Inference, deployment, evaluation, export
| Removed argument | Replacement |
|---|---|
--infer_backend lmdeploy and --lmdeploy_* | --sampler only offers transformers, vllm, sglang, openai, and no |
--infer_backend client | --sampler openai --infer_url <base_url>: infer through the OpenAI interface of the service (/chat/completions). Replies are re-encoded by the local template |
--vllm_enable_lora, --vllm_max_lora_rank, --vllm_use_async_engine | Passing adapters enables LoRA automatically, and the rank is read from adapter_config.json. The async engine is decided by the engine class |
--data_range | --dataset <path>#<sample_count> |
--write_batch_size, --to_ollama, --use_swift_lora, --ignore_args_error | No equivalent |
--eval_backend, --eval_use_evalscope, --local_dataset | swift eval keeps only the native evaluator. Evaluation during training uses --eval_strategy and --eval_dataset |
--temperature, --max_new_tokens, and others of swift eval | --eval_generation_config |
--verbose, --log_level of swift deploy | The server manages its own logs |
--merge_lora, --exist_ok | swift merge, --replace_if_exists |
Checkpoint
--no_save_rng, --no_load_optim, --no_load_rng, --save_safetensors, --save_on_each_node, --use_persistent_ckpt_worker, --dist_ckpt_*, --create_checkpoint_symlink, and --use_flash_ckpt are no longer accepted. The training and export commands each reject --mcore_model/--mcore_adapter in the raw Megatron format. Convert to HF format first.
๐ Data format
The standard messages format, the rejected_response shorthand, and compatible formats such as query-response and alpaca can still be used directly. The differences are:
- The
toolscolumn is a list of tool definitions. The JSON string that v4 required is still readable. - The
contentof atool_callmessage is a{"name": ..., "arguments": ...}object (argumentsis an argument dictionary). The JSON string form is still readable. - The keys allowed per message are fixed to
role,content,loss,loss_scale, andreasoning_content. Other keys are deleted during preprocessing. - The standard way to write multimodal media is content parts inside the message
content. The top-levelimages/videos/audioscolumns are a compatible form. A row can use only one of the two. Having both raises an error. - With
rejected_messages, the negative sample does not inherit any column of the positive sample.system,tools, and media must all be written into the negative sample. Inheritance happens only when justrejected_responseis given. positive_messages/negative_messagesfor embedding and reranker are lists of conversations, and each element is one complete conversation. Only the first positive is used for training.
For details and examples see Custom datasets.
๐งฉ Plugins and Python API
- External plugins are all imported through
--external_pluginsand registered toPluginRegistryby kind. A reward rule inheritsRewardRuleand registers to therewardkind (v4 put functions into theormsdictionary). Callback, loss_scale, loss, tool, harness, sampler, and prm_scorer work the same way. For the contract see Plugins. --callbackstakes the registration name of thecallbackkind and no longer points toswift/callbacks/mapping.py.- A custom loss for
--loss_typeis now registered with@register_loss. A custom--loss_scalestrategy registers to theloss_scalekind. - The Python entry points change from the
*Argumentsand*Mainofswift.llmto the Config dataclasses ofswift.dev.configand therun_*functions ofswift.dev.recipe. Below that, twinkle components can be composed directly. See Components and MP separation. - Checkpoints are read and written by the checkpoint engine of twinkle.
--resume_from_checkpointrestores a directory written by ms-swift 5 itself. A v4 checkpoint can only be loaded for weights through--model/--adaptersand then start over.
๐ Migration example
Keep the model, data, optimization arguments, and effective batch. Change only the interface and execution configuration:
CUDA_VISIBLE_DEVICES=0 swift sft \
--model Qwen/Qwen3.5-4B \
--torch_dtype bfloat16 \
--attn_impl flash_attention_2 \
--dataset 'swift/self-cognition#600' \
--tuner lora \
--lora_rank 8 \
--lora_alpha 32 \
--target_modules all-linear \
--per_device_train_batch_size 1 \
--gradient_accumulation_steps 8 \
--learning_rate 1e-4 \
--num_train_epochs 3 \
--max_length 2048 \
--output_dir output/migrated-sftThe minimal change for online RL: --rlhf_type grpo becomes --rl_type grpo, --use_vllm true becomes --rollout_sampler vllm, --vllm_mode colocate becomes --sampler_mode colocate, and --reward_funcs/--reward_weights become --orm/--orm_weights. --beta, --num_generations, and --max_completion_length stay the same. See the example in Quick start.
The effective batch of data-parallel training is the product of the per-GPU batch, the number of data-parallel replicas, and the number of gradient accumulation steps. When switching to the remote client, the server may also shard the submitted batch. Align with the actual interface in Server and client instead of copying nproc_per_node mechanically.
โจ๏ธ From the command line to Python
MS-SWIFT 5 aims to fix the problem that the training process is hard to change and hard to understand, so we designed the training pipeline as a very simple API. Algorithm developers can use it without understanding distributed principles:
import math
from swift.dev.loss import configure_loss
from swift.dev.builder.optimizer import resolve_max_grad_norm
from swift.dev.config import (
CheckpointConfig, DatasetConfig, DistributedConfig, LoggingConfig, ModelConfig, QuantizeConfig,
TemplateConfig, TrainConfig, TunerConfig,
)
from swift.dev.recipe.configs import RecipeConfigs
from swift.dev.recipe.offline import build_offline_objects
from swift.dev.recipe.batching import grouped_training_batches
from swift.dev.recipe.utils import (
StepState, build_save_knobs, save_final_checkpoint, save_training_step,
)
# Config objects that correspond one-to-one with the command line.
model_config = ModelConfig(model='Qwen/Qwen3.5-4B', torch_dtype='bfloat16', attn_impl='flash_attention_2')
template_config = TemplateConfig(max_length=2048)
dataset_config = DatasetConfig(dataset=['swift/self-cognition#600'])
train_config = TrainConfig(num_train_epochs=3, per_device_train_batch_size=1, gradient_accumulation_steps=8,
learning_rate=1e-4)
distributed_config = DistributedConfig(mode='ray', nproc_per_node=1)
tuner_config = TunerConfig(tuner='lora', lora_rank=8, lora_alpha=32)
checkpoint_config = CheckpointConfig(output_dir='output/migrated-python')
logging_config = LoggingConfig(report_to=['tensorboard'], logging_steps=5)
# Assembly: twinkle initialize -> model -> LoRA -> loss -> optimizer -> dataset; validation happens inside.
cluster = build_offline_objects(
RecipeConfigs(
model=model_config, template=template_config, dataset=dataset_config, train=train_config,
distributed=distributed_config, checkpoint=checkpoint_config, tuner=tuner_config,
logging=logging_config, quantize=QuantizeConfig()),
recipe='run_sft', configure_loss=lambda model: configure_loss(model, loss_type='cross_entropy'),
output_dir=checkpoint_config.output_dir)
model, dataloader = cluster.model, cluster.dataloader
# Stepping and saving: StepState records loss/grad_norm/lr and triggers saving by save_steps.
state = StepState(model, train_config, gradient_accumulation_steps=train_config.gradient_accumulation_steps,
max_steps=cluster.total_opt_steps, max_grad_norm=resolve_max_grad_norm(train_config),
logging_config=logging_config, output_dir=checkpoint_config.output_dir,
save_steps=checkpoint_config.save_steps)
save_knobs = build_save_knobs(checkpoint_config, dataset_config, distributed_config, tuner_config,
output_dir=checkpoint_config.output_dir)
def save(name: str, is_final: bool = False) -> str:
state.publish_state()
return save_training_step(model, state.handler, name, save_knobs, is_final=is_final)
state.handler.on_train_begin()
# Training loop: each group of gradient_accumulation_steps batches runs one forward/backward and one parameter update.
for epoch in range(math.ceil(train_config.num_train_epochs)):
dataloader.set_epoch(epoch)
for group, batch_count in grouped_training_batches(dataloader, train_config.gradient_accumulation_steps):
state.micro_step += batch_count
state.handler.on_step_begin()
model.forward_backward(inputs=group, task=cluster.forward_task, gradient_accumulation_steps=1,
micro_batch_size=train_config.per_device_train_batch_size)
model.clip_grad_and_step(max_grad_norm=state.max_grad_norm, gradient_accumulation_steps=1)
state.handler.on_optimizer_step()
state.record()
state.step_tail(save=save)
state.handler.on_train_end()
save_final_checkpoint(model, save, enabled=True)On top of this, swift sft also has resume, evaluation during training, best-checkpoint tracking, and other logic. See swift/dev/recipe/supervised.py.
For the distributed and plugin-based design see Components and MP separation.
๐ torchrun / Ray and remote
- v5 still supports torchrun mode. For code readability, we recommend the default ray mode for training except for single-GPU training.
- The trainer, sampler, and auxiliary models of local online RL are managed by Ray.
--nproc_per_nodeis the number of processes in the training group, not the sum of the GPU counts of the training group and the sampling group. --sampler_mode disaggregatedassigns separate GPUs to the sampler.colocateuses stage scheduling on shared GPUs.--mode remoteswitches local training directly to the training service (twinkle-server), with the model and computation staying on the server.