LLM) Quantization 방법론 알아보기 (GPTQ | QAT | AWQ | GGUF | GGML | PTQ)

2024. 4. 29. 22:30관심있는 주제/LLM

728x90

양자화 기술은 모델을 압축하여 빠르고 효율적으로 만드는 기술입니다. 모델의 가중치와 활성화 값을 줄여 메모리를 절약하고 연산 속도를 높입니다. 이 글은 여러 양자화 기술을 단계별로 설명하고, 코드를 제공하여 사용자가 직접 모델 압축을 수행할 수 있도록 합니다. 이를 통해 머신 러닝 모델을 최적화하고 더 효율적으로 활용할 수 있습니다.

 

크게 요즘 많이 나오는 방법론은 다음과 같습니다

  • Quantization
  • GPTQ
  • GGUF/GGML
  • QAT
  • AWQ

  • PTQ  (Post-training Quantization) - 훈련 후 양자화
    • GPTQ
    • GGUF/GGML
    • QLORA’s 4 bits 
  • QAT (Quantization-Aware Training) - 훈련하면서 양자화
  • AWQ
    • QAT에 일부 기법 사용 

PTQ                                                                                                     QAT

Quantization 이란?

양자화는 높은 정밀도의 숫자를 낮은 정밀도의 숫자로 변환하는 것을 의미합니다. 

낮은 정밀도의 숫자는 디스크의 작은 공간에 저장될 수 있어서 메모리 요구량을 줄입니다. 

개념을 명확하게 이해하기 위해 간단한 양자화 예제부터 시작해 보겠습니다.

 


이제 FP16 형식의 25개의 가중치 값이 있는 행렬이 있다고 가정해 보겠습니다.

우리는 이러한 값들을 int8 양자화해야 합니다. 아래는 그 과정입니다.

  1. 이전 범위 = FP16 형식의 최대 가중치 값 - FP16 형식의 최소 가중치 값 = 0.932–0.0609 = 0.871
  2. 새로운 범위 = Int8은 -128부터 127까지의 숫자를 가집니다. 따라서 범위 = 127-(-128) = 255
  3. 스케일 = 새로운 범위의 최대 값 / 이전 범위의 최대 값 = 127 / 0.932 = 136.24724986904138
  4. 양자화된 값 = (스케일 * 원래 값)을 반올림한 값
  5. 역 양자화된 값 = 양자화된 값 / 스케일
  6. 반올림 오차 - 여기서 주목할 중요한 점은 역 양자화를 다시 FP16 형식으로 수행할 때 숫자가 완전히 동일하지 않다는 것입니다.
    첫 번째 요소인 0.5415는 0.543이 됩니다. 대부분의 요소에서 동일한 문제를 확인할 수 있습니다. 이것이 양자화 - 역 양자화 과정의 결과인 오차입니다.

4) 양자화된
5) 역 양자화된 값

GPTQ (Post-Training Quantization for GPT Models)


GPTQ는 사후 훈련 양자화( post training quantization ) 방법입니다.

이는 사전 훈련된 LLM을 간단히 모델 매개변수를 낮은 정밀도로 변환하는 것을 의미합니다.

GPTQ는 GPU에서 선호되며 CPU에서는 사용되지 않습니다.

 

아래는 GPTQ의 다양한 유형입니다.

  • Static Range  GPTQ: 가중치 및 활성화를 낮은 정밀도로 변환할 수 있습니다.
  • Dynamic Range  GPTQ: 가중치를 낮은 정밀도로 변환하고 활성화를 낮은 정밀도로 변환하는 함수를 개발합니다. 이 함수는 추론 중에 활성화를 양자화하는 데 사용됩니다.
  • Weight Quantization : 양자화는 가중치와/또는 모델의 활성화의 정밀도를 줄여 공간을 절약합니다. 여기서 추론 시에 입력은 여전히 float32 형식이며 가중치와 입력의 계산을 위해 가중치를 동일한 정밀도로 다시 가져와야 합니다. 그러나 이 과정은 반올림 문제로 인해 정확도 손실을 야기할 수 있습니다.

Static Range Quantization의 알고리즘 개요

