본문 바로가기
C.W.K.
Stream
Lesson 02 of 06 · published

양자화: fp32에서 int8과 int4까지

~14 min · quantization, int8, int4, torchao

Level 0텐서 탐구자
0 XP0/62 lessons0/13 achievements
0/120 XP to next level120 XP to go0% complete

작은 정확도 손실을 큰 크기·속도 이득과 맞바꿔

현대적인 하드웨어는 int8 행렬곱을 fp32보다 훨씬 빠르게 처리하며 경우에 따라 4배까지 차이 나. 메모리 사용량도 비슷한 비율로 줄어. 대신 정확도가 조금 떨어질 수 있어. 제대로 양자화한 모델은 일반적인 벤치마크에서 보통 1% 미만의 손실을 보이지만 작업별 검증은 꼭 필요해. LLM의 int4 가중치 전용 양자화는 2025~2026년의 활발한 연구 영역으로, 70억 개 가중치 자체를 약 3.5~4GB에 담을 수 있어.

양자화의 세 가지 방식

  • 동적 양자화: 가중치는 int8로 저장하고 활성화는 추론 중에 양자화해. 코드 한 줄로 적용할 수 있고 선형 계층이 대부분인 Transformer 계열 모델에 잘 맞아.
  • 정적 학습 후 양자화(PTQ): 가중치와 활성화를 모두 양자화하고 작은 데이터셋으로 범위를 보정해. 동적 방식보다 빠를 수 있지만 구성이 더 복잡해.
  • 양자화 인식 학습(QAT): 순전파에 모의 양자화를 넣어 학습해. 정확도를 가장 잘 보존하지만 준비 비용도 가장 커.

torchao: 현대적인 API

기존 torch.quantizationtorch.ao.quantization의 기능은 독립형 torchao 패키지로 이동하고 있어. 현대적인 int8, int4, 가중치 전용 양자화와 GPTQ, AWQ 기법이 이곳에 모여 있어. 새 프로젝트라면 torchao에서 시작해.

양자화가 도움이 되는 곳과 그렇지 않은 곳

  • 도움이 되는 곳: 큰 Transformer FFN, 큰 임베딩 테이블, LLM 서빙.
  • 도움이 적은 곳: 연산 호출 비용이 지배하는 작은 모델이나 비선형 연산이 많은 모델. 양자화되지 않은 부분이 병목으로 남을 수 있어.

Code

동적 int8 양자화: Transformer용 한 줄 설정·python
import os
import torch
import torch.nn as nn
from transformers import AutoModelForSequenceClassification

model = AutoModelForSequenceClassification.from_pretrained(
    "distilbert-base-uncased-finetuned-sst-2-english"
)
model.eval()

quantized = torch.quantization.quantize_dynamic(
    model, {nn.Linear}, dtype=torch.qint8,
)

# Compare disk size
torch.save(model.state_dict(), '/tmp/fp32.pt')
torch.save(quantized.state_dict(), '/tmp/int8.pt')
print(f"fp32: {os.path.getsize('/tmp/fp32.pt')/1e6:.1f} MB")
print(f"int8: {os.path.getsize('/tmp/int8.pt')/1e6:.1f} MB")
torchao: int8 가중치 전용 양자화·python
# pip install torchao
import torch
import torchao
from torchao.quantization import int8_weight_only
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("gpt2")

# Apply int8 weight-only quant in place
torchao.quantize_(model, int8_weight_only())

# Use the model normally — the quantized layers handle dequant in their forward
torchao: LLM용 int4 가중치 전용 양자화·python
import torchao
from torchao.quantization import int4_weight_only
from transformers import AutoModelForCausalLM

# int4 — even smaller, designed for LLMs
# group_size controls the granularity: smaller groups = better accuracy, more overhead
model = AutoModelForCausalLM.from_pretrained("gpt2")
torchao.quantize_(model, int4_weight_only(group_size=128))

# A 7B-param model at fp16 = ~14GB; at int4 = ~3.5GB
# That's the difference between "needs an A100" and "fits on a 4090"
양자화 후 정확도 검증: 항상·python
import torch

# Run both fp32 and quantized model on a calibration / val set
# Compare outputs on a per-sample basis

def compare_models(fp32_model, quant_model, val_loader):
    fp32_model.eval(); quant_model.eval()
    abs_diff_total = 0
    n = 0
    with torch.inference_mode():
        for x, y in val_loader:
            out_fp = fp32_model(x).logits
            out_q  = quant_model(x).logits
            abs_diff_total += (out_fp - out_q).abs().mean().item()
            n += 1
    print(f"mean |fp32 - quantized| logit diff: {abs_diff_total / n:.4f}")
    # Also recompute task accuracy on both — that's the number that matters

External links

Exercise

Hugging Face Transformer 하나를 골라 int8 동적 양자화를 적용해 봐. distilbert는 작고 빨라 시험하기 좋아. (a) 디스크 크기, (b) 작은 배치의 추론 지연 시간, (c) 별도 검증 데이터의 정확도를 비교해. 수치를 표로 저장해 두면 양자화한 모델을 배포하기 전에 관계자와 판단 근거를 공유할 수 있어.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.