AI-Chain

LlamaFactory 實戰:用一套 CLI 與 Web UI 完成 LLM 微調、推理與部署

LlamaFactory 將 100+ 個 LLM 與 VLM 的微調流程整合成 CLI、Web UI 與 OpenAI 相容 API。本文從 LoRA/QLoRA 快速開始,拆解資料準備、訓練、推理、合併與部署的實作路徑。

分享:
LlamaFactory 實戰:用一套 CLI 與 Web UI 完成 LLM 微調、推理與部署

LlamaFactory 實戰:把模型微調流程收斂成一個可操作的工具鏈

為什麼值得關注

把開源模型微調成可用的專用模型,通常不只是執行一次訓練命令:還要處理模型與 tokenizer、資料格式、訓練策略、顯存配置、推理驗證、權重合併,以及最後的服務化。LlamaFactory 的定位,是把這條鏈路整合在同一個 Python 專案中,提供 CLI、Gradio Web UI,以及 OpenAI-style API/vLLM 推理後端。

截至 2026-08-05,專案在 GitHub 有 73,782 顆星,最近一次 push 是 2026-08-04;官方最新 release v0.9.5 於 2026-05-30 發布。它不是資源清單或單純教學,而是能直接安裝、執行訓練與部署的 AI Engineering 工具。

核心能力:從訓練到服務化

官方 README 將能力分成幾個實作面向:

  • 模型支援:涵蓋 Llama、Qwen、DeepSeek、Gemma、Mistral、GLM、Phi 等模型家族,也包含多模態、音訊與視覺模型。
  • 訓練方法:支援預訓練、監督式微調、Reward Modeling、PPO、DPO、KTO、ORPO 與 SimPO。
  • 參數效率:除了 full-tuning,也提供 freeze-tuning、LoRA,以及透過 AQLM、AWQ、GPTQ、LLM.int8、HQQ、EETQ 的 2/3/4/5/6/8-bit QLoRA。
  • 推理與觀測:可以用 LlamaBoard、TensorBoard、W&B、MLflow 或 SwanLab 觀測實驗,並透過 Gradio、CLI、vLLM worker 或 SGLang worker 加速推理。

這樣的整合價值,不在於重新發明每一種演算法,而在於讓模型、資料集、模板、訓練器與推理介面共享同一套設定。對團隊而言,從實驗切換到 API 服務時,少一次手工搬運與環境分叉。

最小可行路徑:LoRA 微調、聊天、合併

官方 Quickstart 以 Qwen3-4B-Instruct 為例,將 LoRA 微調、推理與權重合併收斂成三個 CLI 命令:

llamafactory-cli train examples/train_lora/qwen3_lora_sft.yaml
llamafactory-cli chat examples/inference/qwen3_lora_sft.yaml
llamafactory-cli export examples/merge_lora/qwen3_lora_sft.yaml

這三步背後對應三個不同驗證點:

  1. train:確認資料格式、模板、顯存與訓練超參數能正常工作,產出 adapter checkpoint。
  2. chat:在不先合併權重的情況下,直接把 base model 與 adapter 載入,檢查模型是否真的學到目標行為。
  3. export:把 adapter 合併或轉出部署需要的格式,讓後續推理服務不必再維持同樣的 adapter 載入流程。

實務上不要跳過第二步。先用 chat 驗證輸出,再決定是否 export,可以避免把資料或模板問題固化到部署產物中。

資料準備是第一個真正的工程問題

LlamaFactory 的資料流程不是把 JSON 丟進訓練器就結束。官方文件要求在 data/dataset_info.json 登記自訂資料集,並依 data/README.md 準備欄位與模板。資料可以來自 Hugging Face、ModelScope、Modelers Hub、本機磁碟或 S3/GCS。

建議把資料檢查拆成三層:

  • 結構:每筆資料是否符合任務需要,例如 instruction/input/output,或偏好學習需要的 chosen/rejected。
  • 模板:訓練與推理使用同一個 chat template;官方特別提醒 reasoning 與 non-reasoning 版本要選對對應模板。
  • 品質:先抽樣檢查多輪對話、工具呼叫、圖片或音訊欄位,再投入長時間訓練。

這裡最容易踩的坑,是把「模型支援」誤認成「資料不需要整理」。框架替你處理載入與格式化,但領域資料的去重、敏感資訊清理、標籤一致性與評估集隔離,仍然是使用者的責任。