GPTQ 알고리즘에서 신경망에 대해 레이어 단위로 양자화합니다.
각 레이어의 가중치 메트릭을 열 그룹으로 나눕니다.
이 그룹들은 반복적으로 처리됩니다. 

예를 들어, GPTQ의 그룹 크기 매개변수를 128로 설정하면 가중치 메트릭이 각각 128개의 열로 구성된 그룹으로 나누어집니다.
각 그룹에 있는 열의 데이터를 양자화한 후, 해당 그룹의 나머지 가중치는 양자화로 인한 오차를 보상하기 위해 업데이트됩니다.
한 그룹의 열에 대한 데이터가 처리되면 전체 행렬의 나머지 열(다른 그룹)도 오차를 보상하기 위해 업데이트됩니다.
이 전체 과정은 "지연 배치 업데이트"라고도 합니다.

 

GPTQ Code

 

!pip install auto_gptq
import torch
from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig
from transformers import TextGenerationPipeline
from transformers import AutoTokenizer

pretrained_model_name = "bigscience/bloom-3b" 
quantize_config = BaseQuantizeConfig(bits=4, group_size=128)

# Tensors of bloom are of float16. Hence, torch_dtype=torch.float16. Do not leave torch_dtype as "auto" as this leads to a warning of implicit dtype conversion
model = AutoGPTQForCausalLM.from_pretrained(pretrained_model_name, quantize_config, trust_remote_code=False, device_map="auto", torch_dtype=torch.float16)  # changing device map to "cuda" does not have any impact on T4 GPU mem usage.
tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name)

# Calibration
examples = [
    tokenizer(
        "Automated machine learning is the process of automating the tasks of applying machine learning to real-world problems. AutoML potentially includes every stage from beginning with a raw dataset to building a machine learning model ready for deployment."
    )
]  # giving only 1 example here for testing. In an real world scenario, you might want to give 500-1000 samples.
model.quantize(examples)

quantized_model_dir = "bloom3b_q4b_gs128"
model.save_quantized(quantized_model_dir)

# Inference with quantized model
device = "cuda:0"  # make use of GPU for inference.
model = AutoGPTQForCausalLM.from_quantized(quantized_model_dir, device=device, torch_dtype=torch.float16)
pipeline = TextGenerationPipeline(model=model, tokenizer=tokenizer, max_new_tokens=50)  
print(pipeline("Automated machine learning is")[0]["generated_text"])
# Sequence length of a model (bloom has seq length of 2048) is total tokens in input & output; 
# max_new_tokens is number of output tokens
# Do note that there is a warning while executing this code that model's sequence length was not in model config. However, what i could find any option to pass the seq length of bloom in configurations.
# The warnings related to fused modules & unsupported model is not valid. The links that i used to validate this are in references.

 

다른 코드

from transformers import AutoModelForCausalLM, AutoTokenizer, GPTQConfig

model_id = "facebook/opt-125m"

tokenizer = AutoTokenizer.from_pretrained(model_id)

quantization_config = GPTQConfig(bits=4, dataset = "c4", tokenizer=tokenizer)

model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", quantization_config=quantization_config)

 

GGUF(GPT-Generated Unified Format) | GGML(GPT-Generated Model Language)

 

GGUF는 GGML의 새로운 버전입니다. 

GGML은 LLM 라이브러리의 C++ 복제본으로, LLaMA 시리즈 및 Falcon 등 여러 LLM을 지원합니다. 

이 라이브러리에서 지원하는 모델은 Apple Silicon(Mac OS)에서도 사용할 수 있습니다. 

Apple Silicon은 CPU와 GPU를 결합한 프로세서로, 이는 Apple의 창의적인 아이디어입니다. 

GGUF는 또한 Windows 및 Linux OS에서도 사용할 수 있습니다. 이는 일반 CPU에서도 이러한 모델을 사용할 수 있음을 의미합니다. 

CPU가 충분하지 않을 경우 몇 개의 레이어를 GPU로 오프로드할 수도 있습니다. 

또한, 2에서 8비트 정밀도까지 다양한 수준의 양자화를 제공합니다. 여기서 아이디어는 원본 LLaMA 모델을 가져와 GGUF 형식으로 변환한 후, 마지막으로 GGUF 형식을 낮은 정밀도로 양자화할 수 있다는 것입니다.

