Transformers documentation

모델을 파인튜닝합니다

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

모델을 파인튜닝합니다

양자화된 가중치는 그라디언트로 직접 업데이트할 수 없으므로, 동결된 양자화 가중치 위에 작은 어댑터를 학습시켜 양자화 모델을 파인튜닝합니다. 4비트 모델에서 LoRA 어댑터를 학습하는 방식은 QLoRA로 알려져 있으며, 이를 통해 bf16에서는 메모리에 맞지 않는 모델을 파인튜닝할 수 있습니다.

Trainer는 학습 전에 모델을 확인하여 다음을 보장합니다:

  • 양자화 방법은 학습을 지원합니다. 방법 선택의 Fine-tune 열을 참조하세요.
  • 모델에는 학습 가능한 어댑터가 연결되어 있습니다. 양자화 인식 학습을 지원하는 메서드는 예외이며, 아래에서 다룹니다.
  • 모델이 torch.compile로 컴파일되지 않았습니다.

어댑터 학습

PEFT를 설치합니다.

pip install -U peft

학습을 지원하는 메서드로 모델을 로드하고, add_adapter()로 LoRA 어댑터를 연결한 뒤, 모델을 Trainer에 전달합니다. 아래 예제는 4-bit bitsandbytes를 사용하며, train_dataset가 토큰화된 데이터셋이라고 가정합니다.

import torch
from peft import LoraConfig
from transformers import AutoModelForCausalLM, BitsAndBytesConfig, Trainer, TrainingArguments

quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
)
model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen3-0.6B",
    quantization_config=quantization_config,
    device_map="auto",
)

lora_config = LoraConfig(r=16, lora_alpha=32, target_modules="all-linear", task_type="CAUSAL_LM")
model.add_adapter(lora_config)

trainer = Trainer(
    model=model,
    args=TrainingArguments(output_dir="qwen3-qlora", bf16=True),
    train_dataset=train_dataset,
)
trainer.train()

어댑터 가중치만 학습됩니다. 양자화된 베이스 가중치는 고정된 상태로 유지됩니다.

어댑터 저장

save_pretrained()는 몇 메가바이트에 불과한 어댑터 가중치만 저장합니다. 이는 양자화 가중치를 저장할 수 없는 방법을 포함하여 모든 방법에서 작동합니다.

model.save_pretrained("qwen3-qlora-adapter")

어댑터를 사용하려면 동일한 양자화 구성으로 베이스 모델을 로드한 후, 그 위에 어댑터를 로드하세요. 자세한 내용은 어댑터 로드를 참조하세요.

양자화 인식 학습

BitNet과 compressed-tensors는 가중치가 학습 가능한 형태를 유지하는 한 어댑터 없이 전체 모델을 학습할 수 있습니다.

  • BitNet은 BitNetQuantConfig에 linear_class="autobitlinear"와 quantization_mode="online"가 필요합니다.
  • compressed-tensors는 압축되지 않은 체크포인트 또는 CompressedTensorsConfig의 dequantize=True가 필요합니다. FP8 커널을 사용하는 체크포인트로는 학습을 수행할 수 없습니다.

양자화 인식 학습이 학습 후 양자화와 어떻게 다른지 확인하려면 Quantization concepts를 참조하세요.

Update on GitHub