ms-swift

modelscopeApache-2.0活跃维护 有专家点评

一站式大模型训练框架,支持 600+ 纯文本大模型和 300+ 多模态大模型的 CPT、SFT、DPO、GRPO 等训练,可用 LoRA 等 PEFT 方式或全参数微调。

Use PEFT or Full-parameter to CPT/SFT/DPO/GRPO 600+ LLMs (Qwen3.8, DeepSeek-V4, GLM-5.1, InternLM3, Llama4, ...) and 300+ MLLMs (Qwen3-VL, Qwen3-Omni, InternVL3.5, Ovis2.5, GLM5.3, Gemma4, Llava, Phi4, ...) (AAAI 2025).

v4.6.0发布于 2026-10-13 13:30 UTC16,081star +23 / 7 天1,793fork同步于 2026-11-11 05:24 UTC

专家点评

上手难度:进阶更新于 2026-11-11

一个仓库覆盖 600+ LLM 与 400+ 多模态模型的 SFT/DPO/GRPO 训练到量化部署,省掉自己拼 PEFT+并行+推理后端

适用场景

  • 需要在一套代码里同时跑 CPT/SFT/DPO/GRPO 且模型清单横跨 Qwen、DeepSeek、GLM、InternLM 多个系列:直接换模型名即可,自己拼 trl+peft+deepspeed 时每换一个模型架构就要改 collator 和 chat template
  • 多模态微调(图文、音视频、Omni 类):它的模型覆盖里 MLLM 和纯文本是同一套训练入口,自己搭时视觉塔冻结策略、processor 对齐、多模态数据打包都要重写
  • 用 Megatron 的 TP/PP/CP/EP 跑 MoE 大模型:省掉自己写并行切分和 checkpoint 转换,代价是要额外装 Megatron 后端
  • 训练完要立刻在同一仓库里做 vLLM/SGLang/LMDeploy 推理和 AWQ/GPTQ/FP8 量化验证:链路是通的,不用在训练框架和推理框架之间手工搬权重格式
  • 非 NVIDIA 卡(昇腾 NPU、MI300、MUSA)上做微调:这是它相对多数同类框架的实际差异点,别处基本只有 CUDA 路径

踩坑

  • 多模态 + GRPO + vLLM 这条组合路径上,issue 里反复出现 multimodal cache 相关的 assert 报错(Expected a cached item for {mm_hash=}),说明多模态 RL 训练与推理后端之间的缓存对齐还没完全收敛;打算走这条路线的话,先按官方示例跑通最小配置再上自己的数据
  • 显存问题在 issue 里被反复提出(Qwen3.5 训练显存过高一类标题),README 里“7B 量化训练 9GB 显存”是特定配置下的数字,不要按它反推你的 batch size 和序列长度;MoE 模型的实际占用和稠密模型不是一回事
  • 安装门槛不在 pip install ms-swift 本身:Python 3.12、PyTorch ≥2.0、modelscope ≥1.23 是硬前置,Megatron/vLLM/SGLang/LMDeploy 各自要单独装且版本互相牵制,撞上的时机通常是你想开并行或换推理后端的时候,而不是第一次跑 SFT 的时候

同类对比

LLaMA-Factory 在纯文本 SFT/DPO 的配置化程度上更轻,模型覆盖和多模态广度不如它;只做 RL 后训练可以看 verl,它把 rollout 和训练解耦得更彻底。要极致控制训练循环、不介意自己维护模型适配层的话,直接 peft+trl+deepspeed 组合反而更少黑盒。

怎么上手

由 README 提炼,执行前请确认
pip install ms-swift
硬件要求按 README 说明

支持 NVIDIA GPU(A100/H100/RTX 等,CUDA)、AMD MI300 系列(ROCm)、华为昇腾 NPU、沐曦与摩尔线程 GPU(MUSA),以及 Apple MPS 和 CPU;README 称 7B 模型量化训练仅需 9GB 显存。

支持 Apple Silicon需要 CUDA支持 ROCm / AMD昇腾 / Ascend多卡 / 张量并行
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

ModelScope 出的大模型与多模态模型微调部署框架,覆盖训练到量化全流程

