โก Quick Start
ms-swift is a one-stop LLM training framework provided by the ModelScope community. ms-swift aims to support LLM training and post-training with a concise API and to keep new models and new algorithms up to date on day 0. So far, ms-swift supports more than a thousand text-only and multimodal LLMs. It natively supports Ray-based agentic RL and can combine various harnesses and sandboxes for asynchronous reinforcement learning training.
Why ms-swift?
- Write single-machine code, train at any scale: the same code scales from a single GPU to large clusters. Distribution and sampling scheduling are driven by configuration.
- Stability and speed: supports async RL, delta sync, low-precision training, automatic scaling of the training cluster, and other techniques for efficient and stable training.
- Training techniques: natively supports PT, SFT, GRPO, PPO, OPD, MOPD, OPSD, and other supervised training, reinforcement learning, and distillation methods, and stays highly extensible for new algorithms.
- A wide range of training backends: supports training models from transformers, megatron, unsloth, sentence-transformers, and other frameworks, and can take on more model frameworks.
- Datasets: 150+ built-in task datasets, support for Data Lake formats, and dynamic addition of new datasets.
- Hardware support: in addition to NVIDIA GPU, supports AMD GPU, Ascend NPU, Kunlunxin XPU, T-Head, MetaX, Apple MPS, and other ecosystems.
- Training as a Service: deploy an API-based training service on a compute cluster. Users can connect remotely and train LLMs without a local GPU. Suits individuals and vendors who want to open up a training service.
Recommended ways to use it
- Command line: one command runs training. Supports pretraining, fine-tuning, RLHF, and agentic training, with performance optimizations built in. Suits developers with a stable training pipeline who are used to the command line. See CLI arguments.
- TrainBench AutoResearch: start from a one-sentence experiment requirement. An agent interviews you about the goal, designs the data and training plan, launches training and evaluation, and iterates against the metrics until the target is met. Suits developers who want to hand the whole experiment loop to an agent. See AutoResearch.
- TrainBench drag-and-drop orchestration: connect model, data, sampling, loss, reward, and other components on a canvas and run them. Node outputs can be inspected step by step. Suits developers who want to control every step of an algorithm or to understand how training works. See Drag-and-drop orchestration.
- Python train loop: assemble components and write the training loop directly in Python. The most customizable. The training API of ms-swift 5 does not require awareness of distribution, so the cost of understanding and coding it is not high. See Components and MP separation.
The four ways above share the same set of components. All support local training and the remote training service with the same API, so choose by your hardware. skills/swift-usage is also provided for AI coding assistants to read. It covers CLI arguments, components, custom data, plugins, Ray, server and client, and recipe entry points.
๐ฆ Environment setup and examples
The architecture of ms-swift involves the following Python packages:
- ms-swift: provides the complete LLM training toolkit. Besides command-line training, it also supports concise code-based training, which is convenient for vibe coding and experiments.
- twinkle-kit: the underlying algorithm component library, installed automatically with ms-swift.
SaaS features:
- twinkle-server: the serving framework for training. It turns every training type and model that ms-swift supports into a remote HTTP training mode.
- twinkle-client: the remote training SDK. Natively and fully supports PT, SFT, GRPO, PPO, OPD, MOPD, OPSD, and other training methods.
๐๏ธ Local training
Install ms-swift on the training machine:
pip install 'ms-swift>=5.0.0'When using the development branch, install from the respective repositories as described in Source installation.
For the full environment requirements see Installation. For starting containers see Docker. For choosing models and data sources see Models and datasets.
The training algorithms that ms-swift supports:
| Training mode | Command | Paper | Example |
|---|---|---|---|
| Pretraining | swift pt | โ | pretrain |
Supervised fine-tuning (--task_type selects chat generation [causal_lm], sequence classification [seq_cls], embedding [embedding], reranker [reranker], generative reranker [generative_reranker], or decision scoring [decision]) | swift sft | โ | train |
| DPO Direct Preference Optimization | swift rl --rl_type dpo | Direct Preference Optimization | dpo |
| ORPO preference alignment (no reference model) | swift rl --rl_type orpo | ORPO | orpo |
| SimPO preference alignment (no reference model) | swift rl --rl_type simpo | SimPO | simpo |
| KTO alignment | swift rl --rl_type kto | KTO | kto |
| CPO Contrastive Preference Optimization (no reference model: the reference-policy term in the preference term of the paper is not implemented, consistent with TRL) | swift rl --rl_type cpo | CPO | cpo |
| Reward model training | swift rl --rl_type rm | InstructGPT | rm |
| PPO Proximal Policy Optimization | swift rl --rl_type ppo | PPO | ppo |
| GRPO Group Relative Policy Optimization | swift rl --rl_type grpo | DeepSeekMath | grpo |
| RFT Rejection Sampling Fine-tuning | swift rl --rl_type rft | RFT | rft |
| GKD online distillation | swift rl --rl_type gkd | GKD | gkd |
| OPSD online self-distillation | swift rl --rl_type opsd | OPSD | opsd |
| MOPD multi-teacher online distillation | swift rl --rl_type mopd | MOPD | mopd |
Non-training features:
| Feature | Command | Example |
|---|---|---|
| Inference (interactive / batch, including the embedding, reranker, reward model, and other task heads) | swift infer | infer |
| Merge LoRA | swift merge | merge |
| Deploy an inference service (vLLM / SGLang, etc.) | swift deploy | deploy |
| Export and quantization (GPTQ / AWQ / FP8, etc.) | swift export | export |
| Evaluation | swift eval | eval |
SFT example:
# A simple sft example
CUDA_VISIBLE_DEVICES=0 \
swift sft \
--model Qwen/Qwen3.5-4B \
--dataset 'swift/self-cognition#600' \
--model_name swift-robot \
--model_author swift \
--gradient_accumulation_steps 8 \
--learning_rate 1e-4 \
--max_length 2048 \
--save_steps 100 \
--save_total_limit 2 \
--output_dir output/sftGRPO example:
# A simple grpo example
# pip install vllm math-verify
CUDA_VISIBLE_DEVICES=0,1 \
swift rl \
--rl_type grpo \
--model Qwen/Qwen3.5-4B \
--dataset 'AI-MO/NuminaMath-TIR#5000' \
--sampler_mode disaggregated \
--vllm_gpu_memory_utilization 0.8 \
--vllm_max_model_len 4096 \
--generation_batch_size 8 \
--num_generations 8 \
--max_length 2048 \
--temperature 1.0 \
--orm accuracy \
--beta 0.04 \
--gradient_accumulation_steps 8 \
--max_steps 100 \
--logging_steps 1 \
--save_steps 50 \
--output_dir output/grpoCode-based MOPD (multi-teacher distillation) example:
# A simple mopd code example
# pip install vllm
# CUDA_VISIBLE_DEVICES=0,1 python mopd.py: GPU0 trains, GPU1 runs the vLLM sampler.
import math
from swift.dev.builder import build_prompt_dataloader, resolve_rl_dp_size
from swift.dev.config import (
CheckpointConfig, DatasetConfig, DistributedConfig, ModelConfig, RLConfig, RewardConfig,
RolloutConfig, TemplateConfig, TrainConfig, TunerConfig)
from swift.dev.recipe.distill.assembly import (
DISTILL_SIGNALS, build_distill_driver, distill_group_requests, initialize_distill_cluster)
from swift.dev.recipe.distill.signal import teacher_signal
from swift.dev.recipe.batching import optimizer_batch_slices
from swift.dev.recipe.utils import (
initialize_rl_devices, prompt_rows_from_dataset, stream_batch_size)
from swift.dev.utils.scoring import copy_inputs
def main():
model_config = ModelConfig(model='Qwen/Qwen3.5-4B', attn_impl='flash_attention_2')
template_config = TemplateConfig(max_length=8192)
dataset_config = DatasetConfig(dataset=['AI-MO/NuminaMath-TIR#2000'])
train_config = TrainConfig(
max_steps=20, per_device_train_batch_size=4, learning_rate=2e-5, gradient_checkpointing=True)
# nproc_per_node = trainer GPUs; the sampler takes the GPU right after them.
distributed_config = DistributedConfig(mode='ray', nproc_per_node=1)
checkpoint_config = CheckpointConfig(output_dir='output/mopd')
generation_batch_size = 16 # prompts rolled out per batch
rollout_config = RolloutConfig(
sampler_mode='disaggregated', vllm_gpu_memory_utilization=0.8,
generation_batch_size=generation_batch_size)
# Two frozen teachers score the student's own rollouts; the weights are normalized to sum 1.
rl_config = RLConfig(
rl_type='mopd', teacher_model=['Qwen/Qwen3.5-4B', 'Qwen/Qwen3.5-9B'],
teacher_weights=[0.7, 0.3], lmbda=1.0, num_generations=1, sampling_temperature=1.0,
max_completion_length=2048)
# 1. Prompts: the rows the student rolls out on.
prompt_rows, prompts, prompt_extras = prompt_rows_from_dataset(dataset_config)
# 2. Devices: the template, the device-group plan and twinkle (Ray) itself.
template, resource_plan, teacher_meshes = initialize_rl_devices(
model_config=model_config, template_config=template_config, dataset_config=dataset_config,
train_config=train_config, distributed_config=distributed_config,
checkpoint_config=checkpoint_config, rollout_config=rollout_config, rl_config=rl_config,
reward_config=RewardConfig(), tuner_config=TunerConfig(),
output_dir=checkpoint_config.output_dir, prompt_rows=prompt_rows,
group_requests=lambda: distill_group_requests(rl_config))
# 3. Cluster: the student (LoRA), the vLLM sampler and the frozen teachers (the loop's
# teacher_signal issues their forward).
train_batch_size = train_config.per_device_train_batch_size * resolve_rl_dp_size(distributed_config)
batch_size = stream_batch_size(
colocate=False, generation_batch_size=generation_batch_size, num_generations=rl_config.num_generations,
train_batch_size=train_batch_size,
gradient_accumulation_steps=train_config.gradient_accumulation_steps)
cluster = initialize_distill_cluster(
model_config=model_config, template_config=template_config, template=template,
train_config=train_config, distributed_config=distributed_config,
checkpoint_config=checkpoint_config, rollout_config=rollout_config, rl_config=rl_config,
tuner_config=TunerConfig(), max_steps=train_config.max_steps,
signal=DISTILL_SIGNALS['mopd'], train_batch_size=train_batch_size, batch_size=batch_size,
resource_plan=resource_plan, auxiliary_meshes=teacher_meshes)
# 4. Driver: streams the student's rollouts, `batch_size` rows per batch.
dataloader = build_prompt_dataloader(
prompts, prompt_extras, seed=dataset_config.data_seed,
shuffle=dataset_config.train_dataloader_shuffle, batch_size=generation_batch_size)
driver = build_distill_driver(
cluster=cluster, rl_config=rl_config, rollout_config=rollout_config,
prompt_dataloader=dataloader, batch_size=batch_size,
num_train_epochs=math.ceil(train_config.num_train_epochs),
max_steps=train_config.max_steps * train_batch_size // batch_size)
# 5. Loop: roll out, score with the teachers, update, publish the weights to the sampler.
cluster.engine.sync_weights()
for trajs, _ in driver:
for lo, hi in optimizer_batch_slices(len(trajs), train_batch_size, 1):
update = trajs[lo:hi]
signal = teacher_signal(cluster, update, True)
cluster.model.forward_backward(
inputs=copy_inputs(update), gradient_accumulation_steps=1,
micro_batch_size=train_config.per_device_train_batch_size, **signal)
cluster.model.clip_grad_and_step(
max_grad_norm=train_config.max_grad_norm, gradient_accumulation_steps=1)
print(cluster.model.calculate_metric(is_training=True))
cluster.engine.sync_weights()
driver.close()
if __name__ == '__main__':
main()๐ Deploying the training service
pip install twinkle-server ms-swiftNote that twinkle-server is dedicated infrastructure for serving training. It is different from swift deploy, which is the sampling service command provided by ms-swift.
The training model and the sampling engine are both described by the server_config.yaml below:
http_options:
host: 127.0.0.1
port: 8000
persistence:
mode: memory
applications:
- name: server
route_prefix: /api/v1
import_path: server
args:
supported_models:
- google/gemma-4-E4B-it
- name: models-gemma-4-E4B-it
route_prefix: /api/v1/model/google/gemma-4-E4B-it
import_path: model
args:
backend: transformers
model_id: ms://google/gemma-4-E4B-it
model_loader: swift.dev.model.loader:build_model_loader
train_mode: lora
min_replicas: 1
nproc_per_node: 1
max_length: 2048
device_group:
name: model
ranks: 1
device_type: cuda
device_mesh:
device_type: cuda
dp_size: 1
- name: sampler-gemma-4-E4B-it
route_prefix: /api/v1/sampler/google/gemma-4-E4B-it
import_path: sampler
args:
model_id: ms://google/gemma-4-E4B-it
sampler_type: vllm
nproc_per_node: 1
engine_args:
max_model_len: 4096
gpu_memory_utilization: 0.5
enable_lora: true
device_group:
name: sampler
ranks: 1
device_type: cuda
device_mesh:
device_type: cuda
dp_size: 1Start Ray and the service:
CUDA_VISIBLE_DEVICES=0,1 ray start --head --num-gpus=2
# TWINKLE_WORKER_SETUP_HOOK registers the swift template into twinkle-server
TWINKLE_WORKER_SETUP_HOOK=swift.dev.builder.server_plugin:register twinkle-server launch --config server_config.yaml๐ก Client for remote training
The client needs twinkle-client to connect to the service, and ms-swift for its dataset, template configuration, and reward functions:
pip install twinkle-client ms-swiftSave the following code as client_grpo.py. The dataset, template, and reward all come from ms-swift: prompt_rows_from_dataset reads the grpo view of GSM8K (answers kept in the solution column) and packs it into user_data. configure_remote_processor sends the TemplateSpec of ms-swift to the model service. set_template pins the same spec to the sampler, so training and sampling encode identically. MathAccuracy scores against solution. On every turn, the current weights are first published to the sampler, then sampling and scoring run, the advantage is obtained by group normalization, and finally the update runs:
import os
from peft import LoraConfig
from twinkle_client import init_twinkle_client
from swift.dev.builder import build_prompt_dataloader, resolve_twinkle_template
from swift.dev.builder.remote import configure_remote_processor
from swift.dev.config import DatasetConfig, DistributedConfig, ModelConfig, TemplateConfig
from swift.dev.recipe.utils import prompt_rows_from_dataset
from swift.dev.reward.rules import MathAccuracy
MODEL_ID = 'google/gemma-4-E4B-it'
NUM_GENERATIONS = 4 # completions per prompt
MAX_STEPS = 20
model_config = ModelConfig(model=MODEL_ID)
# The swift template for gemma-4 E2B/E4B; the server rebuilds it from the same spec, so training and sampling encode identically.
template_config = TemplateConfig(template='gemma4_nothinking', max_length=2048)
with init_twinkle_client(
base_url=os.environ.get('TWINKLE_SERVER_URL', 'http://127.0.0.1:8000'),
api_key=os.environ.get('TWINKLE_SERVER_TOKEN'),
) as client:
# 1. Prompts: math problems; the reference answer travels in user_data['solution'] for the reward.
_, prompts, prompt_extras = prompt_rows_from_dataset(
DatasetConfig(dataset=['modelscope/gsm8k:grpo'], dataset_shuffle=False))
dataloader = build_prompt_dataloader(prompts[:2000], prompt_extras[:2000], seed=42, batch_size=8, shuffle=False)
# 2. Model: LoRA student with the GRPO loss; the dev Template + InputProcessor are rebuilt server-side.
model = client.model(MODEL_ID)
model.add_adapter_to_model(
'default', LoraConfig(r=8, lora_alpha=32, target_modules='all-linear'), gradient_accumulation_steps=1)
configure_remote_processor(model, template_config, model_config, DistributedConfig())
model.set_loss('GRPOLoss', epsilon=0.2, beta=0.0)
model.set_optimizer('Adam', lr=2e-5)
# 3. Sampler: the vLLM engine the student rolls out on, pinned to the same dev TemplateSpec.
sampler = client.sampler(MODEL_ID)
sampler.set_template(**resolve_twinkle_template(template_config, model_config))
reward_fn = MathAccuracy()
sampling_params = {'max_tokens': 1024, 'temperature': 1.0, 'top_p': 0.95}
try:
for step, prompt_batch in enumerate(dataloader):
if step >= MAX_STEPS:
break
# 4. Publish the current weights to the sampler.
weights = model.save(name='grpo-weights', save_optimizer=False, is_sampler=True).twinkle_path
# 5. Roll out NUM_GENERATIONS completions per prompt.
responses = sampler.sample(
inputs=prompt_batch, sampling_params=sampling_params, adapter_uri=weights,
num_samples=NUM_GENERATIONS)
sequences = [seq for response in responses for seq in response.sequences]
samples = [seq.new_input_feature for seq in sequences]
old_logps = [[lp[0][1] for lp in seq.logprobs] for seq in sequences]
# 6. Reward each completion, then normalize inside its group.
rewards = reward_fn(samples)
advantages = []
for i in range(0, len(rewards), NUM_GENERATIONS):
group = rewards[i:i + NUM_GENERATIONS]
mean = sum(group) / len(group)
std = (sum((r - mean)**2 for r in group) / len(group))**0.5
advantages += [(r - mean) / (std + 1e-4) for r in group]
# 7. Update.
model.forward_backward(inputs=samples, advantages=advantages, old_logps=old_logps)
model.clip_grad_and_step(max_grad_norm=1.0)
print(step + 1, model.calculate_metric().result)
checkpoint = model.save('quick-start-grpo', save_optimizer=True)
print(checkpoint.twinkle_path)
finally:
model.close()Run:
python client_grpo.pytwinkle-server also supports the tinker syntax. See the tinker cookbook.
๐ Learn more
- Online RL: the GRPO principle, rewards, and sampling scheduling.
- Components and MP separation: reusing components and modifying the training loop.