LoRA、QLoRA 與顯存取捨

官方硬體表提供一個很實用的估算:以 7B 模型為例,full fine-tuning 的估計顯存需求遠高於 LoRA;16-bit 的 Freeze/LoRA/GaLore/APOLLO/BAdam/OFT 約 16GB,4-bit QLoRA 約 6GB。這些是估算值,不是保證,實際使用量仍會受到序列長度、batch size、梯度累積、optimizer 與 activation checkpointing 影響。

因此可以用以下順序做資源決策:

  1. 先用小資料集與短序列跑通 LoRA。
  2. 顯存不足時,改用 QLoRA 或降低 micro-batch,配合 gradient accumulation 維持有效 batch size。
  3. 需要更大模型或多卡時,再評估 DeepSpeed、FSDP、Megatron-core backend 與分散式啟動。
  4. 訓練完成後,用獨立評估集比較 base model、adapter model 與 merged model,而不是只看 training loss。

從本機實驗走向部署

LlamaFactory 提供三條部署路徑:

  • llamafactory-cli webui 啟動 LlamaBoard,以瀏覽器操作訓練、評估與推理。
  • 透過 OpenAI-style API 與 vLLM worker,將微調後模型接到既有應用程式。
  • 使用 Docker image 或 Docker Compose,固定 CUDA、PyTorch、Python 與 FlashAttention 版本,降低環境漂移。

官方 README 的 Docker image 範例使用 GPU、host IPC,並以 Ubuntu 22.04、CUDA 12.4、Python 3.11、PyTorch 2.6.0 與 Flash-attn 2.7.4 為基礎。若團隊的部署環境不是 NVIDIA CUDA,也要依官方 NPU 文件與對應 image 處理,不能直接套用 CUDA 參數。

服務化前至少要補上三項檢查:

  • 限制可接受的輸入長度與併發,避免推理請求耗盡顯存。
  • 將 adapter、merged checkpoint、tokenizer 與 chat template 一起版本化。
  • 對工具呼叫、個人資料與模型輸出建立審計與安全策略;OpenAI 相容 API 只代表介面相容,不代表自動具備安全控管。

v0.9.5 帶來的訊號

官方 v0.9.5 release notes 列出 Qwen3.5/Qwen3.6、Gemma 4、Transformers v5 相容性,以及 FP8 Transformer Engine backend、Megatron 相關整合與新的 CLI sampler 等變更。這說明專案仍在快速跟進模型與訓練基礎設施,但也代表版本相容性需要被當成正式工程依賴管理。

建議以 release tag 或 commit pin 住可重現環境,搭配一個最小 smoke test:載入模型、跑一個短推理、載入一小批資料、完成幾步訓練,再進行正式升級。不要只因為 README 出現新模型名稱,就直接在生產環境切換套件版本。

結語:適合把「模型調整」變成團隊流程

LlamaFactory 最值得注意的地方,是它把模型微調的多個斷點串成一條可重複的工具鏈:資料登記、模板選擇、LoRA/QLoRA 訓練、互動驗證、權重輸出與 API 部署都能在同一個專案中找到對應入口。它不會替你解決資料品質與評估設計,但能明顯降低從研究實驗走到應用整合的膠水程式碼成本。

如果你的團隊正在建立私有知識、客服、程式碼或多模態模型的客製化流程,LlamaFactory 是值得先用小模型、小資料集做 smoke test 的候選工具;若只是想閱讀微調概念,則應先看官方文件與範例,再決定是否需要完整部署這套框架。

參考資料

  • GitHub repository:https://github.com/hiyouga/LlamaFactory
  • 官方 README:https://github.com/hiyouga/LlamaFactory/blob/main/README.md
  • v0.9.5 release:https://github.com/hiyouga/LlamaFactory/releases/tag/v0.9.5
  • 官方文件:https://llamafactory.readthedocs.io/en/latest/
  • 原始論文:https://arxiv.org/abs/2403.13372

English Version

LlamaFactory in Practice: One Toolchain for Fine-Tuning, Inference, and Deployment

Why it matters