# Install llama.cpp
!git clone https://github.com/ggerganov/llama.cpp
!cd llama.cpp && git pull && make clean && LLAMA_CUBLAS=1 make
!pip install -r llama.cpp/requirements.txt

# Download model
!git lfs install
!git clone https://huggingface.co/Siddharthvij10/MistralSharded2

# Convert weights to fp16
!python llama.cpp/convert.py MistralSharded2 --outtype f16 --outfile "MistralSharded2/mistralsharded2.fp16.bin"

# Quantization - Requires GPU RAM as a mandate. However, does not use much of it.

# As per info on https://huggingface.co/TheBloke/Llama-2-13B-chat-GGML, q4_k_m uses Q6_K for half of the attention.wv and feed_forward.w2 tensors, else Q4_K
!./llama.cpp/quantize "MistralSharded2/mistralsharded2.fp16.bin" "MistralSharded2/mistralsharded2.Q4_K_M.gguf" q4_k_m

import os
# There are 32 layers in mistral 7B. Hence offloading all 32 layers to GPU while loading for inference below.
!./llama.cpp/main -m "MistralSharded2/mistralsharded2.Q4_K_M.gguf" -n 35 --color -ngl 32 -p "Automated machine learning"

 

다른 방식

https://gist.github.com/pdtgct/b8bcbf9220d4d5059b62b1c35615a650

 

Convert HF to GGML

Convert HF to GGML. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

!pip install ctransformers[cuda]
from ctransformers import AutoModelForCausalLM
from transformers import AutoTokenizer, pipeline

# Load LLM and Tokenizer
# Use `gpu_layers` to specify how many layers will be offloaded to the GPU.
model = AutoModelForCausalLM.from_pretrained(
    "TheBloke/zephyr-7B-beta-GGUF",
    model_file="zephyr-7b-beta.Q4_K_M.gguf",
    model_type="mistral", gpu_layers=50, hf=True
)
tokenizer = AutoTokenizer.from_pretrained(
    "HuggingFaceH4/zephyr-7b-beta", use_fast=True
)

# Create a pipeline
pipe = pipeline(model=model, tokenizer=tokenizer, task='text-generation')

# We will use the same prompt as we did originally
outputs = pipe(prompt, max_new_tokens=256)
print(outputs[0]["generated_text"])

 

Quantization Aware Training (QAT)

 


Quantization Aware Training (QAT)은 사전 훈련된 모델 또는 PTQ(Pre-Trained Quantization) 모델로 시작합니다. 이 모델을 QAT를 사용하여 fine tune 합니다. 여기서의 목표는 PTQ 모델을 사용한 경우 발생한 정확도 손실을 복구하는 것입니다.

즉, 모델의 가중치와 활성화를 학습하면서 양자화합니다.

QAT는 forward pass에 영향을 미칩니다. 그러나 backward pass는 영향을 받지 않습니다. QAT에서는 매개변수가 양자화되었을 때 정확도 손실이 발생하지 않는 레이어에 대해 양자화가 수행됩니다. 매개변수가 양자화되면 정확도에 부정적인 영향을 미치는 레이어는 양자화되지 않습니다.

QAT의 기본 아이디어는 해당 레이어의 가중치 정밀도에 따라 입력을 낮은 정밀도로 양자화하는 것입니다. 

또한, 다음 레이어가 요구하는 경우 가중치와 입력의 곱의 출력을 다시 높은 정밀도로 변환하는 것도 처리합니다. 이 입력을 낮은 정밀도로 변환하고 다음 레이어에서 요구하는 경우 출력을 높은 정밀도로 변환하는 프로세스는 "FakeQuant Node Insertion"이라고도 합니다. 이 양자화는 기본 작업으로 양자화하고 다시 양자화하는 과정을 포함하기 때문에 "Fake"로 불립니다.

QAT는 forward pass에 양자화 오류를 추가하고, 이 오류는 backward pass에서 최적화기를 사용하여 조정됩니다. 이렇게 함으로써 모델은 양자화에 의해 도입된 오류를 줄이는 방법을 이해하게 됩니다.

 

! pip uninstall -y tensorflow
! pip install -q tf-nightly  # Use tf-nightly instead of tensorflow since it gets updated with fixes every day
! pip install -q tensorflow-model-optimization  # this lib is used for QAT

