TRL documentation

Unsloth 集成

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v1.18.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Unsloth 集成

Unsloth 是一个用于微调和强化学习的开源框架,可将 LLM(如 Llama、OpenAI gpt-oss、Mistral、Gemma、DeepSeek 等)的训练速度提升高达 2 倍,同时减少高达 80% 的 VRAM 占用。Unsloth 支持与其他推理引擎(如 llama.cpp、Ollama 和 vLLM)配合进行训练、评估、运行和部署。

该库提供了一套精简且兼容 Hugging Face 的工作流,涵盖训练、评估、推理和部署,并完全兼容 SFTTrainer。

主要功能

  • 支持所有兼容 Transformer 的模型进行训练:文本转语音(TTS)、多模态、BERT、强化学习等
  • 支持全量微调、预训练、LoRA、QLoRA、8 位训练等
  • 适用于 Linux、Windows、Colab、Kaggle;NVIDIA GPU,即将支持 AMD 和 Intel 配置
  • 支持 TRL 支持的大多数功能,包括 RLHF(GSPO、GRPO、DPO 等)
  • 手写的 Triton 内核和手动反向传播引擎确保了没有精度损失(0% 近似误差)

安装

pip install

本地安装(推荐 Linux):

pip install unsloth

您也可以根据官方文档安装unsloth。安装完成后,您可以以非常简单的方式将 unsloth 集成到您的工作流中;只需加载FastLanguageModel,而无需加载AutoModelForCausalLM,具体操作如下:

import torch
from trl import SFTConfig, SFTTrainer
from unsloth import FastLanguageModel

max_length = 2048 # Supports automatic RoPE Scaling, so choose any number

# Load model
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name="unsloth/mistral-7b",
    max_seq_length=max_length,
    dtype="auto",  # For auto-detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
    load_in_4bit=True,  # Use 4bit quantization to reduce memory usage. Can be False
)

# Do model patching and add fast LoRA weights
model = FastLanguageModel.get_peft_model(
    model,
    r=16,
    target_modules=[
        "q_proj",
        "k_proj",
        "v_proj",
        "o_proj",
        "gate_proj",
        "up_proj",
        "down_proj",
    ],
    lora_alpha=16,
    lora_dropout=0,  # Dropout = 0 is currently optimized
    bias="none",  # Bias = "none" is currently optimized
    use_gradient_checkpointing=True,
    random_state=3407,
)

training_args = SFTConfig(output_dir="./output", max_length=max_length)

trainer = SFTTrainer(
    model=model,
    args=training_args,
    train_dataset=dataset,
)
trainer.train()

保存的模型与 Hugging Face 的 transformers 库完全兼容。有关 unsloth 的更多信息,请参阅其 官方仓库。

Docker 安装

docker run -d -e JUPYTER_PASSWORD="mypassword" \
  -p 8888:8888 -p 2222:22 \
  -v $(pwd)/work:/workspace/work \
  --gpus all \
  unsloth/unsloth

在 http://localhost:8888 访问 Jupyter Lab,开始微调!

训练

这些是您在训练前可以切换的一些核心设置:

  • max_seq_length = 2048 – 控制上下文长度。虽然 Llama-3 支持 8192,但我们建议测试时使用 2048。Unsloth 支持 4 倍长度的上下文微调。
  • dtype = "auto" – 用于自动检测;对于较新的 GPU,请使用 torch.float16 或 torch.bfloat16。
  • load_in_4bit = True – 启用 4 位量化,将微调时的内存占用降低 4 倍。禁用此选项可启用 LoRA 16 位微调。
  • 要启用全量微调(FFT),请设置 full_finetuning = True。对于 8 位微调,请设置 load_in_8bit = True。注意:一次只能将一种训练方法设置为 True。

有关配置 Unsloth 超参数和功能的更多信息,请参阅他们的文档指南。

保存模型

Unsloth 允许你将微调后的模型直接保存为一个名为 LoRA 适配器的小型文件。如果你希望上传模型,也可以将其推送到 Hugging Face hub!记得获取 Hugging Face token 并添加你的 token!

保存为 GGUF

要将模型保存为 GGUF 格式,Unsloth 使用 llama.cpp。要在本地保存:

model.save_pretrained_gguf("directory", tokenizer, quantization_method = "q4_k_m")
model.save_pretrained_gguf("directory", tokenizer, quantization_method = "q8_0")
model.save_pretrained_gguf("directory", tokenizer, quantization_method = "f16")

要推送到 hub:

model.push_to_hub_gguf("hf_username/directory", tokenizer, quantization_method = "q4_k_m")
model.push_to_hub_gguf("hf_username/directory", tokenizer, quantization_method = "q8_0")

保存至 vLLM

若要保存为 16 位以用于 vLLM,请使用:

model.save_pretrained_merged("model", tokenizer, save_method = "merged_16bit",)
model.push_to_hub_merged("hf/model", tokenizer, save_method = "merged_16bit", token = "")
Update on GitHub