Chapter 13

源码导读:swift CLI 调度链

📌 commit b58b1bd读懂 swift sft → SftArguments → SftPipeline → Trainer

ms-swift 核心代码量约 8 万行,结构清晰。本章给一份阅读路线,重点是 CLI → Arguments → Pipeline → Trainer 这条调度链。

13.1仓库结构

swift/                              https://github.com/modelscope/ms-swift(v4,2026-03 之后扁平化)
├── swift/
│   ├── cli/                            ★ 命令入口 12 个子命令
│   │   ├── main.py                     ROUTE_MAPPING dispatch
│   │   └── sft.py / pt.py / rlhf.py / infer.py / export.py / deploy.py / ...
│   ├── arguments/                      ★ Arguments dataclass(v3 时叫 swift/llm/argument/)
│   │   ├── sft_args.py                 SftArguments
│   │   ├── rlhf_args.py                 RLHFArguments(含 GRPO/PPO/teacher/reward 4 mixin)
│   │   ├── infer_args.py / export_args.py / eval_args.py / deploy_args.py
│   │   ├── tuner_args.py / pretrain_args.py / sampling_args.py
│   │   └── base_args/
│   ├── pipelines/                     ★ SwiftPipeline 编排(v3 时叫 swift/llm/train/)
│   │   ├── train/                     sft_main / pretrain_main / rlhf_main / SwiftSft
│   │   ├── infer/                     infer_main / deploy_main / rollout_main
│   │   ├── eval/                      eval_main(EvalScope)
│   │   ├── export/                     export_main / merge_lora / quantize_model
│   │   ├── sampling/                   sampling_main / distill_sampler
│   │   └── app/                       app_main / build_ui(Gradio)
│   ├── trainers/                       ★ HF Trainer 子类
│   │   ├── trainer.py / seq2seq_trainer.py / embedding_trainer.py / reranker_trainer.py
│   │   ├── mixin.py                    SwiftMixin(templates / SP / plugins)
│   │   └── trainer_factory.py          TrainerFactory(按 task_type / rlhf_type 选)
│   ├── rlhf_trainers/                 ★ 9 算法各一文件(v4 新拆出)
│   │   ├── dpo_trainer.py / grpo_trainer.py / ppo_trainer.py / kto_trainer.py
│   │   ├── cpo_trainer.py / orpo_trainer.py / rm_trainer.py / gkd_trainer.py
│   │   ├── rlhf_mixin.py               RLHFTrainerMixin 共享逻辑
│   │   └── rollout_mixin.py / vllm_client.py
│   ├── tuners/                         11 个 swift 自家 tuner
│   │   ├── base.py                     SwiftModel
│   │   ├── lora.py / lora_layers.py    swift 自家 LoRA
│   │   ├── peft.py                     PEFT 兼容(默认 backend)
│   │   ├── reft.py / restuning.py / side.py / longlora/ / scetuning/ / neftune.py / llamapro.py / adapter.py / prompt.py / part.py
│   │   └── mapping.py                  SWIFT_MAPPING
│   ├── tuner_plugin/                   插件式 tuner(lora_llm / ia3 / dummy)
│   ├── model/                          ★ 200+ 模型注册
│   │   ├── constant.py                 ModelType 枚举
│   │   ├── register.py                 register_model() + get_model_tokenizer()
│   │   ├── model_meta.py / model_arch.py / patcher.py
│   │   └── model/                      30+ 模型族独立文件(qwen.py / llama.py / ...)
│   ├── template/                       ★ 256 个 template 注册
│   │   ├── base.py                     Template(2274 行)
│   │   ├── register.py                 register_template()
│   │   ├── template_meta.py
│   │   ├── vision_utils.py             多模态预处理
│   │   ├── grounding.py                bbox / 关键点
│   │   └── templates/                  34 个 .py(含 vl/ 子目录)
│   ├── dataset/                        DATASET_MAPPING(150+)
│   │   ├── register.py + data/dataset_info.json
│   │   ├── loader.py / preprocessor.py / packing.py
│   │   ├── indexed_dataset.py          流式
│   │   └── media.py                    图像 / 视频 / 音频
│   ├── infer_engine/                   ★ 5 个推理引擎
│   │   ├── infer_engine.py             AutoInferEngine dispatcher
│   │   ├── vllm_engine.py / sglang_engine.py / lmdeploy_engine.py / transformers_engine.py
│   │   └── grpo_vllm_engine.py
│   ├── rewards/                        ORM / AsyncORM / PRM
│   ├── rollout/                        GRPO multi-turn rollout
│   ├── megatron/                        mcore-bridge 集成(init.py / convert.py / model/)
│   ├── sequence_parallel/               Ulysses + ZigZag Ring + NPU
│   ├── ray/ + ray_utils/                MegatronRayPipeline + worker_group
│   ├── ui/                              Gradio Web UI 7 个 tab
│   ├── agent_template/                  20+ agent 模板
│   ├── pipelines/ + agent_template/     已列上方
│   ├── optimizers/                      Muon / LION / Apollo 等插件
│   ├── callbacks/                       训练回调
│   ├── loss/ + loss_scale/             loss_map 插件
│   ├── metrics/                          metric 插件
│   ├── config/ + hub/                   ModelScope hub 集成
│   └── utils/
├── examples/                            30+ 训练 / 推理 / 部署样例
│   ├── train/                          full / qlora / grpo / rlhf / agent / multimodal / packing / ...
│   ├── infer/                           transformers / vllm / sglang / lmdeploy
│   ├── deploy/                          agent / embedding / reranker / reward_model / ...
│   ├── megatron/                       dense / moe / lora / grpo / rlhf / fp8 / mcore_bridge
│   ├── sampler/                         sample / distill
│   ├── ascend/                          华为昇腾 NPU
│   └── models/                          按模型族分类的范例
├── docs/                                中英双语,BestPractices / Customization / Megatron-SWIFT 分类
└── tests/                               80+ 测试

