Chapter 02

安装与依赖

📌 commit b58b1bd魔搭技术栈的版本约束

ms-swift 是阿里魔搭的微调框架,安装相对简单,但依赖 modelscope 生态。本章给安装路径和验证脚本。

2.1三条路径

方式命令场景
稳定版pip install ms-swift常用
最新pip install git+https://github.com/modelscope/ms-swift跟新模型
开发git clone … && pip install -e ".[all]"本仓 commit b58b1bd

2.2依赖矩阵

版本角色
modelscope>= 1.16魔搭模型 / 数据集源
transformers>= 4.42底座
peft>= 0.11LoRA
trl>= 0.13对齐算法
vllm>= 0.6推理(可选)
accelerate>= 0.34多卡
deepspeed>= 0.14大模型多机
megatron-core>= 0.11Megatron 后端(可选)

2.3安装 + 验证

pip install ms-swift modelscope transformers peft trl
swift --help                       # 看到 CLI 列表说明装对了

swift sft --help | head -50        # 看 SFT 的字段总览

2.4仓库结构

swift/                          https://github.com/modelscope/ms-swift
├── swift/
│   ├── cli/                    ★ 命令行入口
│   ├── llm/                    ★ LLM 训练 / 推理 / 量化主入口
│   │   ├── sft.py
│   │   ├── dpo.py / kto.py / orpo.py
│   │   ├── grpo.py
│   │   ├── infer.py
│   │   ├── export.py
│   │   └── model/
│   ├── trainers/               ★ 各种 Trainer
│   ├── tuners/                  PEFT 集成 + GaLore / LISA / 自家
│   ├── megatron/               Megatron 后端
│   └── plugin/                 自定义 reward / metric 等
├── examples/
│   ├── train/                  Llama / Qwen / DeepSeek / GLM 全套示例
│   ├── infer/
│   └── deploy/
├── docs/                       中英双语
└── tests/

2.5常见问题

现象处理
modelscope 下载模型慢用国内镜像;或 export MODELSCOPE_CACHE=/big_disk
swift 命令找不到没装好;pip install ms-swift 后重新打开 shell
OS error macMac 仅支持 LoRA fp16,不支持 QLoRA
transformers 版本冲突pip install -U ms-swift 一起升

2.6swift CLI 12 个子命令

v4 之后 swift 命令暴露 12 个子命令(来源 swift/cli/main.pyROUTE_MAPPING):

子命令对应模块用途
swift pt swift.cli.pt 预训练 / continued pretrain
swift sft swift.cli.sft ★ SFT(最常用)
swift rlhf swift.cli.rlhf DPO/KTO/RM/CPO/SimPO/ORPO/PPO/GRPO/GKD 9 种统一入口
swift infer swift.cli.infer CLI 聊天 / 批量推理
swift merge-lora swift.cli.merge_lora 合并 LoRA
swift export swift.cli.export 量化导出(AWQ / GPTQ / FP8 / BNB)+ GGUF / Ollama
swift deploy swift.cli.deploy OpenAI 兼容 API server
swift rollout swift.cli.rollout 独立 rollout server(GRPO 用)
swift web-ui swift.cli.web_ui Gradio Web UI(7 tab)
swift sample swift.cli.sample 数据采样 / 蒸馏
swift eval swift.cli.eval 评测(EvalScope,100+ benchmark)
swift app swift.cli.app 启动 Gradio chat app

额外可选:

2.7关键环境变量

变量用途
MODELSCOPE_CACHE 魔搭模型缓存路径(默认 ~/.cache/modelscope
USE_HF=1 切到 HuggingFace Hub 而不是 ModelScope
MODELSCOPE_API_TOKEN 下载私有模型 / 数据
SWIFT_UI_LANG Web UI 语言 zh / en
SWIFT_CONFIG_FILE 训练 config 路径(cli 自动设)
NPROC_PER_NODE 多卡训练时 torchrun 数
FORCE_TORCHRUN=1 单卡也强制 torchrun(DeepSpeed 单卡)
FORCE_REDOWNLOAD=1 跳过 cache 重新下载
DISABLE_TQDM=1 禁用 tqdm 进度条(日志整洁)

2.8这章你需要带走的