大模型微调DeepSpeed、vLLM 及 LLaMA-Factory 使用指南一、工具概览工具定位核心能力DeepSpeed分布式训练框架ZeRO 显存优化、数据并行、流水线并行vLLM推理引擎PagedAttention、Continuous Batching、高吞吐推理LLaMA-Factory一站式微调平台100 模型支持、LoRA/QLoRA、Web UI、一键训练三者关系LLaMA-Factory 作为上层框架底层集成 DeepSpeed 做分布式训练集成 vLLM 做推理部署。二、环境准备2.1 硬件要求模型规模微调方式推荐显存推荐 GPU7BLoRA (FP16)16GBRTX 4090 / A100 40GB7BQLoRA (INT4)8GBRTX 3090 / RTX 408013BLoRA (FP16)32GBA100 40GB13BQLoRA (INT4)12GBRTX 409070BLoRA (FP16)160GBH100 80GB x 270BQLoRA (INT4)48GBA100 80GB / L402.2 软件依赖# Python 3.9python-mpipinstall--upgradepip# PyTorch (CUDA 12.1)pipinstalltorch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121# 验证 CUDApython-cimport torch; print(torch.cuda.is_available()); print(torch.version.cuda)三、LLaMA-Factory 安装与使用3.1 安装# 克隆仓库gitclone--depth1https://github.com/hiyouga/LLaMA-Factory.gitcdLLaMA-Factory# 安装基础依赖pipinstall-e.[torch,metrics]# 安装全部可选依赖含 DeepSpeed、vLLM、FlashAttentionpipinstall-e.[torch,metrics,deepspeed,vllm,flash-attn]# 验证安装llamafactory-cli version国内镜像加速可选# 使用魔搭社区下载模型exportUSE_MODELSCOPE_HUB1# 或使用魔乐社区exportUSE_OPENMIND_HUB13.2 启动 Web UIllamafactory-cli webui访问http://localhost:7860可视化界面包含模型选择与加载数据集配置训练参数调整训练监控Loss 曲线推理测试3.3 命令行训练推荐方式一命令行参数llamafactory-cli train\--stagesft\--do_trainTrue\--model_name_or_pathQwen/Qwen2.5-7B-Instruct\--finetuning_typelora\--templateqwen\--flash_attnauto\--dataset_dirdata\--datasetalpaca_zh_demo\--cutoff_len2048\--learning_rate5e-05\--num_train_epochs3.0\--per_device_train_batch_size2\--gradient_accumulation_steps8\--lr_scheduler_typecosine\--max_grad_norm1.0\--logging_steps5\--save_steps100\--output_dirsaves/Qwen2.5-7B/lora/sft\--bf16True\--plot_lossTrue\--lora_rank8\--lora_alpha16\--lora_dropout0\--lora_targetall方式二YAML 配置文件推荐创建train_lora.yaml### modelmodel_name_or_path:Qwen/Qwen2.5-7B-Instruct### methodstage:sftdo_train:truefinetuning_type:loralora_target:alllora_rank:8lora_alpha:16lora_dropout:0### datasetdataset:alpaca_zh_demotemplate:qwencutoff_len:2048max_samples:1000overwrite_cache:truepreprocessing_num_workers:16### outputoutput_dir:saves/qwen2.5-7b/lora/sftlogging_steps:10save_steps:500plot_loss:trueoverwrite_output_dir:true### trainper_device_train_batch_size:1gradient_accumulation_steps:8learning_rate:5.0e-5num_train_epochs:3.0lr_scheduler_type:cosinewarmup_ratio:0.1bf16:trueddp_timeout:180000000执行训练llamafactory-cli train train_lora.yaml3.4 关键参数说明参数说明推荐值finetuning_type微调类型lora/full/freezelora_rankLoRA 秩 r8简单任务/ 16-32复杂任务lora_alphaLoRA 缩放因子2 * rank通常lora_target目标模块all/q_proj,v_projper_device_train_batch_size每设备 batch1-4根据显存调整gradient_accumulation_steps梯度累积8-16等效大 batchlearning_rate学习率1e-5 ~ 5e-5cutoff_len最大序列长度2048 / 4096bf16BF16 混合精度true推荐比 FP16 稳定3.5 自定义数据集准备数据文件data/my_dataset.json[{instruction:请解释什么是机器学习,input:,output:机器学习是人工智能的一个分支...}]在data/dataset_info.json中注册{my_dataset:{file_name:my_dataset.json,formatting:alpaca,columns:{prompt:instruction,query:input,response:output}}}YAML 中引用dataset: my_dataset四、DeepSpeed 集成分布式训练4.1 DeepSpeed 简介DeepSpeed 是微软开源的分布式训练框架核心特性ZeROZero Redundancy Optimizer分片优化器状态、梯度、参数大幅降低显存占用3D 并行数据并行 张量并行 流水线并行Offload将优化器状态卸载到 CPU/NVMe进一步节省显存4.2 在 LLaMA-Factory 中使用 DeepSpeed单卡 LoRA 微调ZeRO-2创建ds_config_zero2.json{train_batch_size:auto,train_micro_batch_size_per_gpu:auto,gradient_accumulation_steps:auto,gradient_clipping:auto,zero_allow_untested_optimizer:true,fp16:{enabled:auto,loss_scale:0,loss_scale_window:1000,initial_scale_power:16,hysteresis:2,min_loss_scale:1},bf16:{enabled:auto},zero_optimization:{stage:2,offload_optimizer:{device:cpu,pin_memory:true},allgather_partitions:true,allgather_bucket_size:2e8,overlap_comm:true,reduce_scatter:true,reduce_bucket_size:2e8,contiguous_gradients:true}}执行训练llamafactory-cli train train_lora.yaml--deepspeedds_config_zero2.json多卡全参数微调ZeRO-3创建ds_config_zero3.json{train_batch_size:auto,train_micro_batch_size_per_gpu:auto,gradient_accumulation_steps:auto,gradient_clipping:auto,zero_allow_untested_optimizer:true,bf16:{enabled:true},zero_optimization:{stage:3,offload_optimizer:{device:cpu,pin_memory:true},offload_param:{device:cpu,pin_memory:true},overlap_comm:true,contiguous_gradients:true,sub_group_size:1e9,reduce_bucket_size:auto,stage3_prefetch_bucket_size:auto,stage3_param_persistence_threshold:auto,stage3_max_live_parameters:1e9,stage3_max_reuse_distance:1e9,stage3_gather_16bit_weights_on_model_save:true}}多卡启动torchrun--nproc_per_node4\src/train.py train_full.yaml\--deepspeedds_config_zero3.json4.3 ZeRO 阶段对比ZeRO 阶段优化内容显存节省适用场景ZeRO-1分片优化器状态~4x数据并行ZeRO-2 分片梯度~8x大模型微调ZeRO-3 分片参数~N 倍NGPU 数超大模型训练ZeRO-Offload卸载到 CPU/NVMe进一步节省显存极度受限4.4 DeepSpeed 关键配置说明{zero_optimization:{stage:2,// ZeRO 阶段1/2/3offload_optimizer:{// 优化器状态卸载device:cpu,// 卸载到 CPU 或 nvmepin_memory:true// 固定内存加速传输},overlap_comm:true,// 通信与计算重叠contiguous_gradients:true// 连续梯度减少碎片}}五、vLLM 集成推理部署5.1 vLLM 简介vLLM 是高性能大模型推理引擎核心特性PagedAttention将 KV Cache 分页管理显存利用率接近 100%Continuous Batching动态合并请求最大化 GPU 利用率高吞吐相比原生 Transformers吞吐量提升 3-10 倍5.2 在 LLaMA-Factory 中使用 vLLM方式一LLaMA-Factory 内置脚本python scripts/vllm_infer.py\--model_name_or_pathsaves/qwen2.5-7b/lora/sft\--templateqwen\--datasetdata_sample\--cutoff_len512\--max_samples1000\--batch_size32\--max_new_tokens512方式二启动 OpenAI 兼容 API 服务# 合并 LoRA 权重后部署llamafactory-cliexportmerge_lora.yaml# 使用 vLLM 启动 API 服务python-mvllm.entrypoints.openai.api_server\--modelsaves/qwen2.5-7b/lora/sft_merged\--templateqwen\--dtypehalf\--gpu_memory_utilization0.95\--max_model_len4096\--port8000调用 APIfromopenaiimportOpenAI clientOpenAI(base_urlhttp://localhost:8000/v1,api_keydummy)responseclient.chat.completions.create(modelsaves/qwen2.5-7b/lora/sft_merged,messages[{role:user,content:你好}])print(response.choices[0].message.content)方式三LLaMA-Factory 一键部署# 使用 LLaMA-Factory 的 API 模式底层调用 vLLMllamafactory-cli api\--model_name_or_pathsaves/qwen2.5-7b/lora/sft\--templateqwen\--finetuning_typelora\--infer_backendvllm5.3 vLLM 关键参数参数说明推荐值--dtype数据类型half/bfloat16/float16--gpu_memory_utilizationGPU 显存利用率0.90-0.95--max_model_len最大序列长度根据模型支持设置--tensor_parallel_size张量并行 GPU 数1单卡/ 2/4/8--quantization量化方式awq/gptq/fp8--block_sizePagedAttention 块大小16默认/ 325.4 性能优化# 启用 AWQ 量化部署python-mvllm.entrypoints.openai.api_server\--modelQwen/Qwen2.5-7B-Instruct-AWQ\--quantizationawq\--dtypehalf\--gpu_memory_utilization0.95# 多卡张量并行python-mvllm.entrypoints.openai.api_server\--modelQwen/Qwen2.5-72B-Instruct\--tensor_parallel_size4\--dtypebfloat16六、完整工作流示例6.1 微调 合并 部署单卡# 1. 准备环境gitclone--depth1https://github.com/hiyouga/LLaMA-Factory.gitcdLLaMA-Factory pipinstall-e.[torch,metrics,deepspeed,vllm]# 2. 准备数据集放入 data/ 目录并注册# 3. LoRA 微调llamafactory-cli train configs/train_lora.yaml# 4. 合并 LoRA 权重catmerge.yamlEOF model_name_or_path: Qwen/Qwen2.5-7B-Instruct adapter_name_or_path: saves/qwen2.5-7b/lora/sft template: qwen finetuning_type: lora export_dir: saves/qwen2.5-7b/lora/sft_merged export_size: 2 export_device: cpu export_legacy_format: false EOFllamafactory-cliexportmerge.yaml# 5. vLLM 部署python-mvllm.entrypoints.openai.api_server\--modelsaves/qwen2.5-7b/lora/sft_merged\--templateqwen\--dtypehalf\--gpu_memory_utilization0.95\--port80006.2 多卡分布式微调DeepSpeed ZeRO-3# 使用 torchrun 启动多卡训练torchrun--nproc_per_node4\--nnodes1\--node_rank0\src/train.py\--deepspeedconfigs/ds_config_zero3.json\configs/train_full.yaml6.3 量化微调QLoRA# train_qlora.yamlmodel_name_or_path:Qwen/Qwen2.5-7B-Instructstage:sftdo_train:truefinetuning_type:loraquantization_bit:4# 4-bit 量化quantization_method:bitsandbyteslora_rank:64lora_alpha:16lora_target:alldataset:alpaca_zh_demotemplate:qwencutoff_len:2048per_device_train_batch_size:1gradient_accumulation_steps:8learning_rate:1.0e-4num_train_epochs:3.0output_dir:saves/qwen2.5-7b/qlora/sftbf16:truellamafactory-cli train train_qlora.yaml七、监控与调试7.1 训练监控# 启用 WandB 监控pipinstallwandb wandb login# YAML 中添加report_to: wandb run_name: qwen2.5-7b-lora-sft7.2 显存监控# 实时监控 GPUwatch-n1nvidia-smi# 或使用 nvitoppipinstallnvitop nvitop7.3 常见问题问题原因解决CUDA OOM显存不足减小 batch_size / 启用 gradient_checkpointing / 使用 ZeRO-OffloadLoss NaN学习率过大降低 learning_rate启用 warmup训练速度慢数据加载瓶颈增加 num_workers启用 pin_memoryvLLM 启动失败CUDA 版本不匹配检查nvidia-smi和torch.version.cuda模型加载慢网络下载使用USE_MODELSCOPE_HUB1或本地缓存