LLaMA Factory: Unified Efficient Fine-Tuning of 100+ LLMs

repository·main·Indexed 13 days ago

https://github.com/hiyouga/llamafactory

A comprehensive framework for the efficient fine-tuning of over 100 large language models. It supports various training methods including LoRA, QLoRA (Bitsandbytes, HQQ, EETQ, GPTQ, AWQ, AQLM), and full-parameter fine-tuning. The tool provides support for Supervised Fine-Tuning (SFT), Pre-training, and Preference Learning (DPO, ORPO, SimPO, KTO), as well as multimodal datasets (image, video, audio). It includes optimized Docker configurations for NVIDIA GPU environments and Megatron Bridge workflows, and supports distributed training via DeepSpeed ZeRO-3 and Ray.

Tokens
27.4K
Snippets
93
Records
115
Agent score
99%

What's inside LLaMA Factory

  1. Overview of LlamaFactory features

    main

    LlamaFactory is an open-source platform designed for easy fine-tuning of hundreds of large language models (LLMs) using either a zero-code Command Line Interface (CLI) or a Web UI (LLaMA Board) powered by Gradio.

    Key capabilities include:

    • Model Support: Wide range of models including LLaMA, LLaVA, Mistral, Mixtral-MoE, Qwen, DeepSeek, Gemma, GLM, Phi, etc.
    • Training Methods: Supports (incremental) pre-training, instruction fine-tuning (including multimodal), reward model training, and various RLHF methods like PPO, DPO, KTO, and ORPO.
    • Precision Options: Full parameter fine-tuning (16-bit), frozen fine-tuning, LoRA, and QLoRA (supporting 2/3/4/5/6/8-bit quantization via AQLM/AWQ/GPTQ/LLM.int8/HQQ/EETQ).
    • Advanced Algorithms: Integration of GaLore, BAdam, APOLLO, Adam-mini, Muon, OFT, DoRA, LongLoRA, LLaMA Pro, Mixture-of-Depths, LoRA+, LoftQ, and PiSSA.
    • Optimization & Speed: Supports FlashAttention-2, Unsloth, Liger Kernel, KTransformers, RoPE scaling, NEFTune, and rsLoRA. Inference can be accelerated using vLLM or SGLang.
    • Task Versatility: Handles multi-turn dialogue, tool calling, image understanding, visual grounding, video recognition, and speech understanding.
    • Experiment Monitoring: Integrates with LlamaBoard, TensorBoard, Wandb, MLflow, and SwanLab.
  2. Format datasets using the Alpaca format

    main

    The Alpaca format is used for Supervised Fine-Tuning (SFT), Pre-training, and Preference learning.

    Supervised Fine-Tuning (SFT)

    Concatenates instruction and input to form the prompt (instruction\ninput). The output column is the target response.

    • System Prompts: Use the system column.
    • Multi-turn Conversation: Use the history column (a list of [user_prompt, assistant_response] tuples). Note: history responses are also learned.
    • Reasoning/CoT: For models like Qwen3, place Chain-of-Thought in the response as <think>cot</think>output.

    Pre-training

    Requires a single text column containing the raw document string.

    Preference Learning (DPO, ORPO, SimPO)

    Requires a chosen column (better response) and a rejected column (worse response). Set ranking: true in dataset_info.json.

    Specialized Formats

    • KTO: Requires a kto_tag column.
    • Multimodal: Requires images, videos, or audios columns.
    // SFT Example
    [
      {
        "instruction": "user instruction (required)",
        "input": "user input (optional)",
        "output": "model response (required)",
        "system": "system prompt (optional)",
        "history": [["user instruction 1", "model response 1"]]
      }
    ]
    
    // Pre-training Example
    [{"text": "document"}]
    
    // Preference Example
    [
      {
        "instruction": "user instruction",
        "chosen": "chosen answer",
        "rejected": "rejected answer"
      }
    ]
  3. Format Pre-training datasets

    main

    For pre-training, only the content in the text column is used for model learning.

    Registration in dataset_info.json: Map the prompt column to the text key in your data.

    // Data format
    [
      {"text": "document"},
      {"text": "document"}
    ]
    
    // dataset_info.json entry
    "dataset_name": {
      "file_name": "data.json",
      "columns": {
        "prompt": "text"
      }
    }
  4. Format Alpaca-style Supervised Fine-Tuning (SFT) datasets

    main

    For SFT using the Alpaca format, the prompt is constructed by concatenating instruction and input (i.e., instruction\ninput). The output column contains the model's response.

    • System Prompt: Use the system column if provided.
    • History: The history column should be a list of string tuples [[instruction, response], ...] representing dialogue turns. Note that history responses are also used for model learning.
    • Reasoning/CoT: For reasoning models, include the Chain of Thought (CoT) within the output column using the format <think>cot</think>output.

    Note on enable_thinking: If the model supports reasoning (e.g., Qwen3) but the dataset lacks CoT, LLaMA-Factory adds an empty CoT.

    • If enable_thinking=True (Slow Thinking/Default): Empty CoT is added to the response and loss is calculated.
    • If enable_thinking=False (Fast Thinking): Empty CoT is added to the user instruction and loss is NOT calculated. Keep this parameter consistent between training and inference.
    [
      {
        "instruction": "User instruction (required)",
        "input": "User input (optional)",
        "output": "Model response (required)",
        "system": "System prompt (optional)",
        "history": [
          ["First turn instruction (optional)", "First turn response (optional)"],
          ["Second turn instruction (optional)", "Second turn response (optional)"]
        ]
      }
    ]
  5. Format Preference datasets (DPO, ORPO, SimPO, Reward Model)

    main

    Preference datasets are used for Reward Model training, DPO, ORPO, and SimPO. They require a chosen column (the better response) and a rejected column (the inferior response).

    Registration in dataset_info.json: Set ranking: true and map the columns accordingly.

    // Data format
    [
      {
        "instruction": "User instruction (required)",
        "input": "User input (optional)",
        "chosen": "Superior response (required)",
        "rejected": "Inferior response (required)"
      }
    ]
    
    // dataset_info.json entry
    "dataset_name": {
      "file_name": "data.json",
      "ranking": true,
      "columns": {
        "prompt": "instruction",
        "query": "input",
        "chosen": "chosen",
        "rejected": "rejected"
      }
    }
  6. Handle Chain-of-Thought (CoT) with enable_thinking

    main

    When training reasoning models, the enable_thinking parameter controls how empty CoT is handled if your dataset lacks it:

    • enable_thinking: True (Slow Thinking, Default): Empty CoT is added to model responses, and loss is computed on it.
    • enable_thinking: False (Fast Thinking): Empty CoT is added to user prompts, and loss is ignored.
    • enable_thinking: None: Allows mixing data containing CoT (with slow thinking) and data without CoT (with fast thinking). Use with caution.

    Important: Keep enable_thinking consistent during both training and inference.

  7. Use custom datasets in LlamaFactory

    main

    To use a custom dataset, you must add a dataset description to the dataset_info.json file. Once described, you can use the dataset by setting the dataset configuration key to the corresponding dataset name.

    Supported dataset categories include:

    • Pre-training datasets (e.g., Wiki Demo, RefinedWeb, RedPajama V2)
    • Instruction tuning datasets (e.g., Alpaca, Belle, UltraChat, OpenOrca)
    • Preference datasets (e.g., DPO mixed, UltraFeedback, KTO mixed)
  8. Understand LlamaFactory licensing and citations

    main

    LlamaFactory is open-source under the Apache-2.0 license.

    Important Note on Model Weights: While the LlamaFactory code is Apache-2.0, the model weights you use are subject to their own specific licenses (e.g., Llama 3, DeepSeek, Qwen, Mistral, etc.). Always verify the license of the specific model weights you are fine-tuning.

    If you use this project in research, you can cite it using the following BibTeX format:

    @inproceedings{zheng2024llamafactory,
      title={LlamaFactory: Unified Efficient Fine-Tuning of 100+ Language Models},
      author={Yaowei Zheng and Richong Zhang and Junhao Zhang and Yanhan Ye and Zheyan Luo and Zhangchi Feng and Yongqiang Ma},
      booktitle={Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 3: System Demonstrations)},
      address={Bangkok, Thailand},
      publisher={Association for Computational Linguistics},
      year={2024},
      url={http://arxiv.org/abs/2403.13372}
    }
  9. Register custom datasets via dataset_info.json

    main

    To use custom datasets in LLaMA-Factory, you must register them in a dataset_info.json file. This file must be located in the directory specified by the dataset_dir parameter (default is ./data).

    Supported formats include alpaca and sharegpt. Supported file types are json, jsonl, csv, parquet, and arrow.

    When using a custom dataset, you must add a description for it in dataset_info.json and then reference it in your configuration using dataset: <dataset_name>.

    "dataset_name": {
      "file_name": "data.json",
      "formatting": "alpaca",
      "columns": {
        "prompt": "instruction",
        "query": "input",
        "response": "output"
      }
    }
  10. Basic usage of llamafactory-cli

    main

    To run training or other tasks, execute commands from the LLaMA-Factory directory. You can select specific compute devices using CUDA_VISIBLE_DEVICES (for NVIDIA GPUs) or ASCEND_RT_VISIBLE_DEVICES (for NPU). By default, LLaMA-Factory uses all visible devices.

    Basic training command:

    llamafactory-cli train examples/train_lora/qwen3_lora_sft.yaml

    Advanced usage with parameter overrides: You can override configuration keys directly in the CLI command.

    CUDA_VISIBLE_DEVICES=0,1 llamafactory-cli train examples/train_lora/qwen3_lora_sft.yaml \
        learning_rate=1e-5 \
        logging_steps=1
    llamafactory-cli train examples/train_lora/qwen3_lora_sft.yaml
  11. Inference and Model Evaluation

    main

    LLaMA-Factory provides several ways to interact with trained models:

    • Command Line Interface (CLI): Interactive chat in the terminal.
    • Web UI: Interactive chat via a browser.
    • OpenAI-compatible API: Start a server to serve model requests via API.
    • vLLM (High Performance): Use scripts/vllm_infer.py for multi-GPU inference and evaluation (e.g., BLEU/ROUGE scores).

    Usage Examples:

    CLI Chat:

    llamafactory-cli chat examples/inference/qwen3_lora_sft.yaml

    Web Chat:

    llamafactory-cli webchat examples/inference/qwen3_lora_sft.yaml

    OpenAI API:

    llamafactory-cli api examples/inference/qwen3_lora_sft.yaml
    llamafactory-cli chat examples/inference/qwen3_lora_sft.yaml
  12. Merging LoRA Adapters and Quantization

    main

    To use a fine-tuned LoRA model as a standalone model, you must export/merge the adapters.

    Important: Do NOT use a quantized model or the quantization_bit parameter when merging LoRA adapters.

    Supported export tasks include merging LoRA adapters, quantizing models using AutoGPTQ, and saving Ollama modelfiles.

    # Merge LoRA Adapters
    llamafactory-cli export examples/merge_lora/qwen3_lora_sft.yaml
    
    # Quantize using AutoGPTQ
    llamafactory-cli export examples/merge_lora/qwen3_gptq.yaml
    
    # Save Ollama modelfile
    llamafactory-cli export examples/merge_lora/qwen3_full_sft.yaml