Một model 70B ở FP16 cần 140GB. Chỉ riêng weight đã cần hai A100. Quantize xuống FP8: một GPU 80GB. INT4: một chiếc MacBook.
Mục tiêu bài học
- Triển khai symmetric và asymmetric quantization từ FP16 xuống INT8 và INT4, gồm cả per-tensor và per-channel scaling
- Tính lượng bộ nhớ tiết kiệm được nhờ quantization và xác định precision nào vừa với VRAM của một GPU cho trước
- Giải thích sự khác nhau giữa post-training quantization (PTQ) và quantization-aware training (QAT)
- Dùng GPTQ hoặc AWQ để quantize một model thật và đo sự đánh đổi giữa độ chính xác và bộ nhớ trên một benchmark
Vấn đề
Llama 3 70B có 70 tỷ parameter. Mỗi parameter là một số dấu phẩy động 16-bit. Tức là 140 tỷ byte. 140GB. Một A100 chỉ có 80GB VRAM. Bạn thậm chí không thể nạp weight lên một GPU, chưa nói đến chạy inference. Bạn cần hai A100, mỗi chiếc $2/giờ, chỉ để phục vụ một model.
Nhưng dùng 16 bit cho mỗi parameter rất lãng phí. Phần lớn weight trong neural network tập trung gần số không. Gần như toàn bộ dải giá trị của FP16 (từ 0.000000059 đến 65,504) không được dùng đến. Nếu đo phân phối weight thực tế trong Llama 3 70B, bạn sẽ thấy 95% nằm trong khoảng -0.1 đến +0.1. Bạn đang dùng 16 bit để biểu diễn những giá trị có thể nằm gọn trong 4 bit.
Quantization thay các số có precision cao bằng những số có precision thấp hơn. Từ FP16 xuống FP8, bộ nhớ giảm một nửa. Từ FP16 xuống INT4, bộ nhớ còn một phần tư. Model 140GB đó còn 35GB. Nó vừa với một GPU phổ thông. Đẩy xuống quantization 2-bit (mạnh tay, mất thông tin, nhưng vẫn dùng được cho một số tác vụ) thì cùng model đó có thể chạy trên laptop 16GB.
Cái giá là độ chính xác. Mỗi bit bị loại bỏ đều làm mất thông tin. Câu hỏi là bạn mất bao nhiêu độ chính xác, và mất ở đâu. Một model INT4 được quantize tốt giữ được 95-99% chất lượng của bản gốc trên hầu hết benchmark. Quantize xuống INT4 một cách ngây thơ có thể phá hỏng hoàn toàn model. Khác biệt nằm ở kỹ thuật.
Các bản quantization Llama 3 xuống INT4 bằng GPTQ do cộng đồng thực hiện cho thấy perplexity trên WikiText tăng khoảng 1-2 điểm. Mistral phát hành các checkpoint FP8 của Mixtral 8x22B mà không đo được mức giảm chất lượng nào trên MMLU. Format GGUF là nền tảng cho llama.cpp, giúp các model 70B chạy trên MacBook dùng chip M-series. Quantization không phải mẹo chữa cháy. Đây là cách deploy tiêu chuẩn cho mọi model lớn hơn 7B.
Khái niệm
Các định dạng số: Từng bit làm gì
Mỗi số dấu phẩy động có ba phần: bit dấu, exponent và mantissa (còn gọi là significand). Bit dấu chiếm một bit. Exponent quyết định dải giá trị (số có thể lớn hoặc nhỏ đến mức nào). Mantissa quyết định precision (bạn có bao nhiêu chữ số thập phân).
FP32: [1 sign] [8 exponent] [23 mantissa] = 32 bits
FP16: [1 sign] [5 exponent] [10 mantissa] = 16 bits
BF16: [1 sign] [8 exponent] [7 mantissa] = 16 bits
FP8: [1 sign] [4 exponent] [3 mantissa] = 8 bits (E4M3)
FP8: [1 sign] [5 exponent] [2 mantissa] = 8 bits (E5M2)
INT8: [1 sign] [7 value] = 8 bits (uniform steps)
INT4: [1 sign] [3 value] = 4 bits (16 levels total)FP32 là full precision. 23 bit mantissa cho bạn khoảng 7 chữ số thập phân chính xác. Dải giá trị: khoảng đến . Trước đây, training chỉ dùng FP32. FP32 vẫn được dùng để accumulation (cộng dồn trong lúc nhân ma trận).
FP16 giảm một nửa số bit. 10 bit mantissa cho khoảng 3.3 chữ số thập phân chính xác. Exponent giảm còn 5 bit, khiến dải giá trị thu hẹp đáng kể (giá trị lớn nhất ~65,504). Như vậy là ổn cho weight (vốn tập trung gần số không), nhưng nguy hiểm với activation và gradient vì chúng có thể tăng vọt trong lúc training. Training bằng FP16 cần loss scaling để tránh underflow.
BF16 (Brain Float 16) giữ exponent 8-bit của FP32 nhưng giảm mantissa xuống 7 bit. Cùng dải giá trị với FP32, precision thấp hơn FP16. Google thiết kế BF16 riêng cho deep learning. Trực giác đằng sau nó: với neural network, dải giá trị quan trọng hơn precision. Một gradient bằng sẽ underflow về số không trong FP16 nhưng vẫn tồn tại trong BF16. Một weight bằng 0.07342 được làm tròn thành 0.0734 trong BF16 vẫn đủ gần. Mọi lần training hiện đại đều dùng BF16 hoặc kết hợp BF16/FP32.
FP8 có hai biến thể. E4M3 (4 bit exponent, 3 bit mantissa) được dùng cho weight và activation khi inference. E5M2 (5 bit exponent, 2 bit mantissa) được dùng cho gradient khi training, nơi dải giá trị quan trọng hơn precision. Inference bằng FP8 trên GPU H100 nhanh hơn FP16 30-50% mà gần như không giảm chất lượng.
INT8 là định dạng số nguyên. Không có exponent hay mantissa. Chỉ có 256 giá trị cách đều nhau từ -128 đến 127. Bạn cần một scale factor để ánh xạ weight dạng số dấu phẩy động vào dải này. Ưu điểm: phép tính số nguyên nhanh hơn và tiết kiệm điện hơn phép tính số dấu phẩy động. Phép nhân ma trận INT8 trên A100 đạt 624 TOPS, so với 312 TFLOPS của FP16.
INT4 đi xa hơn. Chỉ có 16 giá trị khả dĩ. Scale factor phải gánh phần lớn công việc. Chất lượng phụ thuộc hoàn toàn vào cách bạn chọn scale và những weight bạn quantize. Các phương pháp INT4 tiên tiến (GPTQ, AWQ) giữ được hơn 95% chất lượng của model gốc.
Quantization hoạt động như thế nào
Thao tác cốt lõi rất đơn giản. Lấy một tensor gồm các giá trị dấu phẩy động, tìm scale factor, nhân, làm tròn đến số nguyên gần nhất, rồi lưu các số nguyên cùng scale factor.
Quantize:
scale = max(abs(tensor)) / max_int_value
quantized = round(tensor / scale)Dequantize:
reconstructed = quantized * scaleVới INT8 dùng dải đối xứng (-127 đến 127):
scale = max(abs(tensor)) / 127
quantized = clamp(round(tensor / scale), -128, 127)Sai số chính là sai số làm tròn. Mỗi giá trị có thể lệch tối đa scale / 2. Tổng sai số trên một layer phụ thuộc vào số lượng weight và mức độ nhạy của model trước những thay đổi nhỏ ở các weight đó.
Per-tensor và per-channel quantization. Per-tensor dùng một scale factor cho toàn bộ ma trận weight. Đơn giản nhưng mất nhiều thông tin: nếu một cột có giá trị lớn còn cột khác có giá trị nhỏ, các giá trị nhỏ sẽ mất phần lớn precision. Per-channel dùng một scale factor cho mỗi output channel (mỗi hàng hoặc cột của ma trận weight). Tốn thêm chỗ lưu (bạn lưu N scale factor thay vì 1) nhưng chất lượng tốt hơn rõ rệt. Mọi phương pháp quantization dùng trong production đều dùng per-channel hoặc mức chia nhỏ hơn.
Asymmetric quantization thêm một độ lệch zero-point: quantized = round(tensor / scale) + zero_point. Cách này xử lý các phân phối không tập trung quanh số không. Chẳng hạn, activation của ReLU luôn không âm. Symmetric quantization lãng phí nửa dải số nguyên cho các giá trị âm không bao giờ xuất hiện. Asymmetric quantization ánh xạ dải giá trị thực tế [min, max] vào toàn bộ dải số nguyên.
Thứ tự mức độ nhạy
Không phải phần nào trong model cũng chịu được quantization như nhau. Có một thứ tự khá rõ.
Weight (chịu được tốt nhất). Weight của model thay đổi chậm trong lúc training và có phân phối gần giống Gaussian, tập trung quanh số không. Chúng quantize tốt. Weight INT8 với scale per-channel cho kết quả gần như không mất chất lượng. INT4 cần phương pháp tinh vi hơn, nhưng vẫn hiệu quả.
Activation (nhạy ở mức vừa). Activation là các giá trị trung gian đi qua network khi inference. Chúng có dải giá trị rộng hơn weight và chứa các outlier. Một attention head có thể tạo ra giá trị activation lớn gấp 100 lần giá trị trung bình. Những outlier này rất quan trọng với chất lượng model. Quantize chúng một cách ngây thơ sẽ làm mất thông tin. Cách xử lý: giữ các outlier channel ở precision cao hơn (LLM.int8()), hoặc dùng scale activation theo từng token hay từng channel.
KV cache (rất nhạy). KV cache lưu các trạng thái attention của tất cả token trước đó. Với context dài, KV cache chiếm phần lớn bộ nhớ. Với model 70B và context 32K, riêng KV cache đã chiếm 40GB ở FP16. Quantize KV cache xuống FP8 hoặc INT8 tiết kiệm rất nhiều bộ nhớ, nhưng mọi sai số sẽ tích lũy qua tất cả phép tính attention về sau. Tác động lên chất lượng tăng theo độ dài chuỗi.
Attention logits (nhạy nhất). Softmax trong attention rất nhạy với những thay đổi nhỏ ở đầu vào. Sai số quantization bằng 0.01 trong một logit trước softmax cũng có thể làm phân phối attention dịch chuyển đáng kể. Phần lớn phương pháp quantization vẫn tính attention ở precision cao hơn (FP16 hoặc BF16), ngay cả khi mọi thứ khác đã được quantize.
PTQ và QAT
Post-Training Quantization (PTQ) quantize một model đã được training. Không cần training lại. Bạn lấy weight FP16, tính scale factor, làm tròn rồi deploy. Nhanh (từ vài phút đến vài giờ) và rẻ. Hoạt động tốt với INT8 và FP8. Với INT4, PTQ đơn giản thường cho kết quả rất tệ vì sai số làm tròn tích lũy. Các phương pháp PTQ nâng cao (GPTQ, AWQ) dùng calibration data để giảm thiểu sai số quantization.
Quantization-Aware Training (QAT) chèn các thao tác quantization giả vào forward pass trong lúc training. Model học cách đặt weight ở những vị trí ít bị sai số làm tròn. Gradient đi qua thao tác quantization giả nhờ straight-through estimator (STE): coi như thao tác làm tròn có gradient bằng 1. QAT tạo ra model INT4 và INT2 tốt hơn PTQ nhưng đòi hỏi một lần training đầy đủ. Google đã dùng QAT để phục vụ Gemini hiệu quả hơn. Meta đã dùng QAT cho một số mục tiêu deploy Llama.
| Khía cạnh | PTQ | QAT |
|---|---|---|
| Chi phí | Vài phút đến vài giờ | Một lần training đầy đủ |
| Chất lượng ở INT8 | Rất tốt (giảm < 0.1%) | Rất tốt |
| Chất lượng ở INT4 | Tốt với GPTQ/AWQ (giảm 1-3%) | Tốt hơn (giảm < 1%) |
| Chất lượng ở INT2 | Kém | Dùng được cho một số tác vụ |
| Calibration data | 128-1024 ví dụ | Toàn bộ training dataset |
| Khi nào dùng | Deploy, lặp thử nhanh | Chất lượng cao nhất ở số bit thấp |
GPTQ, AWQ, GGUF
GPTQ (GPT Quantization) là phương pháp PTQ thực hiện một lần. Nó quantize weight từng layer một, dùng một calibration dataset nhỏ (thường là 128 ví dụ) để đo Hessian (thông tin bậc hai về mức độ nhạy của output đối với từng weight). Những weight mà Hessian xác định là quan trọng sẽ được quantize cẩn thận hơn. GPTQ là phương pháp đầu tiên khiến quantization INT4 trở nên thực tế với LLM. TheBloke trên Hugging Face đã phổ biến GPTQ bằng cách phát hành các phiên bản đã quantize của hàng trăm model.
AWQ (Activation-Aware Weight Quantization) dựa trên quan sát rằng một phần nhỏ weight (khoảng 1%) quan trọng hơn hẳn vì chúng được nhân với các giá trị activation lớn. AWQ dùng calibration data để xác định những weight nổi bật này và scale chúng lên trước khi quantization (rồi scale các activation tương ứng xuống). Nhờ vậy, các weight quan trọng nằm trong dải mà quantization INT4 có độ chính xác cao. AWQ thường đạt chất lượng ngang hoặc nhỉnh hơn GPTQ một chút, đồng thời áp dụng nhanh hơn 1.5-2 lần.
GGUF (GPT-Generated Unified Format) là file format được llama.cpp và hệ sinh thái của nó sử dụng. Nó hỗ trợ mixed quantization: mỗi layer có thể dùng số bit khác nhau. Layer đầu và cuối (embedding và output head) thường được giữ ở precision cao hơn. Các layer giữa dùng INT4 hoặc INT3. File GGUF chứa đủ mọi thứ: weight, tokenizer, metadata đều nằm trong một file. Format này được thiết kế cho CPU inference và Apple Silicon, nơi cách làm thông thường là nạp toàn bộ model vào bộ nhớ rồi chạy phép nhân ma trận trên CPU hoặc Metal GPU. Q4_K_M là biến thể quantization GGUF phổ biến nhất, cân bằng giữa chất lượng và kích thước.
Đo chất lượng
Làm sao biết model đã quantize của bạn vẫn tốt?
Perplexity. Metric phổ biến nhất. Càng thấp càng tốt. Tính perplexity trên một dataset dành riêng để đánh giá (WikiText-2 là lựa chọn tiêu chuẩn) cho cả model gốc lẫn model đã quantize. Mức chênh lệch cho biết quantization đã làm mất bao nhiêu thông tin. Quy tắc tham khảo: chênh lệch < 0.5 là xuất sắc, 0.5-1.0 là tốt, 1.0-2.0 là chấp nhận được với phần lớn tác vụ, > 2.0 nghĩa là đã có vấn đề.
Benchmark theo từng tác vụ. Chạy model đã quantize trên MMLU, HumanEval, GSM8K hoặc bộ eval riêng của bạn. So sánh với model gốc. Quantization ảnh hưởng không đồng đều đến các năng lực khác nhau. Tác vụ toán và code nhạy với việc mất precision hơn kiến thức tổng quát.
So sánh output. Dùng cùng các prompt để tạo câu trả lời từ hai model rồi so sánh. LLM-as-judge (Lesson 10) rất hợp cho việc này. Tính tỷ lệ thắng: model đã quantize đạt chất lượng ngang hoặc tốt hơn model gốc trên bao nhiêu phần trăm prompt?
Latency và throughput. Mục đích của quantization là giúp model nhanh hơn và rẻ hơn. Đo số token mỗi giây, time to first token và mức sử dụng bộ nhớ. Một model đã quantize mà chạy chậm hơn bản gốc thì còn tệ hơn cả vô dụng.
| Model | Format | Kích thước | Perplexity (WikiText-2) | MMLU | Token/giây (A100) |
|---|---|---|---|---|---|
| Llama 3 70B | FP16 | 140GB | 3.12 | 79.5% | 38 |
| Llama 3 70B | FP8 | 70GB | 3.14 | 79.3% | 55 |
| Llama 3 70B | GPTQ INT4 | 35GB | 4.32 | 77.8% | 72 |
| Llama 3 70B | AWQ INT4 | 35GB | 4.18 | 78.1% | 75 |
| Llama 3 70B | GGUF Q4_K_M | 40GB | 4.25 | 77.9% | 28 (CPU) |
Xu hướng rất rõ: FP8 gần như không có cái giá nào. INT4 làm giảm 1-2 điểm MMLU, nhưng tăng gấp đôi throughput và giảm bộ nhớ còn một phần tư. Sự đánh đổi này đáng giá với gần như mọi trường hợp deploy.
Các con số thực tế
FP16 xuống FP8 trên H100: inference nhanh hơn 30-50%, chất lượng giảm < 0.1%. Đây là lựa chọn quá rõ ràng. Mọi hệ thống deploy trên H100 đều nên dùng.
FP16 xuống INT8 (LLM.int8()): giảm một nửa bộ nhớ, chất lượng giảm < 0.5%. Cách tiếp cận mixed-precision giữ các outlier feature ở FP16, còn lại quantize xuống INT8.
FP16 xuống INT4 (GPTQ/AWQ): giảm bộ nhớ 4 lần, chất lượng giảm 1-3% tùy model và phương pháp. Cho phép chạy model 70B trên một GPU 48GB.
FP16 xuống INT4 (GGUF Q4_K_M): giảm bộ nhớ 3.5 lần, chất lượng giảm 1-2%. Được tối ưu cho CPU inference. Một model 70B ở Q4_K_M chiếm khoảng 40GB và chạy ở tốc độ 10-15 token/giây trên M3 Max có 64GB bộ nhớ.
FP16 xuống INT2: giảm bộ nhớ 8 lần, chất lượng giảm 5-15%. Chỉ khả thi với một số tác vụ hẹp mà bạn chấp nhận chất lượng suy giảm. Đây vẫn là hướng nghiên cứu, chưa sẵn sàng dùng rộng rãi trong production.
Tự xây dựng
Bước 1: Biểu diễn các định dạng số
Xây dựng cách biểu diễn từng định dạng ở mức bit để thấy chính xác bit dấu, exponent và mantissa làm gì.
import numpy as np
def float_to_fp32_bits(value):
bits = np.float32(value).view(np.uint32)
sign = (bits >> 31) & 1
exponent = (bits >> 23) & 0xFF
mantissa = bits & 0x7FFFFF
return {"sign": int(sign), "exponent": int(exponent), "mantissa": int(mantissa),
"exponent_bits": format(int(exponent), '08b'),
"mantissa_bits": format(int(mantissa), '023b'),
"value": float(value),
"actual_exponent": int(exponent) - 127}
def float_to_fp16_bits(value):
fp16 = np.float16(value)
bits = fp16.view(np.uint16)
sign = (bits >> 15) & 1
exponent = (bits >> 10) & 0x1F
mantissa = bits & 0x3FF
return {"sign": int(sign), "exponent": int(exponent), "mantissa": int(mantissa),
"exponent_bits": format(int(exponent), '05b'),
"mantissa_bits": format(int(mantissa), '010b'),
"value": float(fp16),
"actual_exponent": int(exponent) - 15}
def float_to_bf16_bits(value):
fp32_bits = np.float32(value).view(np.uint32)
bf16_bits = (fp32_bits >> 16).astype(np.uint16)
sign = (bf16_bits >> 15) & 1
exponent = (bf16_bits >> 7) & 0xFF
mantissa = bf16_bits & 0x7F
reconstructed = np.uint32(bf16_bits.astype(np.uint32) << 16).view(np.float32)
return {"sign": int(sign), "exponent": int(exponent), "mantissa": int(mantissa),
"exponent_bits": format(int(exponent), '08b'),
"mantissa_bits": format(int(mantissa), '07b'),
"value": float(reconstructed),
"actual_exponent": int(exponent) - 127}
def simulate_fp8_e4m3(value):
sign = 1 if value < 0 else 0
abs_val = abs(value)
max_val = 448.0
abs_val = min(abs_val, max_val)
if abs_val == 0:
return {"sign": sign, "exponent": 0, "mantissa": 0, "value": 0.0,
"exponent_bits": "0000", "mantissa_bits": "000"}
exp = int(np.floor(np.log2(abs_val)))
exp = max(-6, min(8, exp))
mantissa_val = abs_val / (2.0 ** exp) - 1.0
mantissa_quant = round(mantissa_val * 8) / 8
mantissa_quant = max(0, min(0.875, mantissa_quant))
reconstructed = (1.0 + mantissa_quant) * (2.0 ** exp)
if sign:
reconstructed = -reconstructed
mantissa_int = int(round(mantissa_quant * 8))
return {"sign": sign, "exponent": exp + 7, "mantissa": mantissa_int,
"exponent_bits": format(exp + 7, '04b'),
"mantissa_bits": format(mantissa_int, '03b'),
"value": float(reconstructed),
"actual_exponent": exp}
def display_format_comparison(value):
fp32 = float_to_fp32_bits(value)
fp16 = float_to_fp16_bits(value)
bf16 = float_to_bf16_bits(value)
fp8 = simulate_fp8_e4m3(value)
print(f"\n Value: {value}")
print(f" {'Format':<8} {'Stored Value':>14} {'Error':>12} {'Sign':>5} {'Exp Bits':>10} {'Man Bits':>25}")
print(f" {'-'*76}")
print(f" {'FP32':<8} {fp32['value']:>14.6f} {abs(fp32['value'] - value):>12.8f} {fp32['sign']:>5} {fp32['exponent_bits']:>10} {fp32['mantissa_bits']:>25}")
print(f" {'FP16':<8} {fp16['value']:>14.6f} {abs(fp16['value'] - value):>12.8f} {fp16['sign']:>5} {fp16['exponent_bits']:>10} {fp16['mantissa_bits']:>25}")
print(f" {'BF16':<8} {bf16['value']:>14.6f} {abs(bf16['value'] - value):>12.8f} {bf16['sign']:>5} {bf16['exponent_bits']:>10} {bf16['mantissa_bits']:>25}")
print(f" {'FP8e4m3':<8} {fp8['value']:>14.6f} {abs(fp8['value'] - value):>12.8f} {fp8['sign']:>5} {fp8['exponent_bits']:>10} {fp8['mantissa_bits']:>25}")Bước 2: Symmetric quantization (per-tensor và per-channel)
Các thao tác quantization cơ bản. Per-tensor dùng một scale cho cả ma trận. Per-channel dùng một scale cho mỗi hàng hoặc cột.
def quantize_symmetric(tensor, num_bits=8):
qmin = -(2 ** (num_bits - 1))
qmax = 2 ** (num_bits - 1) - 1
abs_max = np.max(np.abs(tensor))
if abs_max == 0:
return np.zeros_like(tensor, dtype=np.int32), 1.0
scale = abs_max / qmax
quantized = np.clip(np.round(tensor / scale), qmin, qmax).astype(np.int32)
return quantized, float(scale)
def dequantize_symmetric(quantized, scale):
return quantized.astype(np.float64) * scale
def quantize_per_channel(tensor, num_bits=8, axis=0):
qmin = -(2 ** (num_bits - 1))
qmax = 2 ** (num_bits - 1) - 1
if axis == 0:
abs_max = np.max(np.abs(tensor), axis=1, keepdims=True)
else:
abs_max = np.max(np.abs(tensor), axis=0, keepdims=True)
abs_max = np.where(abs_max == 0, 1.0, abs_max)
scales = abs_max / qmax
quantized = np.clip(np.round(tensor / scales), qmin, qmax).astype(np.int32)
return quantized, scales.squeeze()
def dequantize_per_channel(quantized, scales, axis=0):
if axis == 0:
return quantized.astype(np.float64) * scales.reshape(-1, 1)
else:
return quantized.astype(np.float64) * scales.reshape(1, -1)
def quantize_asymmetric(tensor, num_bits=8):
qmin = 0
qmax = 2 ** num_bits - 1
t_min = np.min(tensor)
t_max = np.max(tensor)
if t_max == t_min:
return np.zeros_like(tensor, dtype=np.int32), 1.0, 0
scale = (t_max - t_min) / (qmax - qmin)
zero_point = int(np.round(qmin - t_min / scale))
zero_point = max(qmin, min(qmax, zero_point))
quantized = np.clip(np.round(tensor / scale + zero_point), qmin, qmax).astype(np.int32)
return quantized, float(scale), int(zero_point)
def dequantize_asymmetric(quantized, scale, zero_point):
return (quantized.astype(np.float64) - zero_point) * scaleBước 3: Đo chất lượng
Đo lượng thông tin bị quantization làm mất. Dùng mean squared error, signal-to-noise ratio và cosine similarity giữa tensor gốc và tensor được tái tạo.
def quantization_error(original, reconstructed):
diff = original - reconstructed
mse = float(np.mean(diff ** 2))
rmse = float(np.sqrt(mse))
max_error = float(np.max(np.abs(diff)))
signal_power = float(np.mean(original ** 2))
snr_db = 10 * np.log10(signal_power / max(mse, 1e-20))
orig_flat = original.flatten()
recon_flat = reconstructed.flatten()
norm_orig = np.linalg.norm(orig_flat)
norm_recon = np.linalg.norm(recon_flat)
if norm_orig == 0 or norm_recon == 0:
cosine_sim = 0.0
else:
cosine_sim = float(np.dot(orig_flat, recon_flat) / (norm_orig * norm_recon))
return {"mse": mse, "rmse": rmse, "max_error": max_error,
"snr_db": float(snr_db), "cosine_similarity": cosine_sim}
def compare_quantization_methods(tensor, num_bits=8):
q_pt, s_pt = quantize_symmetric(tensor, num_bits)
recon_pt = dequantize_symmetric(q_pt, s_pt)
err_pt = quantization_error(tensor, recon_pt)
q_pc, s_pc = quantize_per_channel(tensor, num_bits, axis=0)
recon_pc = dequantize_per_channel(q_pc, s_pc, axis=0)
err_pc = quantization_error(tensor, recon_pc)
q_asym, s_asym, zp = quantize_asymmetric(tensor, num_bits)
recon_asym = dequantize_asymmetric(q_asym, s_asym, zp)
err_asym = quantization_error(tensor, recon_asym)
print(f"\n Quantization Comparison ({num_bits}-bit, tensor shape {tensor.shape}):")
print(f" {'Method':<20} {'MSE':>12} {'SNR (dB)':>10} {'Cosine Sim':>12} {'Max Error':>12}")
print(f" {'-'*68}")
print(f" {'Per-tensor sym':<20} {err_pt['mse']:>12.8f} {err_pt['snr_db']:>10.2f} {err_pt['cosine_similarity']:>12.8f} {err_pt['max_error']:>12.8f}")
print(f" {'Per-channel sym':<20} {err_pc['mse']:>12.8f} {err_pc['snr_db']:>10.2f} {err_pc['cosine_similarity']:>12.8f} {err_pc['max_error']:>12.8f}")
print(f" {'Asymmetric':<20} {err_asym['mse']:>12.8f} {err_asym['snr_db']:>10.2f} {err_asym['cosine_similarity']:>12.8f} {err_asym['max_error']:>12.8f}")
return {"per_tensor": err_pt, "per_channel": err_pc, "asymmetric": err_asym}Bước 4: Thử nhiều mức bit-width
Quantize cùng một tensor ở các mức bit-width khác nhau (2, 3, 4, 8, 16) và đo chất lượng ở từng mức. Bạn sẽ thấy chính xác chất lượng bắt đầu tụt mạnh ở đâu.
def bit_width_sweep(tensor):
print(f"\n Bit-Width Sweep (tensor shape {tensor.shape}):")
print(f" {'Bits':>6} {'Levels':>8} {'MSE':>14} {'SNR (dB)':>10} {'Cosine Sim':>12} {'Compression':>12}")
print(f" {'-'*64}")
results = []
for bits in [2, 3, 4, 8, 16]:
q, s = quantize_per_channel(tensor, bits, axis=0)
recon = dequantize_per_channel(q, s, axis=0)
err = quantization_error(tensor, recon)
levels = 2 ** bits
compression = 32.0 / bits
print(f" {bits:>6} {levels:>8} {err['mse']:>14.8f} {err['snr_db']:>10.2f} {err['cosine_similarity']:>12.8f} {compression:>11.1f}x")
results.append({"bits": bits, "levels": levels, "error": err, "compression": compression})
return resultsBước 5: Thử nghiệm độ nhạy
Mô phỏng việc quantize các phần khác nhau của một transformer và đo component nào nhạy nhất. Thử nghiệm này cho thấy thứ tự mức độ nhạy: weight < activation < KV cache < attention.
def simulate_transformer_layer(input_data, weights, kv_scale=1.0):
hidden = input_data @ weights["qkv"]
seq_len = hidden.shape[1]
d_model = weights["qkv"].shape[1] // 3
q, k, v = hidden[:, :, :d_model], hidden[:, :, d_model:2*d_model], hidden[:, :, 2*d_model:]
attn_scores = (q @ k.transpose(0, 2, 1)) / np.sqrt(d_model) * kv_scale
attn_max = np.max(attn_scores, axis=-1, keepdims=True)
attn_exp = np.exp(attn_scores - attn_max)
attn_weights = attn_exp / np.sum(attn_exp, axis=-1, keepdims=True)
attn_output = attn_weights @ v
output = attn_output @ weights["out"]
return output, {"q": q, "k": k, "v": v, "attn_scores": attn_scores,
"attn_weights": attn_weights, "attn_output": attn_output}
def sensitivity_experiment(batch_size=2, seq_len=16, d_model=64, num_bits=8):
np.random.seed(42)
input_data = np.random.randn(batch_size, seq_len, d_model) * 0.1
weights = {
"qkv": np.random.randn(d_model, 3 * d_model) * (2.0 / d_model) ** 0.5,
"out": np.random.randn(d_model, d_model) * (2.0 / d_model) ** 0.5,
}
baseline_output, baseline_internals = simulate_transformer_layer(input_data, weights)
experiments = {}
q_qkv, s_qkv = quantize_per_channel(weights["qkv"], num_bits, axis=0)
q_out, s_out = quantize_per_channel(weights["out"], num_bits, axis=0)
quantized_weights = {
"qkv": dequantize_per_channel(q_qkv, s_qkv, axis=0),
"out": dequantize_per_channel(q_out, s_out, axis=0),
}
weight_quant_output, _ = simulate_transformer_layer(input_data, quantized_weights)
experiments["Weights only"] = quantization_error(baseline_output, weight_quant_output)
_, fresh_internals = simulate_transformer_layer(input_data, weights)
q_act, s_act = quantize_per_channel(
fresh_internals["attn_output"].reshape(-1, d_model), num_bits, axis=0
)
quant_attn_out = dequantize_per_channel(q_act, s_act, axis=0).reshape(batch_size, seq_len, d_model)
act_quant_output = quant_attn_out @ weights["out"]
experiments["Activations only"] = quantization_error(baseline_output, act_quant_output)
q_k, s_k = quantize_per_channel(fresh_internals["k"].reshape(-1, d_model), num_bits, axis=0)
q_v, s_v = quantize_per_channel(fresh_internals["v"].reshape(-1, d_model), num_bits, axis=0)
quant_k = dequantize_per_channel(q_k, s_k, axis=0).reshape(batch_size, seq_len, d_model)
quant_v = dequantize_per_channel(q_v, s_v, axis=0).reshape(batch_size, seq_len, d_model)
attn_scores_kv = (fresh_internals["q"] @ quant_k.transpose(0, 2, 1)) / np.sqrt(d_model)
attn_max_kv = np.max(attn_scores_kv, axis=-1, keepdims=True)
attn_exp_kv = np.exp(attn_scores_kv - attn_max_kv)
attn_weights_kv = attn_exp_kv / np.sum(attn_exp_kv, axis=-1, keepdims=True)
kv_quant_output = (attn_weights_kv @ quant_v) @ weights["out"]
experiments["KV cache only"] = quantization_error(baseline_output, kv_quant_output)
noise_scale = np.std(fresh_internals["attn_scores"]) * 0.05
noisy_scores = fresh_internals["attn_scores"] + np.random.randn(*fresh_internals["attn_scores"].shape) * noise_scale
noisy_max = np.max(noisy_scores, axis=-1, keepdims=True)
noisy_exp = np.exp(noisy_scores - noisy_max)
noisy_weights = noisy_exp / np.sum(noisy_exp, axis=-1, keepdims=True)
attn_quant_output = (noisy_weights @ fresh_internals["v"]) @ weights["out"]
experiments["Attention logits (5% noise)"] = quantization_error(baseline_output, attn_quant_output)
print(f"\n Sensitivity Experiment ({num_bits}-bit quantization):")
print(f" {'Component':<30} {'MSE':>14} {'SNR (dB)':>10} {'Cosine Sim':>12}")
print(f" {'-'*68}")
for name, err in sorted(experiments.items(), key=lambda x: x[1]["mse"]):
print(f" {name:<30} {err['mse']:>14.8f} {err['snr_db']:>10.2f} {err['cosine_similarity']:>12.8f}")
return experimentsBước 6: Mô phỏng GPTQ
GPTQ quantize từng cột một, dùng Hessian để quyết định cách phân bổ sai số làm tròn. Đây là phiên bản đơn giản hóa nhưng vẫn thể hiện ý chính: dùng calibration data để đo tầm quan trọng của weight, rồi quantize mạnh tay hơn với những weight ít quan trọng nhất.
def simulated_gptq(weight_matrix, calibration_inputs, num_bits=4):
n_in, n_out = weight_matrix.shape
qmin = -(2 ** (num_bits - 1))
qmax = 2 ** (num_bits - 1) - 1
H = np.zeros((n_in, n_in))
for x in calibration_inputs:
x = x.reshape(-1, 1) if x.ndim == 1 else x
for row in range(x.shape[0]):
xi = x[row].reshape(-1, 1)
H += xi @ xi.T
H /= len(calibration_inputs)
H += np.eye(n_in) * 1e-4
weight_importance = np.diag(H)
quantized = np.zeros_like(weight_matrix, dtype=np.int32)
scales = np.zeros(n_out)
errors = np.zeros(n_out)
W = weight_matrix.copy()
for col in range(n_out):
w_col = W[:, col]
abs_max = np.max(np.abs(w_col))
if abs_max == 0:
scales[col] = 1.0
continue
scale = abs_max / qmax
scales[col] = scale
q_col = np.clip(np.round(w_col / scale), qmin, qmax).astype(np.int32)
quantized[:, col] = q_col
quant_error = w_col - q_col * scale
errors[col] = np.sqrt(np.mean(quant_error ** 2))
if col < n_out - 1:
importance_weights = weight_importance / (np.max(weight_importance) + 1e-10)
for next_col in range(col + 1, min(col + 4, n_out)):
compensation = quant_error * importance_weights * 0.1
W[:, next_col] += compensation
return quantized, scales, {"column_errors": errors,
"mean_error": float(np.mean(errors)),
"max_error": float(np.max(errors))}
def dequantize_gptq(quantized, scales):
result = np.zeros_like(quantized, dtype=np.float64)
for col in range(quantized.shape[1]):
result[:, col] = quantized[:, col] * scales[col]
return resultBước 7: Mô phỏng AWQ
AWQ xác định các weight nổi bật (những weight được nhân với activation lớn) và bảo vệ chúng bằng cách scaling trước khi quantization.
def simulated_awq(weight_matrix, calibration_inputs, num_bits=4, salient_fraction=0.01):
n_in, n_out = weight_matrix.shape
qmin = -(2 ** (num_bits - 1))
qmax = 2 ** (num_bits - 1) - 1
activation_magnitudes = np.zeros(n_in)
for x in calibration_inputs:
if x.ndim == 1:
activation_magnitudes += np.abs(x)
else:
activation_magnitudes += np.mean(np.abs(x), axis=0)
activation_magnitudes /= len(calibration_inputs)
n_salient = max(1, int(n_in * salient_fraction))
salient_indices = np.argsort(activation_magnitudes)[-n_salient:]
scale_factors = np.ones(n_in)
for idx in salient_indices:
col_max = np.max(np.abs(weight_matrix[idx, :]))
if col_max > 0:
scale_factors[idx] = min(4.0, 1.0 / (col_max + 1e-8) * np.mean(np.abs(weight_matrix)))
scaled_weights = weight_matrix * scale_factors.reshape(-1, 1)
quantized, scales = quantize_per_channel(scaled_weights, num_bits, axis=0)
dequantized = dequantize_per_channel(quantized, scales, axis=0)
result = dequantized / scale_factors.reshape(-1, 1)
err = quantization_error(weight_matrix, result)
return result, {"salient_indices": salient_indices,
"scale_factors": scale_factors[salient_indices],
"error": err,
"n_salient": n_salient}Bước 8: Pipeline hoàn chỉnh
Nối tất cả lại với nhau. So sánh quantization đơn giản, per-channel, GPTQ và AWQ trên cùng một ma trận weight.
def full_quantization_comparison(d_in=256, d_out=512, num_bits=4, n_calibration=32):
np.random.seed(42)
weight = np.random.randn(d_in, d_out) * 0.02
outlier_rows = np.random.choice(d_in, size=5, replace=False)
weight[outlier_rows] *= 10
calibration = [np.random.randn(8, d_in) * 0.1 for _ in range(n_calibration)]
q_naive, s_naive = quantize_symmetric(weight, num_bits)
recon_naive = dequantize_symmetric(q_naive, s_naive)
err_naive = quantization_error(weight, recon_naive)
q_pc, s_pc = quantize_per_channel(weight, num_bits, axis=0)
recon_pc = dequantize_per_channel(q_pc, s_pc, axis=0)
err_pc = quantization_error(weight, recon_pc)
q_gptq, s_gptq, gptq_info = simulated_gptq(weight, calibration, num_bits)
recon_gptq = dequantize_gptq(q_gptq, s_gptq)
err_gptq = quantization_error(weight, recon_gptq)
recon_awq, awq_info = simulated_awq(weight, calibration, num_bits)
err_awq = awq_info["error"]
print(f"\n Full Quantization Comparison ({num_bits}-bit, {d_in}x{d_out} matrix)")
print(f" Matrix has {len(outlier_rows)} outlier rows (10x scale)")
print()
print(f" {'Method':<20} {'MSE':>14} {'SNR (dB)':>10} {'Cosine Sim':>12}")
print(f" {'-'*58}")
print(f" {'Naive per-tensor':<20} {err_naive['mse']:>14.8f} {err_naive['snr_db']:>10.2f} {err_naive['cosine_similarity']:>12.8f}")
print(f" {'Per-channel':<20} {err_pc['mse']:>14.8f} {err_pc['snr_db']:>10.2f} {err_pc['cosine_similarity']:>12.8f}")
print(f" {'Simulated GPTQ':<20} {err_gptq['mse']:>14.8f} {err_gptq['snr_db']:>10.2f} {err_gptq['cosine_similarity']:>12.8f}")
print(f" {'Simulated AWQ':<20} {err_awq['mse']:>14.8f} {err_awq['snr_db']:>10.2f} {err_awq['cosine_similarity']:>12.8f}")
test_input = np.random.randn(4, d_in) * 0.1
baseline = test_input @ weight
output_naive = test_input @ recon_naive
output_pc = test_input @ recon_pc
output_gptq = test_input @ recon_gptq
output_awq = test_input @ recon_awq
print(f"\n End-to-End Output Error (matmul with test input):")
print(f" {'Method':<20} {'Output MSE':>14} {'Output Cosine':>14}")
print(f" {'-'*50}")
for name, output in [("Naive", output_naive), ("Per-channel", output_pc),
("GPTQ", output_gptq), ("AWQ", output_awq)]:
out_err = quantization_error(baseline, output)
print(f" {name:<20} {out_err['mse']:>14.8f} {out_err['cosine_similarity']:>14.8f}")
return {"naive": err_naive, "per_channel": err_pc, "gptq": err_gptq, "awq": err_awq}
def memory_calculator(num_params_billions, bits_per_param):
bytes_per_param = bits_per_param / 8
total_bytes = num_params_billions * 1e9 * bytes_per_param
total_gb = total_bytes / (1024 ** 3)
return total_gb
def print_memory_table():
print("\n Memory Requirements by Model and Precision:")
print(f" {'Model':<15} {'FP32':>8} {'FP16':>8} {'FP8':>8} {'INT8':>8} {'INT4':>8} {'INT2':>8}")
print(f" {'-'*64}")
for name, params in [("7B", 7), ("13B", 13), ("34B", 34), ("70B", 70), ("405B", 405)]:
fp32 = memory_calculator(params, 32)
fp16 = memory_calculator(params, 16)
fp8 = memory_calculator(params, 8)
int8 = memory_calculator(params, 8)
int4 = memory_calculator(params, 4)
int2 = memory_calculator(params, 2)
print(f" {name:<15} {fp32:>7.1f}G {fp16:>7.1f}G {fp8:>7.1f}G {int8:>7.1f}G {int4:>7.1f}G {int2:>7.1f}G")
if __name__ == "__main__":
np.random.seed(42)
print("=" * 70)
print("QUANTIZATION: MAKING MODELS FIT")
print("=" * 70)
print("\nSTEP 1: Number Format Comparison")
print("-" * 50)
for val in [0.1, 3.14159, -0.00073, 42.5, 0.0000012]:
display_format_comparison(val)
print("\n\nSTEP 2: Memory Requirements")
print("-" * 50)
print_memory_table()
print("\n\nSTEP 3: Quantization Methods Comparison")
print("-" * 50)
weight_matrix = np.random.randn(128, 256) * 0.02
weight_matrix[0] *= 15
weight_matrix[42] *= 8
compare_quantization_methods(weight_matrix, num_bits=8)
compare_quantization_methods(weight_matrix, num_bits=4)
print("\n\nSTEP 4: Bit-Width Sweep")
print("-" * 50)
sweep_tensor = np.random.randn(64, 128) * 0.05
bit_width_sweep(sweep_tensor)
print("\n\nSTEP 5: Sensitivity Experiment")
print("-" * 50)
print("\n INT8:")
sensitivity_experiment(num_bits=8)
print("\n INT4:")
sensitivity_experiment(num_bits=4)
print("\n\nSTEP 6: GPTQ vs AWQ vs Naive (INT4)")
print("-" * 50)
full_quantization_comparison(d_in=256, d_out=512, num_bits=4)
print("\n\nSTEP 7: Distribution Analysis")
print("-" * 50)
np.random.seed(0)
simulated_weights = np.random.randn(1000) * 0.02
abs_vals = np.abs(simulated_weights)
pct_in_range = np.mean(abs_vals < 0.1) * 100
print(f"\n Simulated weight distribution (1000 params, std=0.02):")
print(f" Weights in [-0.1, 0.1]: {pct_in_range:.1f}%")
print(f" Weights in [-0.05, 0.05]: {np.mean(abs_vals < 0.05) * 100:.1f}%")
print(f" Weights in [-0.01, 0.01]: {np.mean(abs_vals < 0.01) * 100:.1f}%")
print(f" Max absolute value: {np.max(abs_vals):.6f}")
print(f" Mean absolute value: {np.mean(abs_vals):.6f}")
histogram = np.histogram(simulated_weights, bins=20)
print(f"\n Weight histogram:")
max_count = max(histogram[0])
for i in range(len(histogram[0])):
bar_len = int(histogram[0][i] / max_count * 40)
lo = histogram[1][i]
hi = histogram[1][i + 1]
print(f" [{lo:>7.4f}, {hi:>7.4f}] {'#' * bar_len} ({histogram[0][i]})")
print("\n\n" + "=" * 70)
print("DONE")
print("=" * 70)Dùng thực tế
Quantize bằng GPTQModel
# pip install gptqmodel
# from gptqmodel import GPTQConfig, GPTQModel
#
# model_id = "meta-llama/Llama-3.1-8B"
# quant_config = GPTQConfig(bits=4, group_size=128)
#
# model = GPTQModel.load(model_id, quant_config)
# model.quantize(calibration_texts[:128], batch_size=1)
# model.save("llama-8b-gptq-int4")Quantize sang AWQ bằng LLM Compressor
# pip install llmcompressor
# from transformers import AutoModelForCausalLM, AutoTokenizer
# from llmcompressor import oneshot
# from llmcompressor.modifiers.quantization import QuantizationModifier
# from llmcompressor.modifiers.transform.awq import AWQModifier
#
# model_id = "meta-llama/Llama-3.1-8B"
# model = AutoModelForCausalLM.from_pretrained(model_id)
# tokenizer = AutoTokenizer.from_pretrained(model_id)
#
# recipe = [
# AWQModifier(duo_scaling="both"),
# QuantizationModifier(ignore=["lm_head"], scheme="W4A16_ASYM", targets=["Linear"]),
# ]
# oneshot(
# model=model,
# dataset="perfectblend",
# splits="train[:512]",
# recipe=recipe,
# max_seq_length=512,
# num_calibration_samples=256,
# )
# model.save_pretrained("llama-8b-awq-int4", save_compressed=True)
# tokenizer.save_pretrained("llama-8b-awq-int4")AutoGPTQ và AutoAWQ, những công cụ ban đầu cho hai phương pháp này, đã được lưu trữ và không còn phát triển. GPTQModel và LLM Compressor là các công cụ kế nhiệm còn được duy trì.
Chuyển sang GGUF
# git clone https://github.com/ggml-org/llama.cpp
# cmake -S llama.cpp -B llama.cpp/build && cmake --build llama.cpp/build --config Release
# pip install -r llama.cpp/requirements.txt
# hf download meta-llama/Llama-3.1-8B --local-dir Llama-3.1-8B
# python llama.cpp/convert_hf_to_gguf.py Llama-3.1-8B --outtype f16 --outfile llama-8b-f16.gguf
# llama.cpp/build/bin/llama-quantize llama-8b-f16.gguf llama-8b-q4km.gguf Q4_K_M
# llama.cpp/build/bin/llama-server -m llama-8b-q4km.gguf -c 4096 -ngl 99Công cụ chuyển đổi không xuất được K-quant (--outtype chỉ nhận f32, f16, bf16, q8_0, tq1_0, tq2_0 hoặc auto), nên llama-quantize sẽ tạo file Q4_K_M.
Phục vụ model đã quantize
# pip install vllm
# vllm serve llama-8b-awq-int4 --max-model-len 8192vLLM hỗ trợ sẵn model AWQ và GPTQ, đồng thời đọc phương pháp quantization từ config của checkpoint, nên không cần cờ --quantization. Nó xử lý dequantization trong lúc nhân ma trận và dùng paged attention cho KV cache. Với FP8 trên H100, thêm --quantization fp8_per_tensor để quantize weight của checkpoint 16-bit ngay lúc nạp.
Đưa vào sản phẩm
Bài học này tạo ra outputs/skill-quantization.md, một khung ra quyết định để chọn chiến lược quantization phù hợp. Dựa trên kích thước model, phần cứng đích và yêu cầu chất lượng của bạn, nó cho biết nên dùng format, phương pháp và các bước kiểm tra nào. Nó gồm cách tính bộ nhớ cần thiết, khuyến nghị precision cho từng component và hướng dẫn deploy bằng vLLM, llama.cpp và TensorRT-LLM.
Bài tập
- Triển khai group quantization. Thay vì một scale cho mỗi channel, dùng một scale cho mỗi nhóm 128 weight trong một channel. Đây là cách GPTQ và AWQ thực sự làm. So sánh kích thước nhóm 32, 64, 128 và 256 trên cùng một ma trận weight. Nhóm nhỏ hơn cho chất lượng tốt hơn nhưng tốn thêm chỗ lưu scale factor.
- Xây dựng một quantizer mixed-precision. Quantize layer đầu và cuối của một network nhiều layer ở INT8, còn các layer giữa ở INT4. So sánh chất lượng output cuối cùng với trường hợp toàn bộ dùng INT4 và toàn bộ dùng INT8. Đo lượng bộ nhớ tiết kiệm được so với trường hợp toàn bộ dùng INT8.
- Triển khai straight-through estimator (STE) cho quantization-aware training. Chèn các thao tác quantize/dequantize giả vào forward pass của một network hai layer đơn giản được training cho tác vụ regression. So sánh loss cuối cùng giữa model được training bình thường (rồi PTQ xuống INT4) và model được training bằng QAT ngay từ đầu.
- Xây dựng một quantizer có tính đến outlier, lấy cảm hứng từ LLM.int8(). Phát hiện những channel có độ lớn activation vượt quá 6 lần giá trị trung bình. Giữ các channel đó ở FP16 và quantize mọi thứ khác xuống INT8. Đo chất lượng cuối cùng trên transformer layer ở Bước 5 với các ngưỡng outlier khác nhau (3x, 6x, 10x).
- Triển khai một dashboard chất lượng quantization. Với một ma trận weight, hãy tính và hiển thị: histogram phân phối weight, phân phối sai số quantization, scale factor theo từng channel, những channel bị quantize kém nhất (sai số tái tạo cao nhất) và cosine similarity giữa output gốc với output đã quantize trên 100 input ngẫu nhiên. Xác định những channel nào nên được giữ ở precision cao hơn.
Thuật ngữ chính
| Thuật ngữ | Người ta hay nói | Nghĩa thật sự |
|---|---|---|
| FP16 | "Một nửa precision" | Số dấu phẩy động 16-bit với 5 bit exponent và 10 bit mantissa, giá trị lớn nhất 65,504, format tiêu chuẩn cho inference |
| BF16 | "Brain float" | Số dấu phẩy động 16-bit với 8 bit exponent (cùng dải giá trị với FP32) và 7 bit mantissa, được Google thiết kế cho training |
| FP8 | "Số dấu phẩy động 8-bit" | Hai biến thể: E4M3 (inference, precision cao hơn) và E5M2 (training, dải giá trị rộng hơn), được H100 hỗ trợ trực tiếp |
| INT8 | "Số nguyên 8-bit" | 256 giá trị cách đều nhau từ -128 đến 127, cần scale factor để ánh xạ từ số dấu phẩy động |
| INT4 | "Số nguyên 4-bit" | Tổng cộng 16 mức giá trị, cần phương pháp tinh vi (GPTQ, AWQ) để giữ chất lượng |
| Per-channel quantization | "Một scale cho mỗi hàng" | Dùng một scale factor riêng cho từng output channel thay vì một scale factor cho toàn bộ tensor, giúp giảm sai số rõ rệt |
| GPTQ | "Phương pháp Hessian" | Post-training quantization dùng thông tin bậc hai để giảm thiểu sai số output, xử lý từng layer một |
| AWQ | "Có tính đến activation" | Scale các weight nổi bật (những weight được nhân với activation lớn) trước khi quantization để bảo vệ chúng |
| GGUF | "Format của llama.cpp" | File model tự chứa với các layer dùng nhiều mức precision, được tối ưu cho inference trên CPU và Apple Silicon |
| PTQ | "Quantize sau khi training" | Chuyển weight của model đã training xuống precision thấp hơn mà không training lại, nhanh nhưng có giới hạn khi nén quá mạnh |
| QAT | "Quantize trong lúc training" | Chèn quantization giả vào forward pass để model học cách chịu sai số làm tròn, cho kết quả tốt hơn ở INT4/INT2 |
| Calibration data | "128 ví dụ đó" | Một dataset nhỏ được chạy qua model để tính thống kê activation dùng cho việc đặt scale factor |
| Scale factor | "Hệ số nhân" | Chuyển đổi giữa dải số dấu phẩy động và dải số nguyên: float_val = int_val * scale |
| Perplexity delta | "Tệ đi bao nhiêu" | Chênh lệch perplexity giữa model gốc và model đã quantize, < 0.5 là xuất sắc, > 2.0 là có vấn đề |
Đọc thêm
- Frantar et al., 2022 -- "GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers" -- paper giúp quantization INT4 trở nên thực tế với LLM nhờ làm tròn weight dựa trên Hessian
- Lin et al., 2023 -- "AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration" -- bảo vệ các weight nổi bật bằng cách scaling trước khi quantization, đạt chất lượng ngang hoặc tốt hơn GPTQ
- Dettmers et al., 2022 -- "LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale" -- INT8 mixed-precision giữ các outlier feature ở FP16, cho phép inference bằng INT8 mà không giảm chất lượng
- Xiao et al., 2023 -- "SmoothQuant: Accurate and Efficient Post-Training Quantization for Large Language Models" -- chuyển phần khó của quantization từ activation sang weight để deploy W8A8
- Micikevicius et al., 2022 -- "FP8 Formats for Deep Learning" -- paper của NVIDIA/ARM/Intel định nghĩa các format E4M3 và E5M2 hiện được H100 hỗ trợ trực tiếp