import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow_model_optimization as tfmot
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler


### Sample Keras model - Code generated by ChatGPT

# Generate sample data
np.random.seed(0)
data = pd.DataFrame(np.random.rand(1000, 5), columns=['Feature1', 'Feature2', 'Feature3', 'Feature4', 'Feature5'])
target = pd.Series(np.random.randint(0, 2, size=1000), name='Target')

# Split data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=42)

# Standardize features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# Define the Keras model
model = tf.keras.Sequential([
    tf.keras.layers.Dense(64, activation='relu', input_shape=(5,)),
    tf.keras.layers.Dense(32, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# Train the model
model.fit(X_train_scaled, y_train, epochs=10, batch_size=32, validation_split=0.2)

# Evaluate the model
test_loss, test_accuracy = model.evaluate(X_test_scaled, y_test)
print(f'Test Loss: {test_loss}, Test Accuracy: {test_accuracy}')
quant_aware_model = tfmot.quantization.keras.quantize_model(model)
quant_aware_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# Fine tune to create a quant aware model
quant_aware_model.fit(X_train_scaled, y_train, epochs=10, batch_size=32, validation_split=0.2)

# Evaluate the quant aware model
test_loss, test_accuracy = quant_aware_model.evaluate(X_test_scaled, y_test)
print(f'Test Loss: {test_loss}, Test Accuracy: {test_accuracy}')

 

pytorch version

# Enable quantization-aware training
model.qconfig = torch.quantization.default_qconfig

# Convert the model to quantized version
quantized_model = torch.quantization.convert(model, inplace=False)

# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(quantized_model.parameters(), lr=0.01, momentum=0.9)

# Train the model
for epoch in range(5):  # loop over the dataset multiple times

    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # Get the inputs and labels
        inputs, labels = data
        inputs, labels = inputs.to(device), labels.to(device)

        # Zero the gradients
        optimizer.zero_grad()

        # Forward pass
        outputs = quantized_model(inputs)

        # Compute the loss
        loss = criterion(outputs, labels)

        # Backward pass
        loss.backward()

        # Optimize
        optimizer.step()

# Evaluate the model
correct = 0
total = 0
with torch.no_grad():
    for data in testloader:
        inputs, labels = data
        inputs, labels = inputs.to(device), labels.to(device)
        outputs = quantized_model(inputs)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total))

# Save the model
torch.save(quantized_model, 'mnist_model_quantized.pt')

 

 

AWQ(Activation-Aware Quantization for LLMs)

 

이 방법은 GPU 또는 CPU에서 사용하기 위한 것입니다. 이 방법에서는 모든 가중치를 양자화하지 않고 모델의 유효성을 유지하기 위해 중요하지 않은 가중치를 양자화합니다.

알고리즘:
보정: 사전 훈련된 LLM에 샘플 데이터를 전달하여 가중치와 활성화의 분포를 파악합니다.
중요한 활성화와 해당 가중치를 파악합니다.
스케일링: 이러한 핵심 엔티티를 확장하면서 나머지 가중치는 더 낮은 정밀도로 양자화합니다.
중요한 가중치를 확대하고 중요하지 않은 가중치의 정밀도를 낮추므로 양자화로 인한 정확도 손실을 최소화합니다.

 

사용 코드

1. 모델 설정 및 양자화

  1. 초기화: 모델 경로를 정의하고 양자화된 버전에 대한 이름과 디렉터리를 생성합니다.
  2. 모델 및 토크나이저 로드: AutoAWSForCausalLM과 AutoTokenizer를 사용하여 사전 훈련된 모델과 토크나이저를 로드합니다.
  3. 양자화 실행: 사전 정의된 quant_config을 적용하여 중요도가 낮은 가중치에 대해 model.quantize() 메서드를 사용합니다.
  4. 저장: 양자화된 모델을 model.save()를 사용하여 저장하고, 토크나이저는 tokenizer.save_pretrained()를 사용하여 저장합니다.
from awq import AutoAWQForCausalLM
from transformers import AutoTokenizer

import torch
model_path = "" # add hugging face model path
quant_name =  model_path.split("/")[-1] + "-AWQ"
quant_path = "AdithyaSK/" + quant_name # Replace by your username/org
quant_config = {"zero_point" : True, "q_group_size":128,"w_bit":4}
# Load model
model = AutoAWQForCausalLM.from_pretrained(model_path , device_map="auto")
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code = True)
# Quantize
model.quantize(tokenizer,quant_config=quant_config)
model.save(quant_name, safetensors=True , shard_size="10GB")
tokenizer.save_pretrained(quant_name)

 

