Intel Extension for Transformers Pipeline을 사용한 Huggingface 모델의 Weight-Only Quantization

Hugging Face 모델은 WeightOnlyQuantPipeline 클래스를 통해 Weight-Only quantization으로 로컬에서 실행할 수 있습니다. Hugging Face Model Hub는 120,000개 이상의 모델, 20,000개의 데이터셋, 50,000개의 데모 앱(Spaces)을 호스팅하며, 모두 오픈 소스이고 공개적으로 사용 가능하며, 사람들이 쉽게 협업하고 함께 ML을 구축할 수 있는 온라인 플랫폼입니다. 이러한 모델들은 이 로컬 pipeline wrapper 클래스를 통해 LangChain에서 호출할 수 있습니다. 사용하려면 transformers python 패키지pytorch, intel-extension-for-transformers가 설치되어 있어야 합니다.
pip install transformers --quiet
pip install intel-extension-for-transformers

Model 로딩

모델은 from_model_id 메서드를 사용하여 모델 파라미터를 지정하여 로드할 수 있습니다. 모델 파라미터에는 intel_extension_for_transformers의 WeightOnlyQuantConfig 클래스가 포함됩니다.
from intel_extension_for_transformers.transformers import WeightOnlyQuantConfig
from langchain_community.llms.weight_only_quantization import WeightOnlyQuantPipeline

conf = WeightOnlyQuantConfig(weight_dtype="nf4")
hf = WeightOnlyQuantPipeline.from_model_id(
    model_id="google/flan-t5-large",
    task="text2text-generation",
    quantization_config=conf,
    pipeline_kwargs={"max_new_tokens": 10},
)
기존 transformers pipeline을 직접 전달하여 로드할 수도 있습니다.
from intel_extension_for_transformers.transformers import AutoModelForSeq2SeqLM
from transformers import AutoTokenizer, pipeline

model_id = "google/flan-t5-large"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
pipe = pipeline(
    "text2text-generation", model=model, tokenizer=tokenizer, max_new_tokens=10
)
hf = WeightOnlyQuantPipeline(pipeline=pipe)

Chain 생성

모델이 메모리에 로드되면 prompt와 결합하여 chain을 구성할 수 있습니다.
from langchain_core.prompts import PromptTemplate

template = """Question: {question}

Answer: Let's think step by step."""
prompt = PromptTemplate.from_template(template)

chain = prompt | hf

question = "What is electroencephalography?"

print(chain.invoke({"question": question}))

CPU Inference

현재 intel-extension-for-transformers는 CPU 디바이스 inference만 지원합니다. 곧 Intel GPU를 지원할 예정입니다. CPU가 있는 머신에서 실행할 때 device="cpu" 또는 device=-1 파라미터를 지정하여 모델을 CPU 디바이스에 배치할 수 있습니다. CPU inference의 기본값은 -1입니다.
conf = WeightOnlyQuantConfig(weight_dtype="nf4")
llm = WeightOnlyQuantPipeline.from_model_id(
    model_id="google/flan-t5-large",
    task="text2text-generation",
    quantization_config=conf,
    pipeline_kwargs={"max_new_tokens": 10},
)

template = """Question: {question}

Answer: Let's think step by step."""
prompt = PromptTemplate.from_template(template)

chain = prompt | llm

question = "What is electroencephalography?"

print(chain.invoke({"question": question}))

Batch CPU Inference

CPU에서 배치 모드로 inference를 실행할 수도 있습니다.
conf = WeightOnlyQuantConfig(weight_dtype="nf4")
llm = WeightOnlyQuantPipeline.from_model_id(
    model_id="google/flan-t5-large",
    task="text2text-generation",
    quantization_config=conf,
    pipeline_kwargs={"max_new_tokens": 10},
)

chain = prompt | llm.bind(stop=["\n\n"])

questions = []
for i in range(4):
    questions.append({"question": f"What is the number {i} in french?"})

answers = chain.batch(questions)
for answer in answers:
    print(answer)

Intel-extension-for-transformers에서 지원하는 데이터 타입

저장을 위해 가중치를 다음 데이터 타입으로 양자화하는 것을 지원합니다(WeightOnlyQuantConfig의 weight_dtype):
  • int8: 8비트 데이터 타입을 사용합니다.
  • int4_fullrange: 일반적인 int4 범위 [-7,7]와 비교하여 int4 범위의 -8 값을 사용합니다.
  • int4_clip: int4 범위 내의 값을 클리핑하고 유지하며, 나머지는 0으로 설정합니다.
  • nf4: 정규화된 float 4비트 데이터 타입을 사용합니다.
  • fp4_e2m1: 일반 float 4비트 데이터 타입을 사용합니다. “e2”는 지수에 2비트가 사용됨을 의미하고, “m1”은 가수에 1비트가 사용됨을 의미합니다.
이러한 기술들은 가중치를 4비트 또는 8비트로 저장하지만, 계산은 여전히 float32, bfloat16 또는 int8(WeightOnlyQuantConfig의 compute_dtype)로 수행됩니다:
  • fp32: float32 데이터 타입을 사용하여 계산합니다.
  • bf16: bfloat16 데이터 타입을 사용하여 계산합니다.
  • int8: 8비트 데이터 타입을 사용하여 계산합니다.

지원되는 알고리즘 매트릭스

intel-extension-for-transformers에서 지원하는 양자화 알고리즘(WeightOnlyQuantConfig의 algorithm):
AlgorithmsPyTorchLLM Runtime
RTN
AWQstay tuned
TEQstay tuned
RTN: 매우 직관적으로 생각할 수 있는 양자화 방법입니다. 추가 데이터셋이 필요하지 않으며 매우 빠른 양자화 방법입니다. 일반적으로 RTN은 가중치를 균일하게 분포된 정수 데이터 타입으로 변환하지만, Qlora와 같은 일부 알고리즘은 비균일 NF4 데이터 타입을 제안하고 이론적 최적성을 증명합니다.
AWQ: 1%의 중요한 가중치만 보호해도 양자화 오류를 크게 줄일 수 있음을 증명했습니다. 중요한 가중치 채널은 채널별 활성화 및 가중치의 분포를 관찰하여 선택됩니다. 중요한 가중치는 보존을 위해 양자화 전에 큰 스케일 팩터를 곱한 후 양자화됩니다.
TEQ: Weight-only quantization에서 FP32 정밀도를 보존하는 훈련 가능한 등가 변환입니다. AWQ에서 영감을 받았으며 활성화와 가중치 간의 최적 채널별 스케일링 팩터를 검색하기 위한 새로운 솔루션을 제공합니다.

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I