Turning an open model into a useful domain model involves more than starting a training job. Teams must handle model and tokenizer loading, dataset formats, training methods, GPU memory, inference checks, weight merging, and serving. LlamaFactory brings these steps together in one Python project with a CLI, a Gradio Web UI, and an OpenAI-style API with vLLM or SGLang inference backends.

As of 2026-08-05, the repository has 73,782 GitHub stars and was pushed on 2026-08-04. Its latest official release, v0.9.5, was published on 2026-05-30. This is an implementation-oriented AI Engineering tool, not a resource list or a learning-only repository.

Core capabilities

The official README describes support for Llama, Qwen, DeepSeek, Gemma, Mistral, GLM, Phi, and multimodal models. Training approaches include pre-training, supervised fine-tuning, reward modeling, PPO, DPO, KTO, ORPO, and SimPO. Parameter-efficient options include freeze-tuning, LoRA, and 2/3/4/5/6/8-bit QLoRA through several quantization backends. Experiment tracking can use LlamaBoard, TensorBoard, W&B, MLflow, or SwanLab, while inference can use the CLI, Gradio, vLLM, or SGLang.

The main value is integration: models, datasets, templates, trainers, and inference interfaces share one configuration ecosystem. That reduces the manual handoffs between an experiment and an API service.

The minimum path: LoRA, chat, and export

The official Quickstart uses Qwen3-4B-Instruct and exposes three commands:

llamafactory-cli train examples/train_lora/qwen3_lora_sft.yaml
llamafactory-cli chat examples/inference/qwen3_lora_sft.yaml
llamafactory-cli export examples/merge_lora/qwen3_lora_sft.yaml

train validates the dataset, template, memory settings, and hyperparameters. chat checks the adapter with the base model before merging. export produces a checkpoint suitable for the next deployment step. Keeping the chat validation before export is a useful guard against shipping a broken template or dataset.

Data preparation is the first engineering problem

Custom datasets must be registered in data/dataset_info.json and formatted according to data/README.md. Sources can include Hugging Face, ModelScope, Modelers Hub, local storage, S3, or GCS. Validate structure, chat templates, and data quality separately. The framework handles loading and formatting, but deduplication, privacy filtering, label consistency, and evaluation-set isolation remain application responsibilities.

LoRA, QLoRA, and GPU trade-offs

The README estimates roughly 16GB for a 7B model with 16-bit Freeze/LoRA-style tuning and roughly 6GB with 4-bit QLoRA, while full tuning requires much more memory. These are estimates; sequence length, batch size, optimizer, gradient accumulation, and activation checkpointing change the actual footprint.

Start with a small LoRA smoke test, move to QLoRA when memory is constrained, and evaluate distributed options such as DeepSpeed, FSDP, or Megatron-core only when the single-device path is understood. Compare the base, adapter, and merged models on a held-out evaluation set instead of relying on training loss alone.

Moving from experiments to serving

Use llamafactory-cli webui for the LlamaBoard interface, an OpenAI-style API with vLLM for application integration, or Docker images and Compose to pin the CUDA, PyTorch, Python, and FlashAttention environment. Before serving, constrain input length and concurrency, version the adapter together with the tokenizer and chat template, and add audit and safety controls. API compatibility does not automatically provide production security.

What v0.9.5 signals

The v0.9.5 release notes mention primary support for Qwen3.5/Qwen3.6 and Gemma 4, Transformers v5 compatibility, an FP8 Transformer Engine backend, Megatron-related integration, and a CLI sampler. The project is moving quickly with model and infrastructure changes, so reproducibility requires pinning release tags or commits and running a small smoke test before upgrades.

Conclusion

LlamaFactory connects dataset registration, template selection, LoRA/QLoRA training, interactive validation, checkpoint export, and API deployment in one repeatable toolchain. It does not replace data-quality or evaluation design, but it can reduce the glue code between research experiments and application integration. Teams building private knowledge, customer-support, code, or multimodal models should start with a small model and dataset, validate the end-to-end path, and then scale it deliberately.

References

  • GitHub repository: https://github.com/hiyouga/LlamaFactory
  • Official README: https://github.com/hiyouga/LlamaFactory/blob/main/README.md
  • v0.9.5 release: https://github.com/hiyouga/LlamaFactory/releases/tag/v0.9.5
  • Official documentation: https://llamafactory.readthedocs.io/en/latest/
  • Paper: https://arxiv.org/abs/2403.13372