2. Hugging Face Hub에 모델 및 토크나이저 업로드

  1. HfApi 사용: huggingface_hub에서 HfApi를 사용하여 양자화된 모델 파일을 지정된 저장소(repo_id)에 업로드합니다.
  2. 파일 업로드: repo_id에 대한 경로와 repo_type으로 'model'을 지정하여 업로드합니다.
from hugginface_hub import HfApi

api = HfApi()
path_in_repo = "model.safetensors"
local_file_path = "./"+ quant_name + "/" + path_in_repo
repo_id = "AdithyaSK/" + quant_name
api.upload_file(
    path_or_fileobj = local_file_path,
    path_in_repo = path_in_repo,
    repo_id = repo_id,
    repo_type = "model"
)

 

3단계: Non 모델 파일 업로드

  1. 파일 경로 목록: 다양한 설정 및 토큰 관련 파일을 포함하는 local_file_paths 목록을 제공합니다.
  2. 파일 업로드 반복: 각 파일을 반복하면서 Hugging Face Hub 저장소에 업로드하고, 모델의 완전성을 향상합니다.
from huggingface_hub import HfApi

api = HfApi()
repo_id = "AdithyaSK/"+ quant_name
local_file_paths = [
    "./"+ quant_name + "/config.json",
    "./"+ quant_name + "/pytorch_model.bin",
    "./"+ quant_name + "/special_tokens_map.json",
    "./"+ quant_name + "/tokenizer_config.json",
    "./"+ quant_name + "/tokenizer.json",
]
# Loop through each file and upload
for local_file_path in local_file_paths:
    file_name = local_file_path.split("/")[-1]
    path_in_repo = file_name
    api.upload_file(
        path_or_fileobj=local_file_path,
        path_in_repo=path_in_repo,
        repo_id=repo_id,
        repo_type="model"
    )
    print(f"Uploaded {file_name} to {repo_id}")

 

4단계: AWQ를 사용한 추론 실행

  1. AWQ 모델 로드: AutoAWQForCausalLM 클래스를 사용하여 양자화된 모델에서 추론을 실행합니다.
  2. 모델 및 토크나이저 설정: 모델은 "safetensors" 형식에 맞게 설정되어야 하며, 필요한 구성이 설정된 토크나이저와 함께 로드됩니다.
## Load AWQ Model

from awq import AutoAWQForCausalLM
from transformers import AutoTokenizer
### Note that the model must be in safetensors format!
# model_name_or_path = "TheBloke/Llama-2-7b-Chat-AWQ"
model_name_or_path = "AdithyaSK/"
model = AutoAWQForCausalLM.from_quantized(model_name_or_path, fuse_layer=True,trust_remote_code = False, safetensors = True)
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, trust_remote_code = False)

 

5단계: 출력 생성

  1. 프롬프트 정의 및 포맷: 상호작용을 위해 “users” 및 “assistant” 토큰과 함께 프롬프트를 정의하고 포맷팅 합니다.
  2. 프롬프트 토큰화 및 텐서 변환: 프롬프트를 토큰화하고 PyTorch 텐서로 변환합니다.
  3. 출력 생성: model.generate()를 사용하여 출력을 생성하고, 생성된 출력을 디코드 하여 최종 응답을 얻습니다.
prompt = "Who played the character Iron man?"

fromatted_prompt = f"users\n{prompt}\n assistant \n"
tokens = tokenizer(fromatted_prompt, return_tensors="pt").input_ids.cuda()
# Generate Output
generation_output = model.generate(tokens, do_sample=False, max_new_tokes=512)
print(tokenizer.decode(generation_output[0], skip_special_tokens=True))

 

 