一站式大模型训练框架,支持 600+ 纯文本大模型和 300+ 多模态大模型的 CPT、SFT、DPO、GRPO 等训练,可用 LoRA 等 PEFT 方式或全参数微调。

核心能力

  • 支持 600+ 纯文本与 400+ 多模态模型的训练推理部署
  • 内置 LoRA、QLoRA、DoRA 等轻量微调方法
  • 集成 GRPO、DAPO、GSPO 等强化学习算法族
  • 用 Megatron 的 TP/PP/CP/EP 并行加速 MoE 训练
  • 支持 vLLM、SGLang、LMDeploy 推理加速与 AWQ/GPTQ/FP8 量化

容易踩的坑

需 Python 3.12、PyTorch ≥2.0、modelscope ≥1.23;部分训练与推理能力依赖额外后端(如 Megatron、vLLM、SGLang、LMDeploy)需另行安装;模型与数据集需从 ModelScope 下载。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v4.6.0
  1. v4.6.0最新正式版2026-10-13 · 2026-10-13 13:30 UTC

    v4.6.0

    JEV Support (typed-decision / System-1)

    • Added the decision task type for JEV-style decision models: instead of generating text, the model returns calibrated probabilities over each question's fixed option set (choice / score / noul) in a single forward pass. (#10306)
    • Ready-to-use recipes for three released decision models — JEV-27B-VL, Clef and OmniJev — covering training, inference and LoRA merge/export. Any CausalLM can also be converted with swift sft --task_type decision.
    • Details: Decision (Best Practices) · examples

    New Models

    • MiniCPM5 (1B / 2B) — LLM series with base and SFT variants, vLLM inference supported.
    • MiniCPM-V-4.7 (1B / 35B-A3B) — vision-language models with image and video support.
    • GLM-5.3-Flash — ZhipuAI GLM-5.3-Flash with vision and video support.
    • DeepSeek-V4.1-Flash — full-parameter SFT & GRPO on Megatron-SWIFT plus vLLM inference.
    • Xing4.0-29B-A4B — MLA + MoE + mHC; LoRA & full-parameter SFT (DDP / DeepSpeed ZeRO-3) with grouped_mm expert acceleration (~3.7x).
    • MonkeyOCRv2 (S / B) — OCR and document-understanding models.

    New Features & Compatibility

    • Added a Moore Threads (MUSA) backend via torchada. (#10224)
    • Compatibility: transformers ≥ 5.17 kernel proxy, vLLM 0.28+ colocate weight sync / wake-up API, and TRL optional-dependency checks under Transformers 5. (#9770, #10311, #10315)
    • Updated qwen4_exp / glm5_next MTP examples with GLM-5.3 support. (#10219)

    Security

    • Hardened the WebUI and rollout: fixed unauthenticated RCE and arbitrary file read, a rollout-side vulnerability, and GitHub Actions workflow injection. (#10209, #10218, #10226, #10227)
    • Authenticate before request-body deserialization; weights_only=True for Megatron checkpoint loading; download security fixes. (#10062, #10066, #10234, #10235)

    Training & RL

    • Loss & gradient alignment across SP, DPO, DAPO/CISPO/FIPO and GKD/GRPO (including Liger and off-policy paths); listwise reranker and partial gradient-accumulation fixes. (#9977, #10100, #10104, #10116, #10130, #10144, #10185, #10244, #10285)
    • Megatron & parallelism: contiguous CP token order, ring-padding handling in output unpacking / packed seq_acc / MoE aux loss, mcore checkpoint metadata. (#10071, #10113, #10181, #10182, #10184, #10242)
    • Training stability: ZeRO-3 hooks after generation errors, GaLore checkpointing, LISA init and layer selection, SP sampler options, CPU-offload activation views. (#10132, #10140, #10157, #10161, #10173, #10260)
    • RLHF & rollout: colocate offload / vLLM wake-up ordering, async rollout failure propagation, IPC bucket acknowledgment, vLLM LoRA metadata and local-teacher adapters. (#10092, #10107, #10109, #10207, #10231, #10232)
    • Embedding & reranker: InfoNCE negative sampling and gradient compensation under DDP / Megatron DP, DP metric gathering, WeMM duplicate forward. (#10059, #10068, #10069, #10081, #10088, #10091, #10150)

    Inference & Deployment

    • Fixed qwen-omni vLLM inference, video metadata handling after frame sampling, and video_second_per_grid tensor handling. (#10168, #10274, #10330)
    • infer: adapter-cache and async-request isolation, independent event-loop thread, streamed-request completion, worker error propagation, SSE heartbeats. (#10080, #10086, #1009
  2. v4.5.32026-09-08 · 2026-09-08 13:00 UTC
    查看更新说明

    New Models

    New Features

    • Megatron-SWIFT Muon optimizer supports different learning rates for different parameters.
    • OPD distillation (GRPO) now supports separate vision inputs for teacher and student, enabling multimodal distillation. Reference doc: https://swift.readthedocs.io/en/latest/Instruction/Distillation.html
    • A last-checkpoint link is maintained when saving checkpoints, making resume easier.
    • dataloader_persistent_workers now defaults to True to avoid dataloader cold start on each eval.
    • Performance: vectorized padding-free log-prob restore and sequence reductions; Megatron loss all-reduce deferred to logging time; vectorized ring attention LSE extraction on NPU.
    • Added the vllm_kunlun inference backend for rollout/deploy.
    • Removed the gradio dependency.

    Bug Fixes

    • Training: resume_from_checkpoint with transformers 4.x, DPO/IPO log-prob normalization, reward model margins aligned with pairs, predict_with_generate DDP evaluation, loss scaling with sequence parallelism, vocab loss & external files in multi-processing, template pickling, py3.14 compatibility, etc.
    • RL: Megatron GRPO vocab-parallel log-prob gradients, vLLM weight sync in colocate mode (LoRA IndexError, sender device alignment), colocated vLLM cleanup ordering on rollout failures, token-in/token-out consistency in agentic multi-step rollouts.
    • Megatron: router replay CP partition and expert indices, MTP shared weights forward, reference adapter loading, zero multimodal learning rates, Megatron-FSDP DTensor checkpoint save/load, etc.
    • Model fixes: Qwen3.5 (linear attention FP32 weights, multimodal packing kwargs), Qwen-Omni video fps, MiniCPM-o 4.5 video inputs, mplug_owl2_1, etc.

    What's Changed

  3. v4.5.22026-08-16 · 2026-08-16 02:44 UTC
    查看更新说明

    Bug Fixes

    • Fixed: Corrected the incorrect size configuration for Qwen3.8-35B-A3B, which was mistakenly copied from the previous Qwen3.5/3.6 series during development. We apologize for the confusion and inconvenience this caused. Thanks to the community for reporting this issue.
  4. v4.5.02026-08-14 · 2026-08-14 17:07 UTC
    查看更新说明

    New Models

    Qwen3.8

    Qwen3.8, the strongest open Qwen generation so far. Same Gated DeltaNet hybrid backbone as Qwen3.5/3.6, native vision/video, hybrid thinking on by default, plus tunable reasoning effort and preserved historical thinking. (#9914)

    NVIDIA Nemotron 3.5 Lightning

    Nemotron 3.5 Lightning 30B-A3B: hybrid Mamba-2 + MoE + Attention, 30B total / 3B active, 1M context, MTP. (#9894)

    Muse Glimmer

    Muse-Glimmer-30B, Meta’s 30B dense multimodal model distilled from Muse Spark for local agents. (#9887)

    Other changes

    • MiMo-V2.5 inference (vLLM / SGLang) (#9880)
    • DeepSeek-V4-Flash-0731 adaptation (#9834)
    • Thinking-prefix loss scale (#9875)
    • OpenAI / Anthropic message processors (#9809)

    What's Changed

  5. v4.4.3Patch release v4.4.32026-08-12 · 2026-08-12 03:39 UTC
    查看更新说明

    What's Changed

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    SWIFT (Scalable lightWeight Infrastructure for Fine-Tuning)

    📖 Table of Contents

    ☎ Groups

    You can contact us and communicate with us by adding our group:

    Discord GroupWeChat Group

    📝 Introduction

    🍲 ms-swift is a large model and multimodal large model fine-tuning and deployment framework provided by the ModelScope community. It now supports training (pre-training, fine-tuning, human alignment), inference, evaluation, quantization, and deployment for 600+ text-only large models and 400+ multimodal large models. Large models include: Qwen3, Qwen3.5, InternLM3, GLM4.5, Mistral, DeepSeek-R1, Llama4, etc. Multimodal large models include: Qwen3-VL, Qwen3-Omni, Kimi-K3, Llava, InternVL3.5, MiniCPM-V-4, Ovis2.5, GLM4.5-V, DeepSeek-VL2, etc.

    🍔 In addition, ms-swift integrates the latest training technologies, including Megatron parallelism techniques such as TP, PP, CP, EP to accelerate training, as well as numerous GRPO algorithm family reinforcement learning algorithms including: GRPO, DAPO, GSPO, SAPO, CISPO, RLOO, Reinforce++, etc. to enhance model intelligence. ms-swift supports a wide range of training tasks, including preference learning algorithms such as DPO, KTO, RM, CPO, SimPO, ORPO, as well as Embedding, Reranker, and sequence classification tasks. ms-swift provides full-pipeline support for large model training, including acceleration for inference, evaluation, and deployment modules using vLLM, SGLang, and LMDeploy, as well as model quantization using GPTQ, AWQ, BNB, and FP8 technologies.

    Why Choose ms-swift?

    • 🍎 Model Types: Supports 600+ text-only large models, 400+ multimodal large models, and All-to-All full modality models from training to deployment full pipeline, with Day-0 support for popular models.
    • Dataset Types: Built-in 150+ datasets for pre-training, fine-tuning, human alignment, multimodal and various other tasks, with support for custom datasets. Users only need to prepare datasets for one-click training.
    • Hardware Support: Supports NVIDIA GPUs (A100/H100/RTX series, etc., via CUDA), AMD GPUs (MI300 series, etc., via ROCm), domestic hardware such as Huawei Ascend NPU, MetaX GPU and Moore Threads GPU (via MUSA), as well as Apple MPS and CPU.
    • Lightweight Training: Supports lightweight fine-tuning methods such as LoRA, QLoRA, DoRA, LoRA+, LLaMAPro, LongLoRA, LoRA-GA, ReFT, RS-LoRA, Adapter, LISA, etc.
    • Quantized Training: Supports training on BNB, AWQ, GPTQ, AQLM, HQQ, EETQ quantized models, requiring only 9GB training resources for 7B models.
    • Memory Optimization: GaLore, Q-Galore, UnSloth, Liger-Kernel, Flash-Attention 2/3, and Ulysses and Ring-Attention sequence parallelism techniques support, reducing memory consumption for long-text training.
    • Distributed Training: Supports distributed data parallelism (DDP), device_map simple model parallelism, DeepSpeed ZeRO2 ZeRO3, FSDP/FSDP2, and Megatron distributed training technologies.
    • 🍓 Multimodal Training: Supports multimodal packing technology to improve training speed by 100%+, supports mixed modality data training with text, images, video and audio, and supports independent control of vit/aligner/llm.
    • Agent Training: Supports Agent templates, allowing one dataset to be used for training different models.
    • 🍊 Training Tasks: Supports pre-training and instruction fine-tuning, as well as training tasks such as DPO, GKD, KTO, RM, CPO, SimPO, ORPO, and supports Embedding/Reranker and sequence classification tasks.
    • 🥥 Megatron Parallelism: Provides TP/PP/SP/CP/ETP/EP/VPP parallel strategies to significantly boost MoE model training speed. Supports full-parameter and LoRA training methods for 300+ pure text large models and 100+ multimodal large models. Supports CPT/SFT/GRPO/DPO/KTO/RM training tasks.
    • 🍉 Reinforcement Learning: Built-in rich GRPO family algorithms, including GRPO, DAPO, GSPO, SAPO, CISPO, CHORD, RLOO, Reinforce++, etc. Supports synchronous and asynchronous vLLM engine inference acceleration, with extensible reward functions, multi-turn inference Schedulers, and environments through plugins.
    • Full-Pipeline Capabilities: Covers the entire workflow of training, inference, evaluation, quantization, and deployment.
    • UI Training: Provides Web-UI interface for training, inference, evaluation, and quantization, completing the full pipeline for large models.
    • Inference Acceleration: Supports Transformers, vLLM, SGLang, and LmDeploy inference acceleration engines, providing OpenAI interfaces for accelerating inference, deployment, and evaluation modules.
    • Model Evaluation: Uses EvalScope as the evaluation backend, supporting 100+ evaluation datasets for evaluating text-only and multimodal models.
    • Model Quantization: Supports quantization export for AWQ, GPTQ, FP8, and BNB. Exported models support inference acceleration using vLLM/SGLang/LmDeploy.

    🎉 News

    • 🔥 2026.10.29: Day-0 Support for NVIDIA-Nemotron-3.5-Transcribe, Refer to the SFT examples.
    • 🔥 2026.10.22: Support EntroPack flexible bitrate model quantization, enabling fine-grained control of the model's bitrate based on the VRAM budget, with support for Transformers inference and LoRA training. See the best practices and the QLoRA example.
    • 🔥 2026.10.19: Support for EmbeddingGemma-2 (740M, multimodal embedding model, unifying text/image/video/audio in a single 768d vector space). Inference and training verified with infonce loss fine-tuning.
    • 🔥 2026.10.15: Day-0 Support for NVIDIA-Nemotron-3.5-Super-VL-120B-A12B, Refer to the SFT examples.
    • 🔥 2026.10.13: Support for training and inference of decision models (typed-decision System-1 scoring models) via --task_type decision, which performs a single forward pass and outputs calibrated probabilities over each question's option set. Supports JEV-27B-VL, Clef, OmniJev and Kev (0.8b/4b/9b), with proper scoring rule losses (distill_rps, smooth_brier, ce_rps). Refer to the documentation and examples.
    • 🔥 2026.10.01: Support for Xing4.0-29B-A4B: transformers-backend training and inference, with LoRA & full-parameter SFT on single/multi-GPU (DDP & DeepSpeed ZeRO-3) and grouped_mm expert acceleration (~3.7x). Refer to the examples.
    • 🔥 2026.09.21: Support for DeepSeek-V4.1-Flash: Megatron-SWIFT full-parameter training (SFT and GRPO) plus vLLM inference. Refer to the examples.
    • 🔥 2026.09.01: Support inference and training for the Tencent Hunyuan multimodal embedding model WeMM-Embedding (2B/4B/9B), supporting image-text mixed input for vector representation. Refer to embedding example.
    • 🔥 2026.08.26: Day-0 Support for Qwen3.8-Flash-Next, refer to sft example for training.
    • 🎁 2026.08.21: Support inference and training for the OpenMOSS multimodal model MOSS-VL-Instruct-0708, with LoRA and full-parameter fine-tuning, covering single/multi-image, single/multi-video and mixed-media scenarios.
    • 🎁 2026.08.11: Support inference and training for the multimodal model Muse-Glimmer-30B, with Megatron-SWIFT support as well.
    • 🎁 2026.07.22: Support inference for the moonshotai multimodal model Kimi-K3, including the XTML chat template, thinking channel (reasoning_effort) and tool calling (--agent_template kimi_k3).
    • 🎁 2026.06.10: Megatron-Ray now supports GRPO and GKD training. See docs and examples.
    • 🎁 2026.03.03: ms-swift v4.0 major version is officially released. For release notes, please refer to here. You can provide your suggestions to us in this issue. Thank you for your support.

    🛠️ Installation

    To install using pip:

    pip install ms-swift -U
    
    # Using uv
    pip install uv
    uv pip install ms-swift -U --torch-backend=auto
    

    To install from source:

    # pip install git+https://github.com/modelscope/ms-swift.git
    
    git clone https://github.com/modelscope/ms-swift.git
    cd ms-swift
    # The main branch is for swift 4.x. To install swift 3.x, please run the following command:
    # git checkout release/3.12
    pip install -e .
    
    # Using uv
    uv pip install -e . --torch-backend=auto
    

    Running Environment:

    RangeRecommendedNotes
    python>=3.103.12
    cudacuda12.8/13.0No need to install if using CPU, NPU, MPS
    torch>=2.02.8.0/2.11.0
    transformers>=4.334.57.6/5.12.1
    modelscope>=1.23
    datasets>=3.0,<4.8.53.6.0/4.8.4
    peft>=0.11,<0.21
    flash_attn2.8.3/4.0.0b15
    trl>=0.15,<1.00.29.1RLHF
    deepspeed>=0.19.3,<0.200.19.7Training
    vllm>=0.5.10.11.0/0.23.0Inference/Deployment
    sglang>=0.4.6Inference/Deployment
    evalscope>=1.0Evaluation
    gradio5.32.1Web-UI/App

    For more optional dependencies, you can refer to here.

    🚀 Quick Start

    10 minutes of self-cognition fine-tuning of Qwen3-4B-Instruct-2507 on a single 3090 GPU:

    Command Line Interface (Recommended)

    # 13GB
    CUDA_VISIBLE_DEVICES=0 \
    swift sft \
        --model Qwen/Qwen3-4B-Instruct-2507 \
        --tuner_type lora \
        --dataset 'AI-ModelScope/alpaca-gpt4-data-zh#500' \
                  'AI-ModelScope/alpaca-gpt4-data-en#500' \
                  'swift/self-cognition#500' \
        --torch_dtype bfloat16 \
        --num_train_epochs 1 \
        --per_device_train_batch_size 1 \
        --per_device_eval_batch_size 1 \
        --learning_rate 1e-4 \
        --lora_rank 8 \
        --lora_alpha 32 \
        --target_modules all-linear \
        --gradient_accumulation_steps 16 \
        --eval_steps 50 \
        --save_steps 50 \
        --save_total_limit 2 \
        --logging_steps 5 \
        --max_length 2048 \
        --output_dir output \
        --warmup_ratio 0.05 \
        --dataloader_num_workers 4 \
        --model_author swift \
        --model_name swift-robot
    

    Tips:

    • If you want to train with a custom dataset, you can refer to this guide to organize your dataset format and specify --dataset <dataset_path>.
    • The --model_author and --model_name parameters are only effective when the dataset includes swift/self-cognition.
    • To train with a different model, simply modify --model <model_id/model_path>.
    • By default, ModelScope is used for downloading models and datasets. If you want to use HuggingFace, simply specify --use_hf true.

    After training is complete, use the following command to infer with the trained weights:

    • Here, --adapters should be replaced with the last checkpoint folder generated during training. Since the adapters folder contains the training parameter file args.json, there is no need to specify --model, --system separately; Swift will automatically read these parameters. To disable this behavior, you can set --load_args false.
    # Using an interactive command line for inference.
    CUDA_VISIBLE_DEVICES=0 \
    swift infer \
        --adapters output/vx-xxx/checkpoint-xxx \
        --stream true \
        --temperature 0 \
        --max_new_tokens 2048
    
    # merge-lora and use vLLM for inference acceleration
    CUDA_VISIBLE_DEVICES=0 \
    swift infer \
        --adapters output/vx-xxx/checkpoint-xxx \
        --stream true \
        --merge_lora true \
        --infer_backend vllm \
        --vllm_max_model_len 8192 \
        --temperature 0 \
        --max_new_tokens 2048
    

    Finally, use the following command to push the model to ModelScope:

    CUDA_VISIBLE_DEVICES=0 \
    swift export \
        --adapters output/vx-xxx/checkpoint-xxx \
        --push_to_hub true \
        --hub_model_id '<your-model-id>' \
        --hub_token '<your-sdk-token>' \
        --use_hf false
    

    Web-UI

    The Web-UI is a zero-threshold training and deployment interface solution based on Gradio interface technology. For more details, you can check here.

    SWIFT_UI_LANG=en swift web-ui
    

    image.png

    Using Python

    ms-swift also supports training and inference using Python. Below is pseudocode for training and inference. For more details, you can refer to here.

    Training:

    from peft import LoraConfig, get_peft_model
    from swift import get_model_processor, get_template, load_dataset, EncodePreprocessor
    from swift.trainers import Seq2SeqTrainer, Seq2SeqTrainingArguments
    # Retrieve the model and template, and add a trainable LoRA module
    model, tokenizer = get_model_processor(model_id_or_path, ...)
    template = get_template(tokenizer, ...)
    lora_config = LoraConfig(...)
    model = get_peft_model(model, lora_config)
    
    # Download and load the dataset, and encode the text into tokens
    train_dataset, val_dataset = load_dataset(dataset_id_or_path, ...)
    train_dataset = EncodePreprocessor(template=template)(train_dataset, num_proc=num_proc)
    val_dataset = EncodePreprocessor(template=template)(val_dataset, num_proc=num_proc)
    
    # Train the model
    training_args = Seq2SeqTrainingArguments(...)
    trainer = Seq2SeqTrainer(
        model=model,
        args=training_args,
        template=template,
        train_dataset=train_dataset,
        eval_dataset=val_dataset,
    )
    trainer.train()
    

    Inference:

    from swift import TransformersEngine, InferRequest, RequestConfig
    # Perform inference using the native Transformers engine
    engine = TransformersEngine(model_id_or_path, adapters=[lora_checkpoint])
    infer_request = InferRequest(messages=[{'role': 'user', 'content': 'who are you?'}])
    request_config = RequestConfig(max_tokens=max_new_tokens, temperature=temperature)
    
    resp_list = engine.infer([infer_request], request_config)
    print(f'response: {resp_list[0].choices[0].message.content}')
    

    ✨ Usage

    Here is a minimal example of training to deployment using ms-swift. For more details, you can check the examples.

    • If you want to use other models or datasets (including multimodal models and datasets), you only need to modify --model to specify the corresponding model's ID or path, and modify --dataset to specify the corresponding dataset's ID or path.
    • By default, ModelScope is used for downloading models and datasets. If you want to use HuggingFace, simply specify --use_hf true.
    Useful Links
    🔥Command Line Parameters
    Megatron-SWIFT
    GRPO
    Supported Models and Datasets
    Custom Models, 🔥Custom Datasets
    LLM Tutorial

    Training

    Supported Training Methods:

    MethodFull-ParameterLoRAQLoRADeepspeedMulti-MachineMultimodal
    Pre-training✅✅✅✅✅✅
    Supervised Fine-Tuning✅✅✅✅✅✅
    GRPO✅✅✅✅✅✅
    GKD✅✅✅✅✅✅
    PPO✅✅✅✅✅❌
    DPO✅✅✅✅✅✅
    KTO✅✅✅✅✅✅
    Reward Model✅✅✅✅✅✅
    CPO✅✅✅✅✅✅
    SimPO✅✅✅✅✅✅
    ORPO✅✅✅✅✅✅
    Embedding✅✅✅✅✅✅
    Reranker✅✅✅✅✅✅
    Sequence Classification✅✅✅✅✅✅

    Pre-training:

    # 8*A100
    NPROC_PER_NODE=8 \
    CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
    swift pt \
        --model Qwen/Qwen3-4B-Base \
        --dataset swift/chinese-c4 \
        --streaming true \
        --tuner_type full \
        --deepspeed zero2 \
        --output_dir output \
        --max_steps 10000 \
        ...
    

    Fine-tuning:

    CUDA_VISIBLE_DEVICES=0 swift sft \
        --model Qwen/Qwen3-4B-Instruct-2507 \
        --dataset AI-ModelScope/alpaca-gpt4-data-en \
        --tuner_type lora \
        --output_dir output \
        ...
    

    RLHF:

    CUDA_VISIBLE_DEVICES=0 swift rlhf \
        --rlhf_type dpo \
        --model Qwen/Qwen3-4B-Instruct-2507 \
        --dataset hjh0119/shareAI-Llama3-DPO-zh-en-emoji \
        --tuner_type lora \
        --output_dir output \
        ...
    

    Megatron-SWIFT

    ms-swift supports using Megatron parallelism techniques to accelerate training, including large-scale cluster training and MoE model training. The following training methods are supported:

    MethodFull-ParameterLoRAMoEMultimodalFP8
    Pre-training✅✅✅✅✅
    Supervised Fine-Tuning✅✅✅✅✅
    GRPO✅✅✅✅✅
    GKD✅✅✅✅✅
    DPO✅✅✅✅✅
    KTO✅✅✅✅✅
    RM✅✅✅✅✅
    Embedding✅✅✅✅✅
    Reranker✅✅✅✅✅
    Sequence Classification✅✅✅✅✅
    NPROC_PER_NODE=2 CUDA_VISIBLE_DEVICES=0,1 megatron sft \
        --model Qwen/Qwen3-4B-Instruct-2507 \
        --save_safetensors true \
        --dataset AI-ModelScope/alpaca-gpt4-data-zh \
        --tuner_type lora \
        --output_dir output \
        ...
    

    Reinforcement Learning

    ms-swift supports a rich set of GRPO family algorithms:

    MethodFull-ParameterLoRAMultimodalMulti-Machine
    GRPO✅✅✅✅
    DAPO✅✅✅✅
    GSPO✅✅✅✅
    SAPO✅✅✅✅
    CISPO✅✅✅✅
    CHORD✅✅✅✅
    RLOO✅✅✅✅
    Reinforce++✅✅✅✅
    CUDA_VISIBLE_DEVICES=0,1,2,3 NPROC_PER_NODE=4 \
    swift rlhf \
        --rlhf_type grpo \
        --model Qwen/Qwen3-4B-Instruct-2507 \
        --tuner_type lora \
        --use_vllm true \
        --vllm_mode colocate \
        --dataset AI-MO/NuminaMath-TIR#10000 \
        --output_dir output \
        ...
    

    Inference

    CUDA_VISIBLE_DEVICES=0 swift infer \
        --model Qwen/Qwen3-4B-Instruct-2507 \
        --stream true \
        --infer_backend transformers \
        --max_new_tokens 2048
    

    Interface Inference

    CUDA_VISIBLE_DEVICES=0 swift app \
        --model Qwen/Qwen3-4B-Instruct-2507 \
        --stream true \
        --infer_backend transformers \
        --max_new_tokens 2048
    

    Deployment

    CUDA_VISIBLE_DEVICES=0 swift deploy \
        --model Qwen/Qwen3-4B-Instruct-2507 \
        --infer_backend vllm
    

    Sampling

    CUDA_VISIBLE_DEVICES=0 swift sample \
        --model Qwen/Qwen3-4B-Instruct-2507 \
        --sampler_engine transformers \
        --num_return_sequences 5 \
        --dataset AI-ModelScope/alpaca-gpt4-data-zh#5
    

    Evaluation

    CUDA_VISIBLE_DEVICES=0 swift eval \
        --model Qwen/Qwen3-4B-Instruct-2507 \
        --infer_backend sglang \
        --eval_backend OpenCompass \
        --eval_dataset ARC_c
    

    Quantization

    CUDA_VISIBLE_DEVICES=0 swift export \
        --model Qwen/Qwen3-4B-Instruct-2507 \
        --quant_method fp8 \
        --dataset AI-ModelScope/alpaca-gpt4-data-zh \
        --output_dir Qwen3-4B-Instruct-2507-FP8
    

    Push Model

    swift export \
        --model <model-path> \
        --push_to_hub true \
        --hub_model_id '<model-id>' \
        --hub_token '<sdk-token>'
    

    🏛 License

    This framework is licensed under the Apache License (Version 2.0). For models and datasets, please refer to the original resource page and follow the corresponding License.

    📎 Citation

    @misc{zhao2024swiftascalablelightweightinfrastructure,
          title={SWIFT:A Scalable lightWeight Infrastructure for Fine-Tuning},
          author={Yuze Zhao and Jintao Huang and Jinghan Hu and Xingjun Wang and Yunlin Mao and Daoze Zhang and Zeyinzi Jiang and Zhikai Wu and Baole Ai and Ang Wang and Wenmeng Zhou and Yingda Chen},
          year={2024},
          eprint={2408.05517},
          archivePrefix={arXiv},
          primaryClass={cs.CL},
          url={https://arxiv.org/abs/2408.05517},
    }
    

    Star History

    Star History Chart