13.2调度链:swift sft 怎么跑起来

用户 → swift sft --model ... --dataset ...
   │
   └── swift/cli/main.py:分发到 sft 子命令
           │
           └── swift/cli/sft.py:解析参数为 SftArguments
                   │
                   └── swift/llm/train/sft.py:SftPipeline
                           │
                           ├── 加载 model + tokenizer
                           │       └── swift/llm/model/register.py(按 model_type 查 register)
                           ├── 加载 template
                           │       └── swift/llm/template/register.py
                           ├── 加载 dataset + preprocess
                           │       └── swift/llm/dataset/
                           ├── 套 PEFT(如果 train_type=lora)
                           │       └── swift/tuners/lora.py
                           ├── 构造 Trainer
                           │       └── swift/trainers/trainers.py:Trainer
                           └── trainer.train()

13.3建议阅读顺序

#文件读什么
1swift/cli/main.pyCLI 分发
2swift/llm/argument/train_args.py::SftArguments训练参数全字段
3swift/llm/train/sft.py::SftPipeline主流程
4swift/llm/model/register.pyModelType 系统
5swift/llm/model/model/qwen.py典型模型注册
6swift/llm/template/register.pyTemplate 系统
7swift/llm/dataset/preprocessor/core.py数据格式自动识别
8swift/tuners/lora.pyLoRA 接入
9swift/tuners/galore.pyGaLore 实现
10swift/trainers/trainers.pyTrainer 包装
11swift/llm/infer/infer_engine/pt_engine.pyPT 推理引擎

13.4关键 commit 时间线

时间变更
2023-08v1.0:首版 LoRA 微调框架
2023-11多模型支持(Qwen / Llama / Baichuan)
2024-02多模态 (Qwen-VL / Yi-VL)
2024-05DPO / KTO / ORPO 支持
2024-08v2.0:架构重构,Pipeline 风格
2024-11GRPO + R1 风格训练
2025-02v3.0:Megatron 后端集成
2025-Q2多模态 GRPO + 视觉 R1

13.5对照其他框架

ms-swiftLLaMA-FactoryAxolotlNeMo
UICLI + Web UIWebUI 强YAMLrecipe
模型数200+100+50+
多模态★★★★★★★★★★★★★★★
RLHF★★★★(含 GRPO + Megatron)★★★★★★★★★★★
大模型多机★★★★(Megatron)★★★★★★★★★★★
中文社区★★★★★★★★★★★★★★

