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.17.1).
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배 빠르게 학습하고 VRAM 사용량을 최대 80%까지 줄이는 파인튜닝 및 강화 학습용 오픈소스 프레임워크입니다. Unsloth를 사용하면 학습, 평가, 실행 및 llama.cpp, Ollama, vLLM과 같은 다른 추론 엔진을 활용한 배포가 가능합니다.

이 라이브러리는 학습, 평가, 추론 및 배포를 위한 간결하고 Hugging Face 호환 워크플로를 제공하며 SFTTrainer와 완전히 호환됩니다.

주요 기능

  • 모든 transformer 호환 모델에 대한 학습 지원: 텍스트-음성 변환(TTS), 멀티모달, BERT, RL 등
  • 전체 fine-tuning, 사전 학습, LoRA, QLoRA, 8-bit 학습 및 기타 기능을 지원합니다
  • Linux, Windows, Colab, Kaggle에서 작동하며, NVIDIA GPU를 지원하고 곧 AMD 및 Intel 환경도 지원할 예정입니다
  • TRL이 지원하는 대부분의 기능, RLHF(GSPO, GRPO, DPO 등)를 포함하여 지원합니다
  • 수동으로 작성된 Triton 커널과 수동 역전파 엔진을 통해 정확도 저하가 없음을 보장합니다(0% 근사 오차).

설치

pip install

로컬 설치 (Linux 권장):

pip install unsloth

unsloth를 공식 문서에 따라 설치할 수도 있습니다. 설치 후, 워크플로에 unsloth를 매우 간단하게 통합할 수 있습니다. AutoModelForCausalLM를 로드하는 대신, 다음과 같이 FastLanguageModel만 로드하면 됩니다:

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-bit 양자화를 활성화하여 파인튜닝 시 메모리 사용량을 4분의 1로 줄입니다. 비활성화하면 LoRA 16-bit 파인튜닝을 활성화할 수 있습니다.
  • 전체 파인튜닝(FFT)을 활성화하려면 full_finetuning = True로 설정합니다. 8-bit 파인튜닝을 사용하려면 load_in_8bit = True로 설정합니다. 참고: 한 번에 하나의 학습 방법만 True로 설정할 수 있습니다.

Unsloth의 하이퍼파라미터 및 기능 설정에 대한 자세한 내용은 여기서 문서 가이드를 참고하세요.

모델 저장

Unsloth를 사용하면 파인튜닝된 모델을 LoRA 어댑터라는 작은 파일로 직접 저장할 수 있습니다. 모델을 업로드하려면 Hugging Face 허브에 푸시하는 것도 가능합니다! Hugging Face 토큰을 발급받아 토큰을 추가하는 것을 잊지 마세요!

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")

허브에 푸시하려면:

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에 저장

vLLM에 16-bit으로 저장하려면 다음을 사용하세요:

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