AWQ의 장점:

  • 효율성 증가: AWQ는 32비트에서 8/4/2비트 가중치로의 모델 압축을 4배에서 8배까지 가능하게 하며, 이는 저장 공간 및 처리 능력을 현저히 줄여줍니다.
  • 빠른 추론 속도: INT8/4 하드웨어에서 최대 3배 빠른 추론을 제공하여 사용자 경험을 개선하고 리소스 사용을 최소화합니다.
  • 높은 정확도 유지: 단순 반올림 양자화보다 정확도를 훨씬 더 잘 유지하며, 모델 재학습 없이도 다양한 데이터셋에 걸쳐 견고하게 작동합니다.
  • 범용적 통합: AWQ는 ONNX Runtime, PyTorch, TensorFlow Lite 등과 같은 인기 있는 오픈 소스 모델 배포 도구에 통합되어 있어, 생산화를 단순화합니다.


AWQ의 단점:

  • 구현 복잡성: 초기 설정과 구성이 복잡할 수 있으며, 특히 새로운 사용자에게는 양자화 과정의 세밀한 조정이 요구될 수 있습니다.
  • 하드웨어 의존성: 최대 성능을 달성하기 위해서는 특수화된 INT8/4 하드웨어가 필요할 수 있어, 모든 환경에서의 배포가 제한될 수 있습니다

결론

 

양자화는 머신러닝 모델의 가중치와 활성화 값을 낮은 정밀도의 숫자로 변환함으로써 메모리 사용량을 줄이고, 연산 속도를 향상시키는 기술입니다. 이 글은 다양한 양자화 방법을 소개하고, 사용자가 모델을 효율적으로 압축하고 최적화할 수 있도록 단계별 코드 예제를 제공합니다.

양자화 방법론 요약

  1. Post-training Quantization (PTQ):
    1. GPTQ: 사후 훈련 양자화 방법으로, GPU에서 선호되며, 가중치 및 활성화를 낮은 정밀도로 변환합니다.
    2. GGUF/GGML: 특히 CPU 최적화에 초점을 맞춘 방법으로, Apple Silicon과 같은 하드웨어에서도 효과적입니다.
    3. QLoRa's 4 bits: 데이터 세트와 함께 사용하여 가중치와 활성화 값을 4비트 정밀도로 낮추는 방법입니다.
  2. Quantization-Aware Training (QAT):
    1. 훈련 과정 중에 양자화를 고려하여 모델을 최적화합니다.
    2. TensorFlow, PyTorch, Huggingface: 이들 플랫폼은 QAT를 지원하여, 학습 중에 모델이 양자화된 상태에서도 정확도를 유지하도록 돕습니다.
    3. QAT는 forward pass에서 양자화 오류를 추가하고, 이를 통해 모델이 양자화에 의해 도입된 오류를 줄이는 방법을 학습합니다.
  3. Activation-Aware Quantization (AWQ):
    1. 중요하지 않은 가중치는 낮은 정밀도로, 중요한 가중치는 높은 정밀도로 유지하는 방식으로 양자화를 진행합니다.
      이 방법은 GPU 또는 CPU에서 사용 가능하며, 양자화로 인한 정확도 손실을 최소화합니다.

구현 및 코드 예제

 

각 양자화 방법에 대해 실제 구현 예제와 함께, 양자화 과정을 진행하는 코드가 제공됩니다. 이를 통해 사용자는 실제 양자화 절차를 이해하고 자신의 모델에 적용할 수 있습니다.

 

양자화의 장단점

  • 장점: 메모리 절약, 추론 속도 향상, 다양한 하드웨어와의 호환성.
  • 단점: 구현의 복잡성, 정밀도 손실 가능성, 특정 하드웨어에 대한 의존성.

 

 

참고 링크

https://medium.com/@siddharth.vij10/llm-quantization-gptq-qat-awq-gguf-ggml-ptq-2e172cd1b3b5
https://www.tensorops.ai/post/what-are-quantized-llms
https://www.maartengrootendorst.com/blog/quantization/
https://colab.research.google.com/drive/1rt318Ew-5dDw21YZx2zK2vnxbsuDAchH?usp=sharing
https://deci.ai/blog/ggml-vs-gguf-comparing-formats-amp-top-5-methods-for-running-gguf-files/
https://medium.com/@jan_marcel_kezmann/master-the-art-of-quantization-a-practical-guide-e74d7aad24f9
 
 
 
728x90