13.6社区入口

13.7v4 真实调用栈(替换 13.2 简化版)

用户 → swift sft my.yaml --override
   │
   ├── swift/cli/main.py
   │       └── ROUTE_MAPPING[sft] → swift.cli.sft.main()
   │            └── YAML 加载 + CLI override(line 38–71)
   │            └── 自动 torchrun 包装(line 86–102)
   ├── swift/cli/sft.py
   │       └── from swift.pipelines import sft_main → sft_main(args)
   ├── swift/pipelines/train/sft.py
   │       └── SwiftSft(SwiftPipeline).run()
   │            ├── swift/model/register.py:get_model_tokenizer
   │            │   └── ModelType lookup → ModelMeta → load HF model
   │            ├── swift/template/register.py:get_template_meta
   │            │   └── Template (含多模态 / grounding / packing 元数据)
   │            ├── swift/dataset/loader.py:get_dataset
   │            │   └── DATASET_MAPPING + AutoPreprocessor
   │            ├── swift/tuners/peft.py(默认)or swift/tuners/*.py
   │            │   └── PeftModel / SwiftModel wrap
   │            └── swift/trainers/trainer_factory.py:TrainerFactory
   │                 └── task_type/rlhf_type 选 Trainer
   ├── swift/trainers/seq2seq_trainer.py
   │       └── Seq2SeqTrainer(SwiftMixin, DataLoaderMixin, HfSeq2SeqTrainer).train()
   │            └── 调 HF Trainer.train() 但 forward / loss / collator 都被 SwiftMixin patch
   └── checkpoint 保存到 output_dir/v0-xxx/

13.8examples/ 30+ 子目录速查

examples/ 子目录用途
train/full/ 全参 SFT / Pretrain
train/qlora/ QLoRA 4/8 bit
train/grpo/ GRPO + DAPO / GSPO / SAPO / CISPO / RLOO / REINFORCE++
train/rlhf/ DPO / KTO / RM / CPO / SimPO / ORPO / PPO / GKD
train/agent/ ReAct / 工具调用
train/embedding/ / reranker/嵌入 / 重排序模型微调
train/multimodal/ VLM 含多模态 RLHF
train/packing/ 动态 packing
train/sequence_parallel/Ulysses / ZigZag Ring
train/tuners/ Adapter / LISA / DoRA / LoRA+ / LongLoRA / LoRA-GA / RS-LoRA
train/liger/ Liger Kernel 加速
train/think_model/ R1 风格思考链
train/flash_attention_3/ FA3 集成
train/multi-gpu/ / multi-node/DDP / DeepSpeed 多机
infer/ 4 后端推理示例
deploy/ OpenAI 兼容 API(agent / embedding / reranker / lora 多场景)
eval/ LLM / VLM 评测,train_eval / quantize
megatron/ Megatron 全套(dense / moe / lora / grpo / rlhf / fp8 / mcore_bridge)
sampler/ 采样 + API 蒸馏
models/ 30+ 模型族特化样例(Qwen3-VL / GLM-4.6V / DeepSeek-OCR / InternVL3 / Llama4 / MiniCPM-V / Ovis2 / GPT-OSS 等)
ascend/ 华为昇腾 NPU 训练

13.9跟着测试读 API

测试文件覆盖
tests/general/test_model.py ModelType 注册、加载
tests/general/test_template.py template 解析 + multimodal
tests/general/test_dataset.py DATASET_MAPPING / preprocessor
tests/train/test_sft.py SFT 端到端
tests/train/test_rlhf.py 9 个 RLHF 算法
tests/train/test_grpo.py GRPO + 变体
tests/train/test_grounding.py VLM grounding
tests/train/test_packing.py 动态 packing
tests/megatron/ Megatron 各路径(train / grpo / rlhf / lora / fp8 / export)
tests/infer/test_sglang.py SGLang 后端
tests/deploy/test_agent.py agent 推理 / 工具调用
tests/export/test_quant.py AWQ / GPTQ / FP8 量化

13.10这章你需要带走的