अध्याय 7 · Inference aur deployment 7.5
Model quantization: INT8, INT4, GPTQ aur AWQ ka siddhant aur measurement
Quantization weights, activations ya KV cache ko kam bits mein rakhta hai. Yeh page memory aur bandwidth ka hisaab lagata hai, Qwen2.5-0.5B par INT8 aur INT4 ki perplexity naapta hai, SmoothQuant, AWQ, GPTQ aur KV cache quantization implement karta hai, aur selection table deta hai।
यह पृष्ठ पूरा करने पर आप
- Ek model ke weights aur KV cache alag-alag kitni memory lete hain, nikaalein, aur quantization decode ko hi kyun zyada tez karta hai, samjhayein।
- Symmetric aur group quantization likhein, aur "effective bit-width" samjhayein।
- Samjhayein INT8 lagbhag lossless kyun, INT4 ko grouping aur calibration kyun chahiye, aur activations weights se mushkil kyun hain।
- SmoothQuant, AWQ-style scaling, GPTQ aur KV cache quantization khud implement karke perplexity se compare karein।
- Bottleneck weights mein hai, KV cache mein ya compute mein - uske hisaab se quantization scheme chunein, aur launch se pehle kya check karna hai, jaanein।
इस पृष्ठ पर
- Quantization kyun: memory aur bandwidth ka hisaab
- Quantization ke targets aur routes
- Quantization ka math: scaling factor, zero point aur grouping
- Khud karein: bit-width, grouping aur outliers
- Khud karein: Qwen2.5-0.5B par chaar experiments
- Experiment 1: weights ki bit-width aur granularity
- Har layer equally sensitive nahi
- Experiment 2: activations quantize karna mushkil kyun
- Experiment 3: calibration data se error ghatana
- Experiment 4: KV cache quantization
- Results ek saath
- Selection aur launch
- Pehle bottleneck pehchano
- Tools aur formats
- Symptoms, causes aur actions
- Common galtiyan
- Research case: KV cache ki bit-width layer-wise badalna
- Summary aur exercises
- Quick self-test
- Aage padhein
- अक्सर पूछे जाने वाले सवाल
Quantization kyun: memory aur bandwidth ka hisaab
LLM deployment ki lagat mainly teen cheezon se hai: weights ki memory, KV cache ki memory, aur har generated token ke liye weights ek baar padhne wali memory bandwidth. Quantization numbers ko kam bits mein rakhkar teeno saath ghata hai (kyun “har token par weights padhna” bottleneck banta hai: GPU aur roofline model; FP16, BF16, FP8 ke bit allocation aur common failures: numerical precision). Pehle hisaab: neeche Llama-3-8B ke config.json se gin kar, memory bandwidth 2 TB/s maan kar, ek 80 GB card ka 90% available (baaki activations aur overhead ke liye; vLLM mein yeh ratio --gpu-memory-utilization se control hota hai, default version ke saath badalta hai)।
import torch
from transformers import AutoConfig, AutoModelForCausalLM
cfg = AutoConfig.from_pretrained("NousResearch/Meta-Llama-3-8B")
with torch.device("meta"): # sirf skeleton, memory allocate nahi
skel = AutoModelForCausalLM.from_config(cfg)
n_emb = skel.get_input_embeddings().weight.numel() # input embedding
n_head = skel.lm_head.weight.numel() # output layer (embedding se shared nahi)
n_lin = sum(m.weight.numel() for n, m in skel.named_modules()
if isinstance(m, torch.nn.Linear) and ".layers." in n)
n_all = sum(p.numel() for p in skel.parameters())
print(f"Llama-3-8B: total {n_all / 1e9:.2f}B params, "
f"decoder linear layers {n_lin / 1e9:.2f}B,")
print(f"embedding {n_emb / 1e9:.2f}B, output layer {n_head / 1e9:.2f}B")
BW, MEM = 2e12, 0.9 * 80e9 # bandwidth 2 TB/s; 90% of 80 GB card
kv_tok = 2 * cfg.num_hidden_layers * cfg.num_key_value_heads * \
(cfg.hidden_size // cfg.num_attention_heads) # K,V elements per token
print(f"KV cache per token {kv_tok * 2} bytes (BF16); "
f"ek 8K sequence {kv_tok * 2 * 8192 / 1e9:.2f} GB")
print("weights+KV wts GB read GB tok/s max 8K conc")
for tag, w_bits, kv_bits in (("BF16 + BF16", 16, 16),
("INT4 + BF16", 4.125, 16),
("INT4 + INT8", 4.125, 8.125)):
lin = n_lin * w_bits / 8 # sirf decoder linear quantized; emb+out BF16
weights = lin + (n_emb + n_head) * 2
read = lin + n_head * 2 # per decode step: linear + out layer (emb sirf ek row)
seqs = (MEM - weights) // (kv_tok * kv_bits / 8 * 8192)
print(f"{tag:<14}{weights / 1e9:9.1f}{read / 1e9:12.1f}"
f"{BW / read:14.0f}{seqs:11.0f}")
Output:
Llama-3-8B: total 8.03B params, decoder linear layers 6.98B,
embedding 0.53B, output layer 0.53B
KV cache per token 131072 bytes (BF16); ek 8K sequence 1.07 GB
weights+KV wts GB read GB tok/s max 8K conc
BF16 + BF16 16.1 15.0 133 52
INT4 + BF16 5.7 4.6 430 61
INT4 + INT8 5.7 4.6 430 121
Note: numbers original run se hain; print labels Latin transliteration mein likhe gaye hain।
Is table ko padhne ke chaar points:
- Weights 4x nahi ghat-te. Sirf decoder ke linear layers (6.98B) INT4 mein quantize hote hain; group quantization mein har group scaling factor bhi store hota hai, isliye 4.125 bits gin-te hain. Input embedding aur output layer har ek 0.53B, abhi bhi BF16 - isliye weights 16.1 GB se 5.7 GB, lagbhag 2.8x।
- Decode ki speed ceiling “har step kitne bytes padhe” se aati hai. Har token ke liye linear layers ke weights aur output layer memory se padhna padta hai: BF16 mein 15.0 GB, 2 TB/s bandwidth par max 133 token/s; INT4 mein sirf 4.6 GB, ceiling 430 token/s, lagbhag 3.2x. Yeh batch=1 ka ceiling hai; asli speed kernel efficiency, KV cache reads aur scheduling overhead se bhi seemit hai।
- KV cache concurrency tay karta hai. Llama-3-8B har token ki KV cache 131,072 bytes (2 x 32 layers x 8 KV heads x 128 dim x 2 bytes); ek 8K sequence 1.07 GB. 80 GB card par BF16 weights ke baad sirf lagbhag 52 aisi sequences fit; weights INT4 karne par 61; aur KV cache INT8 (har 128-dim vector ka ek scaling factor, 8.125 bits) karne par 121. Jab concurrency memory se block ho, KV cache dabana weights dabane se zyada kaam karta hai।
- Prefill zaroori nahi tez ho. Prefill poora prompt ek saath process karta hai; bottleneck compute hai. W4A16 kernels aam taur par registers mein weights ko 16-bit mein dequantize karke matrix multiply karte hain (AWQ paper ka TinyChat section yeh discuss karta hai), isliye prefill ka gain seemit hai; matrix multiply khud low precision (W8A8, FP8) mein chalane ke liye activations bhi quantize karne padte hain - experiment 2 ka vishay।
Quantization ke targets aur routes
Quantization teen jagah ho sakti hai: weights static hain, offline calibrate ho sakte hain, sabse mature; activations input ke saath badalte hain, mushkil; KV cache inference mein badhta hai, concurrency tay karta hai. Timing ke do raaste: PTQ (Post-Training Quantization) training ke baad seedha quantize - sasta, open-source deployment ka aam raasta; QAT (Quantization-Aware Training) training mein quantization error simulate karta hai, model low-bit ke saath adjust hota hai - potential precision behtar, par complex aur mehnga. Is page ke experiments sab PTQ hain।
Quantization ka math: scaling factor, zero point aur grouping
Pehle “quantization” ko formula likhein. Floating-point weights ke liye ek scaling factor dhoondein, har number ko se divide karke integer mein round karein, use karte waqt wapas multiply karke milega. Symmetric quantization mein 0 integer 0 se map hota hai; scaling sirf sabse bade absolute value se tay hota hai:
Asymmetric quantization ek zero point bhi store karta hai, jisse integer range range ko poora cover karta hai:
Bina clipping ke har weight ki error se kam hai. Har 1 extra bit par step aadha, noise power chauthai, SNR lagbhag dB badhta hai।
Grouping tay karta hai kitne weights ek share karte hain. Whole-tensor sabse sasta hai, par ek outlier hi ko phula deta hai aur baaki weights kuch integer levels mein simat jaate hain; har weights ka ek group outlier ke asar ko apne group mein rakhta hai. Keemat: har group ek 16-bit scaling factor (asymmetric mein zero point bhi), isliye 4-bit, ka “effective bit-width” bits hai. GPTQ aur AWQ ka aam config 4-bit, group size 128 hai।
Khud karein: bit-width, grouping aur outliers
Widget ka data fixed-seed 1024 standard-normal random numbers hain - illustrative data, real model weights nahi; real weights ka tail bhaari aur outliers zyada hote hain. Aise kheliye:
- Har extra bit par SNR lagbhag 6 dB. Symmetric, whole-tensor par 2 se 8 bits ke SQNR kram se 1.1, 9.6, 16.9, 23.5, 29.8, 35.6, 42.1 dB. 2-bit symmetric ke paas sirf teen levels - taqreeban bekaar।
- Ek outlier whole-tensor quantization tabah kar deta hai. “1 outlier (20x std)” check karein: 4-bit whole-tensor SQNR 16.9 dB se 3.7 dB (baaki weights kuch levels mein simat jaate hain); group size 128 par 11.6 dB, 64 par 14.7 dB, 16 par 19.1 dB (effective bit-width 5.0). Yehi wajah hai ki 4-bit weight quantization ko grouping chahiye - aur LLM.int8() ka bhi starting point, jo outlier dimensions ko alag karke 16-bit mein compute karta hai।
- Asymmetric thoda zyada precise, sirf thoda zyada storage. 4-bit, , no outlier: symmetric 18.1 dB (4.125 bits), asymmetric 19.6 dB (4.156 bits)।
- Size dekhein. 7B model ke BF16 weights 14 GB; 4-bit, symmetric lagbhag 3.6 GB ( bytes)।
Khud karein: Qwen2.5-0.5B par chaar experiments
Chaar experiments ek hi model par: Qwen2.5-0.5B (24 layers, hidden dim 896, 14 attention heads with 2 KV heads, weights BF16 mein release hue). Metric perplexity: WikiText-2 test set ke pehle 40 windows of 512 tokens (total 20,480 tokens) par average negative log-likelihood ka exponential - jitna kam, utna achha. Kyunki yeh quantization error par sensitive aur fast hai; par downstream task accuracy ke barabar nahi, launch se pehle apne task par evaluate karein. Aur, chhote models quantization ke liye bade se zyada fragile hain (experiment 1 ke end mein), isliye yahan absolute numbers pessimistic hain - relative trend asli point hai।
Sab experiments simulated quantization (fake quantization) hain: weights integers mein quantize karke turant scaling se multiply karke wapas float, phir normal float matrix multiply. Isse algorithm ki precision loss naapi jaati hai, speed nahi, aur kisi GPU kernel par nirbhar nahi. Real deployment mein weights integers mein store hote hain, kernel read karte waqt dequantize karta hai. Neeche WxAy matlab weights x-bit, activations y-bit; W8A16 sirf weights INT8।
Pehle model load karein, perplexity define karein, aur quantize hone wale 168 linear layers ka backup lein (embedding aur output layer shared hain, waise hi rehte hain):
import math
import pandas as pd
import torch
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from torch import nn
from transformers import AutoModelForCausalLM, AutoTokenizer
dev = "mps" if torch.backends.mps.is_available() else "cpu"
name = "Qwen/Qwen2.5-0.5B"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, dtype=torch.float32)
model = model.to(dev).eval()
def wikitext(split):
path = hf_hub_download(
"Salesforce/wikitext",
f"wikitext-2-raw-v1/{split}-00000-of-00001.parquet",
repo_type="dataset")
return "".join(pd.read_parquet(path)["text"])
CTX = 512 # har window 512 tokens
ids = tok(wikitext("test"), return_tensors="pt").input_ids[0]
test = ids[:40 * CTX].view(40, CTX).to(dev) # test set ke pehle 40 windows
@torch.no_grad()
def ppl(make_cache=None):
"""Perplexity: avg negative log-likelihood ka exponential, kam achha."""
nll = 0.0
for x in test.split(4):
kw = {}
if make_cache: # experiment 4 ke liye: quantized KV cache
kw = {"past_key_values": make_cache(), "use_cache": True}
logits = model(x, **kw).logits[:, :-1].float()
nll += F.cross_entropy(logits.reshape(-1, logits.size(-1)),
x[:, 1:].reshape(-1), reduction="sum").item()
return math.exp(nll / (len(test) * (CTX - 1)))
# sirf decoder layers ke linear layers quantize; embedding (out layer se
# shared) as-is
names = [n for n, m in model.named_modules()
if isinstance(m, nn.Linear) and ".layers." in n]
linears = [model.get_submodule(n) for n in names]
orig = [m.weight.data.clone() for m in linears] # backup, har experiment ke baad restore
n_w = sum(w.numel() for w in orig)
n_all = sum(p.numel() for p in model.parameters())
n_emb = model.get_input_embeddings().weight.numel()
print(f"total params {n_all / 1e6:.0f}M: linear {n_w / 1e6:.0f}M, "
f"embedding {n_emb / 1e6:.0f}M (out layer se shared)")
print(f"BF16 storage: linear {n_w * 2 / 1e6:.0f} MB, "
f"poora model {n_all * 2 / 1e6:.0f} MB")
print(f"baseline (BF16 weights, FP32 compute): perplexity {ppl():.2f}")
Output:
total params 494M: linear 358M, embedding 136M (out layer se shared)
BF16 storage: linear 716 MB, poora model 988 MB
baseline (BF16 weights, FP32 compute): perplexity 16.25
Baseline perplexity 16.25 hai. Note: embedding 136M parameters - poore model ka 28%; aage is baat par wapas aayenge।
Experiment 1: weights ki bit-width aur granularity
Sabse seedha tareeka RTN (Round To Nearest): koi data nahi dekha, seedha pichhle section ke formula se har weight quantize. fake_quant wahi formulas hai; grid bit-width (INT8, INT4, INT3) aur granularity (whole tensor, per row, har weights ka group) ka combination hai:
def fake_quant(w, bits, group):
"""Symmetric absmax quantization, wapas float. group: "tensor", "row" ya int."""
qmax = 2 ** (bits - 1) - 1
if group == "tensor":
g = w.reshape(1, -1) # poora tensor ek hi scaling factor
elif group == "row":
g = w # har output channel (row) ka ek
else:
g = w.reshape(-1, group) # har group weights ka ek
s = (g.abs().amax(dim=1, keepdim=True) / qmax).clamp(min=1e-8)
return ((g / s).round().clamp(-qmax, qmax) * s).reshape(w.shape)
def n_scales(w, group):
if group == "tensor":
return 1
return w.shape[0] if group == "row" else w.numel() // group
def set_weights(fn): # fn(linear index, original weight) -> naya weight
for i, (m, w) in enumerate(zip(linears, orig)):
m.weight.data = fn(i, w)
def eff_bits(bits, group): # har scaling factor 16 bits, har weight par spread
return bits + 16 * sum(n_scales(w, group) for w in orig) / n_w
grid = [(8, "tensor"), (8, "row"), (4, "tensor"), (4, "row"),
(4, 128), (4, 64), (4, 32), (4, 16), (3, 128)]
for bits, group in grid:
set_weights(lambda i, w: fake_quant(w, bits, group))
eff = eff_bits(bits, group)
print(f"INT{bits} {str(group):<7} eff bits {eff:5.3f} "
f"weights {n_w * eff / 8e6:4.0f} MB perplexity {ppl():8.2f}")
set_weights(lambda i, w: w.clone()) # restore
# whole-tensor INT4 collapse kyun: max value typical se bahut bada,
# zyada tar weights 0 mein round ho jaate hain
r = torch.stack([w.abs().max() / w.abs().median() for w in orig])
print(f"har layer max|w| / median|w|: median {r.median():.0f}, max {r.max():.0f}")
for group in ("tensor", "row", 128):
z = [(fake_quant(w, 4, group) == 0).float().mean().item() for w in orig]
print(f"INT4 {str(group):<7} 0 mein rounded weights {sum(z) / len(z):.1%}")
Output:
INT8 tensor eff bits 8.000 weights 358 MB perplexity 17.24
INT8 row eff bits 8.014 weights 358 MB perplexity 16.29
INT4 tensor eff bits 4.000 weights 179 MB perplexity 82798903.47
INT4 row eff bits 4.014 weights 180 MB perplexity 36.35
INT4 128 eff bits 4.125 weights 185 MB perplexity 22.41
INT4 64 eff bits 4.250 weights 190 MB perplexity 20.36
INT4 32 eff bits 4.500 weights 201 MB perplexity 19.50
INT4 16 eff bits 5.000 weights 224 MB perplexity 18.08
INT3 128 eff bits 3.125 weights 140 MB perplexity 223.43
har layer max|w| / median|w|: median 27, max 117
INT4 tensor 0 mein rounded weights 74.3%
INT4 row 0 mein rounded weights 26.4%
INT4 128 0 mein rounded weights 19.7%
Note: numbers original run se hain; print labels Latin transliteration mein likhe gaye hain।
- INT8 lagbhag lossless, shart yeh hai ki per-row (ya finer) scaling ho. Per-row scaling par perplexity 16.29, baseline se sirf 0.04 farq; whole-tensor ek hi scaling factor par 17.24 (6% upar), kyunki kuch rows ke weights bahut bade hain aur poore tensor ka scaling phula dete hain।
- Whole-tensor INT4 poori tarah collapse - perplexity , vocabulary mein uniform random guess (perplexity = vocab size 151,936) se 500 guna se zyada bura. Output ke end mein wajah: har layer ka median 27; INT4 ke paas sirf se - 15 levels; scaling , isliye se chhote absolute values wale weights 0 mein round ho jaate hain. Whole-tensor scaling par 74.3% weights 0 bane, per-row 26.4%, group-128 19.7%।
- Grouping storage se precision khareedna hai, aur returns ghatte hain. Group size 128 se 64, 32, 16 par effective bit-width kram se 4.125, 4.25, 4.5, 5.0 bits, perplexity 22.41, 20.36, 19.50, 18.08; baseline se farq 6.16 se 4.11, 3.25, 1.83. Teen ghataav ne kram se 0.125, 0.25, 0.5 bits extra liye; perplexity kram se 2.05, 0.86, 1.42 giri; per extra bit ke hisaab se: 16.4, 3.4, 2.8 - sabse pehle kharch kiya gaya storage sabse sasta tha।
- RTN 3 bits par unusable hai. Group size 128 ka INT3 223.43. Bits aur dabaane ke liye experiment 3 ki calibration chahiye।
- Chhote models zyada fragile. GPTQ paper ne OPT aur BLOOM par dekha: same bit-width par bade models aam taur par quantize karna aasaan (OPT-66B exception): OPT-175B ka 4-bit RTN perplexity 8.34 se 10.54; OPT-1.3B ka 14.63 se 48.17 (paper ka RTN per-row asymmetric quantization hai, is page ke symmetric se exact match nahi). Is page ka 0.5B model mushkil side par hai।
Har layer equally sensitive nahi
Overall numbers ke neeche har layer ki sensitivity alag hai. Neeche har baar sirf ek tarah ke linear layers (ya kuch layers) INT4 g128 mein quantize, baaki as-is; aakhir mein embedding:
# sensitivity: har baar sirf ek tarah ke linear layers INT4 g128
for kind in ("q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"):
set_weights(lambda i, w: fake_quant(w, 4, 128)
if names[i].endswith(kind) else w.clone())
print(f"sirf {kind:<9} quantized perplexity {ppl():.2f}")
# phir depth ke hisaab se: sirf kuch layers
for lo, hi in ((0, 4), (10, 14), (20, 24)):
set_weights(lambda i, w: fake_quant(w, 4, 128)
if lo <= int(names[i].split(".")[2]) < hi else w.clone())
print(f"sirf layers {lo}-{hi - 1} perplexity {ppl():.2f}")
# embedding (out layer se shared) aam taur par quantize nahi hoti:
# quantize karne par kya hota hai, model kitna chhota hota hai
set_weights(lambda i, w: fake_quant(w, 4, 128))
emb = model.get_input_embeddings().weight
emb_orig = emb.data.clone()
print(f"linear INT4 g128, embedding as-is: perplexity {ppl():.2f}")
emb.data = fake_quant(emb_orig, 4, 128)
print(f"linear aur embedding dono INT4 g128: perplexity {ppl():.2f}")
emb.data = emb_orig
set_weights(lambda i, w: w.clone())
size = n_w * eff_bits(4, 128) / 8 + (n_all - n_w) * 2 # bytes mein
print(f"linear INT4 g128, baaki BF16: poora model {size / 1e6:.0f} MB, "
f"BF16 ka {size / (n_all * 2):.0%}")
Output:
sirf q_proj quantized perplexity 16.37
sirf k_proj quantized perplexity 16.38
sirf v_proj quantized perplexity 16.89
sirf o_proj quantized perplexity 16.67
sirf gate_proj quantized perplexity 16.85
sirf up_proj quantized perplexity 17.29
sirf down_proj quantized perplexity 17.88
sirf layers 0-3 perplexity 17.76
sirf layers 10-13 perplexity 16.66
sirf layers 20-23 perplexity 17.87
linear INT4 g128, embedding as-is: perplexity 22.41
linear aur embedding dono INT4 g128: perplexity 24.71
linear INT4 g128, baaki BF16: poora model 457 MB, BF16 ka 46%
- Type ke hisaab se, baseline 16.25:
q_proj,k_projsabse kam sensitive (0.12 aur 0.13 upar),o_proj0.42,gate_proj0.60,v_proj0.64,up_proj1.04,down_projsabse sensitive, 1.63। - Depth ke hisaab se, pehle 4 layers 1.51 upar, aakhri 4 layers 1.62, beech ki 4 layers sirf 0.41. Shuru aur ant ki layers zyada sensitive।
- Embedding ka hissa chhota nahi. Linear layers INT4 g128, embedding BF16: poora model 457 MB - BF16 ka 46%, 25% nahi. Embedding (out layer se shared) bhi INT4 g128 karne par perplexity 22.41 se 24.71. 0.5B model mein embedding 28% hai; Llama-3-8B mein embedding + output layer sirf 13% - isliye bade models ki quantization zyada kareeb hoti hai “4x chhota” ke।
- Practical matlab mixed precision hai: sensitive parts (shuru-aakhir ke layers,
down_proj, embedding + output layer) zyada bit-width par rakhein, insensitive parts 4-bit par।
Experiment 2: activations quantize karna mushkil kyun
Weights training ke baad fixed hain; quantization ke liye sirf weights dekhne padte hain. Activations input ke saath badalte hain; runtime ke kisi bhi value ko handle karna hai. Pehle layer 12 ke linear layers ke inputs ka shape dekhein (q/k/v ek hi input share karte hain, gate/up bhi), phir teen settings compare: sirf weights quantize (W8A16); weights + activations dono INT8, activations whole-tensor ya per-token scaled (W8A8, dynamic - har forward par scaling freshly computed):
def act_quant(x, per_token):
"""INT8 dynamic activation quant: whole-tensor scaling, ya per-token."""
s = x.abs().amax(dim=-1, keepdim=True) if per_token else x.abs().amax()
s = (s / 127).clamp(min=1e-8)
return (x / s).round().clamp(-127, 127) * s
# 1) activations kaise dikhte hain: layer 12 ke linear inputs (512-token window)
which = {"q/k/v": "self_attn.q_proj", "o": "self_attn.o_proj",
"gate/up": "mlp.gate_proj", "down": "mlp.down_proj"}
seen, hooks = {}, []
for key, sub in which.items():
layer = model.get_submodule(f"model.layers.12.{sub}")
hooks.append(layer.register_forward_pre_hook(
lambda mod, args, key=key: seen.__setitem__(key, args[0][0].abs())))
with torch.no_grad():
model(test[:1])
for h in hooks:
h.remove()
for key, a in seen.items(): # a: 512 tokens x channels ki magnitudes
med = a.median(0).values # har channel ka 512 tokens par median
top = med.argmax().item() # sabse bade median wala channel
share = (a.argmax(1) == top).float().mean().item()
tk, ch = divmod(a.argmax().item(), a.size(1)) # global max ki jagah
print(f"{key:<8} overall median {a.median():.3f}, "
f"per-token max ka median {a.amax(1).median():.2f}")
print(f"{'':<8} max {a.max():.1f}: token {tk}, channel {ch}; "
f"us channel ka median {med[ch]:.2f}")
print(f"{'':<8} sabse bade median wala channel {top}: {med[top]:.2f}, "
f"{share:.0%} tokens mein max isi channel mein")
# 2) weights INT8 (per-row scaling) + activations INT8: tensor vs per-token
set_weights(lambda i, w: fake_quant(w, 8, "row"))
print(f"W8A16 (sirf weights) perplexity {ppl():.2f}")
for per_token in (False, True):
hooks = [m.register_forward_pre_hook(
lambda mod, args: (act_quant(args[0], per_token),))
for m in linears]
mode = "per token" if per_token else "whole tensor"
print(f"W8A8 (activations {mode}) perplexity {ppl():.2f}")
for h in hooks:
h.remove()
set_weights(lambda i, w: w.clone())
Output:
q/k/v overall median 0.454, per-token max ka median 11.88
max 39.2: token 0, channel 62; us channel ka median 0.74
sabse bade median wala channel 646: 9.36, 44% tokens mein max isi mein
o overall median 0.138, per-token max ka median 1.72
max 5.2: token 439, channel 2; us channel ka median 0.46
sabse bade median wala channel 14: 0.67, 5% tokens mein max isi mein
gate/up overall median 0.431, per-token max ka median 11.06
max 26.6: token 0, channel 62; us channel ka median 0.49
sabse bade median wala channel 570: 9.69, 58% tokens mein max isi mein
down overall median 0.047, per-token max ka median 1.55
max 7.8: token 445, channel 961; us channel ka median 0.05
sabse bade median wala channel 1671: 0.49, 0% tokens mein max isi mein
W8A16 (sirf weights) perplexity 16.29
W8A8 (activations whole tensor) perplexity 111.78
W8A8 (activations per token) perplexity 16.75
Note: numbers original run se hain; print labels Latin transliteration mein likhe gaye hain।
- Activations mein do tarah ke bade values. Pehla type fixed channels mein: q/k/v ke input (RMSNorm ka output) mein channel 646 ki magnitude median 9.36 - overall median 0.454 ka 21 guna; 44% tokens mein hi max isi channel mein. gate/up ke input mein channel 570 waise hi (median 9.69, 58% tokens). Yehi LLM.int8() aur SmoothQuant wale “outlier channels” hain. Doosra type: kuch specific tokens par spikes: q/k/v input ka max 39.2 pehle token (token 0) ke channel 62 par; usi channel ka poore window ka median sirf 0.74. Sun adi (2024) ne aise extreme values ko massive activations kaha. o aur down ke inputs is layer mein aise prominent channels nahi (sabse bade median wale channel 0.7 se kam; 5% aur 0% tokens), par wahi heavy-tail distribution: down input ka max 7.8, median 0.047 ka lagbhag 166 guna. Yeh sirf layer 12, ek window ka observation hai; doosri layers mein position aur size alag।
- Whole-tensor scaling max value se tay hota hai. W8A16 = 16.29; W8A8 whole-tensor = 111.78; per-token = 16.75. q/k/v input ka misaal: whole-tensor scaling ; ek typical element (0.454) sirf lagbhag 1.5 quantization steps; per-token scaling par har token ke max ka median 11.88, , typical element lagbhag 5 steps. Per-token scaling token 0 wale spike ka asar hata deta hai, par fixed channels ke bade values abhi bhi hain - isliye problem sirf 3 guna se zyada halki hui, khatam nahi।
- Industry ke do upay. LLM.int8() (Dettmers adi, 2022) outlier-containing kuch feature dimensions (paper threshold 6.0 se decide; lagbhag 0.1%) alag karke 16-bit compute, baaki 99.9% per-vector 8-bit. SmoothQuant (Xiao adi, 2022) mathematically-equivalent transform se activation ke outlier magnitudes ko channels ke hisaab se weights par shift karta hai: ; activations ko se divide, weights ko se multiply - dono quantize karna aasaan; paper max 1.56x speedup aur 2x memory reduction report karta hai।
Experiment 3: calibration data se error ghatana
RTN sirf weights dekhta hai, yeh nahi ki wo inputs se kya multiply honge. Asal mein control karna hai har layer ka output error. Maan lo kisi layer ke weights , quantized , aur layer ke calibration tokens ke inputs ():
input ka second-order statistic hai (is least-squares objective ke liye Hessian se sirf constant factor ka farq; size , token count se independent). SmoothQuant, AWQ, GPTQ sab chhoti calibration batch se input statistics estimate karke quantize karte hain. Neeche training set ke pehle 64 windows (32,768 tokens, test se overlap nahi) se teen cheezein: har layer ki , har input channel ki average magnitude (AWQ ke liye) aur max magnitude (SmoothQuant ke liye):
train_ids = tok(wikitext("train")[:500_000], return_tensors="pt").input_ids[0]
calib = train_ids[:64 * CTX].view(64, CTX).to(dev) # calib: pehle 64 windows
H = [torch.zeros(m.in_features, m.in_features, device=dev) for m in linears]
amean = [torch.zeros(m.in_features, device=dev) for m in linears]
amax = [torch.zeros(m.in_features, device=dev) for m in linears]
def collect(i):
def hook(mod, args):
x = args[0].reshape(-1, mod.in_features)
H[i] += x.T @ x # second-order statistic: Σ x xᵀ
amean[i] += x.abs().sum(0) # har channel ki avg magnitude (pehle sum)
amax[i] = torch.maximum(amax[i], x.abs().amax(0)) # max magnitude
return hook
hooks = [m.register_forward_pre_hook(collect(i))
for i, m in enumerate(linears)]
with torch.no_grad():
for x in calib.split(4):
model(x)
for h in hooks:
h.remove()
for i in range(len(linears)):
H[i] /= calib.numel()
amean[i] /= calib.numel()
print(f"calibration: {len(calib)} windows, {calib.numel()} tokens; "
f"Hessians total {sum(h.numel() for h in H) * 4 / 1e9:.1f} GB")
Output:
calibration: 64 windows, 32768 tokens; Hessians total 2.7 GB
Pehle SmoothQuant se experiment 2 ki problem solve karein. Neeche har linear layer ko se smooth, weights abhi bhi per-row INT8, activations whole-tensor INT8 (har forward par fresh scaling), scan:
def smooth(alpha):
"""SmoothQuant: activation ke outlier magnitudes ko weights par shift,
mathematically equivalent."""
scales = []
def one(i, w):
w_max = w.abs().amax(0).clamp(min=1e-5) # har channel ke weights ka max
s = (amax[i].clamp(min=1e-5) ** alpha / w_max ** (1 - alpha))
scales.append(s.clamp(min=1e-5))
return fake_quant(w * scales[-1], 8, "row") # weights ko s se multiply karke quantize
set_weights(one)
return scales
for alpha in (0.3, 0.5, 0.7, 0.8, 0.9, 1.0):
scales = smooth(alpha)
hooks = [m.register_forward_pre_hook( # activations ko s se divide karke tensor quantize
lambda mod, args, i=i: (act_quant(args[0] / scales[i], False),))
for i, m in enumerate(linears)]
print(f"SmoothQuant alpha={alpha}: W8A8 (act tensor) perplexity {ppl():.2f}")
for h in hooks:
h.remove()
set_weights(lambda i, w: w.clone())
Output:
SmoothQuant alpha=0.3: W8A8 (act tensor) perplexity 96.26
SmoothQuant alpha=0.5: W8A8 (act tensor) perplexity 25.10
SmoothQuant alpha=0.7: W8A8 (act tensor) perplexity 18.76
SmoothQuant alpha=0.8: W8A8 (act tensor) perplexity 18.12
SmoothQuant alpha=0.9: W8A8 (act tensor) perplexity 18.57
SmoothQuant alpha=1.0: W8A8 (act tensor) perplexity 19.21
- Smoothing ne whole-tensor INT8 ka W8A8 bacha liya. Bina smoothing 111.78; par 18.12 - W8A16 ke 16.29 se sirf 1.83।
- ek knob hai jiska optimum point hai. bahut chhota to activations ke bade values dab-te nahi (0.3 par 96.26, 0.5 par 25.10); bahut bada to difficulty weights par chali jaati hai (1.0 par 19.21 wapas). Best 0.8 ke aaspaas. Paper ko OPT aur BLOOM ka default rakhta hai, mushkil activations wale GLM-130B ke liye 0.75, aur chhoti batch par grid search ki salah deta hai. Is page ke model ka optimal paper ke default se alag - khud search karna padta hai।
- Whole-tensor scaling sabse sasta tier hai. Paper weights aur activations dono whole-tensor scaled, activation ka scaling calibration data se pehle tay (O3) ko sabse efficient config maanta hai - isliye uske liye smoothing layak hai. Agar runtime per-token max nikaal sakte hain, to smoothing ka fayda kam ho jaata hai (exercise 5)।
Phir low-bit weight quantization: AWQ aur GPTQ. Inka target INT4, INT3 ke weight errors hain।
AWQ (Activation-aware Weight Quantization) ka idea: weights equally important nahi hain. Input channel ki activation magnitude badi ho to us channel ke weights ka error amplified hota hai. Aise channels ke weights ko se multiply karke quantize karne par unki relative error ghatti hai; input ko se divide karte hain - mathematically equivalent (real implementation mein pichhle operator mein merge ho jaata hai). Paper leta hai, jahan us channel ki average activation magnitude, aur par grid search se chunta hai jo output error minimize kare; alawa weight clipping bhi. Neeche awq teaching-simplified hai: har layer independent search, 11 grid points, no clipping।
def rtn(w, H, a, bits, group): # teen methods same signature; a sirf AWQ use karta hai
return fake_quant(w, bits, group)
def awq(w, H, a, bits, group):
"""AWQ-style: activation magnitude se input channels badhakar quantize;
output error minimize karne wala exponent alpha search karo."""
best = (float("inf"), None)
for alpha in [i / 10 for i in range(11)]: # alpha=0 hi RTN hai
s = a.clamp(min=1e-5) ** alpha
s = s / (s.max() * s.min()).sqrt()
wq = fake_quant(w * s, bits, group) / s
d = w - wq
err = ((d @ H) * d).sum().item() # calibration par output error tr(d H dᵀ)
best = min(best, (err, wq), key=lambda t: t[0])
return best[1]
def evaluate(tag, fn, bits, group):
rel = []
def one(i, w):
wq = fn(w, H[i], amean[i], bits, group)
d = w - wq
rel.append((((d @ H[i]) * d).sum() / ((w @ H[i]) * w).sum()).item())
return wq
set_weights(one)
print(f"{tag:<5} INT{bits} g{group} rel output error "
f"{sum(rel) / len(rel):.4f} perplexity {ppl():.2f}")
for bits in (4, 3):
for tag, fn in (("RTN", rtn), ("AWQ", awq)):
evaluate(tag, fn, bits, 128)
set_weights(lambda i, w: w.clone())
Output:
RTN INT4 g128 rel output error 0.0151 perplexity 22.41
AWQ INT4 g128 rel output error 0.0111 perplexity 20.16
RTN INT3 g128 rel output error 0.0742 perplexity 223.43
AWQ INT3 g128 rel output error 0.0574 perplexity 75.18
GPTQ weights column-by-column quantize karta hai: har column quantize karne ke baad us column ke quantization error ko ke hisaab se un-quantized columns par compensate karta hai. Specifically ka Cholesky decomposition se upper triangular (); column ka quantization error ; har aage wala column update: . Paper ke teen engineering tricks: saare rows ek hi column order use karte hain, ek baar hi compute; har 128 columns ek block mein lazy batch update, compute-to-memory ratio behtar; diagonal mein average diagonal value ka 1% damping, numerical stability ke liye. Neeche 30 lines se chhota implementation, block size = group size 128, CPU par float64:
def gptq(w, H, a, bits, group, damp=0.01):
"""GPTQ: column-by-column quantize; har column ka error H inverse se
un-quantized columns par spread."""
w, H = w.cpu().double(), H.cpu().double()
n = w.shape[1]
dead = H.diag() == 0 # kabhi activate nahi hue input channels
H[dead, dead] = 1
w[:, dead] = 0
H += damp * H.diag().mean() * torch.eye(n, dtype=H.dtype) # damping
L = torch.linalg.cholesky(H)
Hinv = torch.cholesky_solve(torch.eye(n, dtype=H.dtype), L)
U = torch.linalg.cholesky(Hinv, upper=True) # H⁻¹ ka Cholesky factor
qmax = 2 ** (bits - 1) - 1
q = torch.zeros_like(w)
for i1 in range(0, n, group): # block size = group size
i2 = i1 + group
s = (w[:, i1:i2].abs().amax(1) / qmax).clamp(min=1e-8)
err = torch.zeros(w.shape[0], group, dtype=w.dtype)
for j in range(group):
col, d = w[:, i1 + j], U[i1 + j, i1 + j]
q[:, i1 + j] = (col / s).round().clamp(-qmax, qmax) * s
err[:, j] = (col - q[:, i1 + j]) / d
w[:, i1 + j:i2] -= err[:, j:j + 1] * U[i1 + j, i1 + j:i2]
w[:, i2:] -= err @ U[i1:i2, i2:] # poore block ka error aage ke columns ko
return q.float().to(dev)
for bits in (4, 3):
evaluate("GPTQ", gptq, bits, 128)
set_weights(lambda i, w: w.clone())
Output:
GPTQ INT4 g128 rel output error 0.0055 perplexity 18.40
GPTQ INT3 g128 rel output error 0.0286 perplexity 47.01
RTN, AWQ aur GPTQ ek saath (group size 128, baseline 16.25):
| Method | INT4 rel output error | INT4 perplexity | INT3 rel output error | INT3 perplexity |
|---|---|---|---|---|
| RTN | 0.0151 | 22.41 | 0.0742 | 223.43 |
| AWQ-style | 0.0111 | 20.16 | 0.0574 | 75.18 |
| GPTQ | 0.0055 | 18.40 | 0.0286 | 47.01 |
- Output error ka order aur perplexity ka order match karte hain: RTN, AWQ, GPTQ kram se behtar. INT4 par GPTQ baseline se farq 6.16 se 2.15 (65% kam); teaching AWQ 3.91 par।
- Calibration ke barabar bits bach jaate hain. GPTQ ka 4.125-bit perplexity (18.40), bina-calibration RTN ko 5 bits (group size 16, 18.08) lene par hi milta hai।
- 3 bits abhi bhi bahut tight. Calibration methods INT3 ko collapse (223) se 75 aur 47 tak laate hain, par baseline 16.25 se abhi bhi bahut door; 0.5B chhote model par unusable. Bada model, chhota group, ya sensitive layers ko high bit-width par rakhna hi asli raasta hai।
- Yeh teaching version hai, paper ka poora result nahi. Teaching AWQ har linear layer ko independently search karta hai; real implementation mein same input share karne wali layers (
q/k/v,gate/up) ko ek hi share karna hota hai, kyunki pichhli RMSNorm mein merge hota hai - performance yahan se thodi kam, aur paper weight clipping bhi karta hai. GPTQ ki calibration set sirf 64 windows, aur WikiText hi hai (test jaisa domain); zyada alag domain ke data par gain ghat jaata hai. AWQ paper highlight karta hai ki woh sirf activation ki average magnitude use karta hai - calibration set par kam nirbhar, overfit hona mushkil। - Keemat alag hai. RTN ko data nahi chahiye; AWQ ko sirf activation statistics, search sasta; GPTQ ko har layer ki store (is page total 2.7 GB), Cholesky decomposition, aur per-column serial loop - bahut dheema (is page ke experiments mein sabse dheema step)।
Experiment 4: KV cache quantization
KV cache context length aur concurrency ke saath linearly badhta hai (shuru ka hisaab dekhein). Qwen2.5-0.5B GQA use karta hai - sirf 2 KV heads; har token sirf 12,288 bytes; ek 32K sequence bhi 403 MB - BF16 weights (988 MB) ka lagbhag 41%. Neeche cache mein likhi jaane wali K aur V ko INT8 ya INT4 mein quantize. Default: har token, har head ka ek scaling factor (64 numbers share); K ke liye ek aur option per-channel scaling: har channel, har 32 tokens ka ek scaling - KIVI paper (Liu adi, 2024) ka K ke liye tareeka।
from transformers import DynamicCache
cfg = model.config
head_dim = cfg.hidden_size // cfg.num_attention_heads
per_token = 2 * cfg.num_hidden_layers * cfg.num_key_value_heads * head_dim * 2
print(f"KV cache per token: {per_token} bytes (BF16); "
f"ek 32K sequence {per_token * 32768 / 1e6:.0f} MB")
def kv_quant(x, bits, per_channel=False, g=32):
"""x: (batch, heads, seq, 64). Default har token har head ka scaling;
per_channel: har channel har g tokens ka scaling (KIVI ka K wala)."""
b, h, n, d = x.shape
if per_channel:
x = x.reshape(b, h, n // g, g, d).transpose(3, 4)
q = fake_quant(x.reshape(-1, x.size(-1)), bits, "row").reshape(x.shape)
return q.transpose(3, 4).reshape(b, h, n, d) if per_channel else q
def kv_cache(k_bits, k_chan, v_bits):
class QuantCache(DynamicCache):
def update(self, k, v, layer_idx, cache_kwargs=None):
if k_bits < 16: # 16 matlab quantize nahi
k = kv_quant(k, k_bits, k_chan)
if v_bits < 16:
v = kv_quant(v, v_bits)
return super().update(k, v, layer_idx, cache_kwargs)
return QuantCache
cases = [(16, False, 16), (8, False, 8), (4, False, 4), (4, False, 16),
(16, False, 4), (8, True, 8), (4, True, 4)]
for k_bits, k_chan, v_bits in cases:
ktag = "K as-is" if k_bits == 16 else f"K INT{k_bits}" + (" per-chan" if k_chan else "")
vtag = "V as-is" if v_bits == 16 else f"V INT{v_bits}"
print(f"{ktag}, {vtag}: perplexity {ppl(kv_cache(k_bits, k_chan, v_bits)):.2f}")
Output:
KV cache per token: 12288 bytes (BF16); ek 32K sequence 403 MB
K as-is, V as-is: perplexity 16.25
K INT8, V INT8: perplexity 16.95
K INT4, V INT4: perplexity 62.46
K INT4, V as-is: perplexity 59.62
K as-is, V INT4: perplexity 16.51
K INT8 per-chan, V INT8: perplexity 16.26
K INT4 per-chan, V INT4: perplexity 18.00
Note: numbers original run se hain; print labels Latin transliteration mein likhe gaye hain।
- INT8 mein is baat par nirbhar ki K kaise quantize kiya. K, V dono per-token scaled: INT8 perplexity 16.95 (0.70 upar); K ko per-channel karne par INT8 lagbhag lossless (16.26)।
- INT4 ka error lagbhag sab K se aata hai. Sirf V ko INT4: perplexity 16.51 (0.26 upar); sirf K ko INT4: 59.62; dono per-token: 62.46 - unusable।
- K ko per-channel scaling par problem lagbhag solve. K per-channel, V per-token, dono INT4: perplexity 18.00. KIVI ki observation same: K per-channel quantize hona chahiye, V per-token।
- Keemat. Per-channel scaling ka factor har 32 tokens par ek - K ka effective bit-width 4.5 bits (per-token 4.25); aur quantize karne ke liye ek group bhar tokens jama karne padte hain - KIVI latest tokens ko full-precision buffer mein rakhta hai. Yeh experiment poora window ek saath likhta hai, woh simulate nahi kiya - isliye per-channel numbers thode optimistic hain।
Results ek saath
| Scheme | Quantization target | Effective bits | Perplexity | Baseline se farq |
|---|---|---|---|---|
| BF16 baseline | koi nahi | 16 | 16.25 | 0 |
| INT8, per-row RTN | weights | 8.014 | 16.29 | 0.04 |
| INT4, g128, RTN | weights | 4.125 | 22.41 | 6.16 |
| INT4, g128, AWQ-style | weights | 4.125 | 20.16 | 3.91 |
| INT4, g128, GPTQ | weights | 4.125 | 18.40 | 2.15 |
| INT3, g128, GPTQ | weights | 3.125 | 47.01 | 30.76 |
| W8A8, act per-token | weights + activations | 8 | 16.75 | 0.50 |
| W8A8, SmoothQuant (alpha=0.8), act tensor | weights + activations | 8 | 18.12 | 1.87 |
| KV: K aur V dono INT8, per-token | KV cache | 8.25 | 16.95 | 0.70 |
| KV: K per-channel, V per-token, dono INT4 | KV cache | K 4.5, V 4.25 | 18.00 | 1.75 |
Selection aur launch
Pehle bottleneck pehchano
| Aapka bottleneck | Pehle kya karein | Aadhar |
|---|---|---|
| Weights fit nahi, ya decode dheemi (memory-bound) | Weight quantization: pehle INT8 (per-row), kaam na kare to INT4 g128, AWQ ya GPTQ calibration ke saath | Experiments 1, 3: INT8 lagbhag lossless, INT4 ko grouping + calibration, chhote models fragile |
| High concurrency ya lambe context par KV cache kaafi nahi | KV cache quantization (is page INT8/INT4 algorithm measure karta hai; vLLM mein FP8 KV cache), PagedAttention ke saath | Experiment 4 + shuru ka hisaab: KV cache concurrency tay karta hai; INT4 ke liye K per-channel |
| Prefill ya large batch compute-bound | W8A8 ya FP8, activations per-token, ya pehle SmoothQuant | Experiments 2, 3: activations ke outlier channels aur spikes |
| Fine-tuning mein memory kam | QLoRA: 4-bit NF4 base freeze, sirf LoRA adapters train | QLoRA paper: 65B model ek 48 GB GPU par |
| Quantization ke baad quality giri, kahan giri pata nahi | INT8 par wapas baseline; layer type aur depth ke hisaab se sensitivity naapo; sensitive parts high bit-width | Experiment 1 ke baad ki sensitivity table |
Tools aur formats
| Naam | Upyog | Note |
|---|---|---|
| bitsandbytes | LLM.int8() aur NF4 (QLoRA ka 4-bit data type) | Load time par instant quantization, calibration data nahi chahiye |
| GPTQModel, AutoAWQ | GPTQ, AWQ format ke quantized models generate aur load | Dono weight-only (W4A16 type) |
| LLM Compressor | vLLM deployment ke liye quantization library; FP8, INT8 W8A8, INT4 W4A16 support | vLLM docs dekhein |
| llama.cpp (GGUF) | Local inference ka format aur runtime; kai chunked quantization types | Laptop aur edge devices ke liye |
| vLLM | Serving framework; upar ke kai weight formats support; KV cache mainly FP8 (--kv-cache-dtype fp8) | Supported formats version ke saath badalte hain; docs final (yeh page November 2026 ke docs par likha gaya) |
Symptoms, causes aur actions
| Jo dikhta hai | Zyada likely problem | Zyada fit action |
|---|---|---|
| Memory bachi, par speed lagbhag wahi | Bits kam nahi, kernel mismatch ya framework support kam; ya asli bottleneck KV cache/scheduling | Same-conditions tokens/s compare, GPU utilization dekho, framework-format compatibility confirm |
| 4-bit laga aur answer quality saaf giri | Task precision-sensitive, calibration set unfit, ya kuch layers quantization ke liye bahut fragile | INT8 baseline par wapas; AWQ vs GPTQ compare; sensitive layers high bit-width; real business samples par degradation dekho |
| Model chhota hua, par lambe context par abhi OOM | Weights dabe, KV cache/concurrency/request length phata | Context aur concurrency limit, KV cache quantize, PagedAttention + continuous batching |
| Kharab lagta hai, par kahan kharab pata nahi | High-precision baseline, fixed samples aur rollback path nahi | Pehle high-precision baseline aur fixed eval set rakho, phir quantization compare |
Launch se pehle ki checklist: BF16 ya FP16 baseline ho; eval set mein apne task ke samples hon, sirf perplexity aur public benchmarks nahi; memory, tokens/s aur quality teeno record; quantization format aur inference framework version fix; high-precision version par jaldi switch karne wala rollback path ho।
Common galtiyan
- Low bit ka matlab “zaroor tez” nahi. Weight quantization sirf memory-bound decode tez karta hai; kernel mismatch par gain chhota; prefill aur large batch compute-bound - W8A8 ya FP8 chahiye।
- Sirf perplexity ya public benchmarks dekhna. Perplexity quantization par sensitive hai, par aapke task se sync nahi; kuch models public benchmarks par thoda girate hain par vertical tasks par saaf girti hain।
- Quantization target ignore karna. Weights, activations, KV cache ki difficulties aur fayde alag: weights ko grouping + calibration, activations mein outlier channels aur spikes, KV cache mein K V se zyada sensitive।
- Simulated quantization ko real deployment samajhna. Simulated quantization algorithm ki precision loss naapta hai; real kernels mein accumulation precision, data layout, fusion waghera hain - launch se pehle real format par phir test karein।
- Rollback path nahi banaya. Quantization ke baad quality girne par high-precision par jaldi switch hona chahiye, warna troubleshooting bahut mehngi।
Research case: KV cache ki bit-width layer-wise badalna
Berkeley Scalable AI ka EchoKV project KV cache ki precision layer-wise adjust karne ko explore karta hai. Idea: chhota high-precision reference se error track karna, controller uske aadhar par bit-width allocate karta hai. Yeh uniform bit-width ke selection problem ko memory budget ke andar allocation problem banata hai; reference cache, error estimation aur switching overhead bhi laata hai।
Experiments padhte waqt frozen aur dynamic protocols alag karein. Frozen allocation ke baad same budget par uniform vs per-layer bit-width ke output differences compare ho sakte hain. Dynamic runtime mein controller updates, precision switching aur end-to-end latency alag se naapne padte hain. Project khud dynamic controller ka independent benchmark future work ke roop mein list karta hai. Review karte waqt same token trajectory rakhkar local errors dekhein, phir har config ko freely generate karke error accumulation ke task-level asar evaluate karein।
Summary aur exercises
Is page ke mukhya points:
- Quantization ka fayda teen jagah se: weights ki memory, har step padhne wale bytes (decode ki speed ceiling), KV cache (concurrency). Teenon ke bottlenecks alag - pehle bottleneck pehchano, phir scheme chuno. Llama-3-8B 80 GB card par: BF16 lagbhag 52 8K-sequences; sirf weights INT4 par 61; KV cache bhi INT8 par 121।
- Symmetric quantization , error se kam. Ek outlier phula deta hai, isliye 4-bit ko grouping chahiye; effective bit-width = bits + 16/group size; group 128 par 4.125।
- Qwen2.5-0.5B par INT8 per-row scaling lagbhag lossless (16.25 se 16.29); INT4 whole-tensor collapse, g128 RTN 22.41. Calibration se same 4.125 bits par 20.16 (AWQ-style) aur 18.40 (GPTQ); latter bina-calibration RTN ke 5 bits (g16, 18.08) ke barabar।
- Activations mein fixed channels ke bade values aur specific tokens ke spikes: whole-tensor INT8 W8A8 = 111.78; per-token scaling (16.75) ya SmoothQuant (18.12) bachata hai।
- KV cache mein K V se zyada sensitive: K per-channel, V per-token INT4 par bhi sirf 18.00; dono per-token par 62.46।
- Simulated quantization sirf algorithm ki precision loss naapti hai. Launch se pehle real kernels aur formats, aur memory + tokens/s + quality teeno, rollback path ke saath।
Quick self-test
1. 70B-parameter model, weights INT4 (group size 128, effective 4.125 bits) mein. Sirf weights lagbhag kitni memory?
- Lagbhag 70 GB
- Lagbhag 36 GB
- Lagbhag 17.5 GB
- Lagbhag 140 GB
bytes, lagbhag 36 GB. 70 GB INT8 ka hisaab hai, 140 GB BF16 ka, 17.5 GB 2-bit ka।
2. Whole-tensor INT4 perplexity tak le jaata hai; har 128 weights ka group sirf 22.41. Mukhya wajah?
- Whole-tensor kam bits use karta hai
- Ek tensor ka max value typical weights se bahut bada hai; scaling factor phool jaata hai aur zyada tar weights 0 mein round ho jaate hain
- Whole-tensor quantization ke baad float restore nahi hota
- Grouping trainable parameters badha deti hai
Dono 4-bit hain. Experiment 1 mein har layer ka max|w|/median|w| median 27; whole-tensor scaling par 74.3% weights 0 bane, g128 par 19.7%।
3. Experiment 2 mein W8A8 whole-tensor activation scaling perplexity 111.78, per-token 16.75. Yeh kya batata hai?
- INT8 ke bits kaafi nahi; activations ko 16-bit chahiye
- Activations mein kuch bahut bade values hain; whole-tensor scaling max se tay hota hai aur baaki elements ke paas bahut kam quantization steps rehte hain; per-token scaling asar ko apni row mein seemit karta hai
- Activation quantization weight quantization se aasaan hai
- Perplexity activation quantization error par sensitive nahi
Whole-tensor scaling factor max 39.2 se tay hota hai; typical element (0.454) ke paas lagbhag 1.5 quantization steps; per-token scaling par lagbhag 5।
4. 80 GB card par Llama-3-8B, 8K context, concurrency KV cache se block hai. Shuru ke hisaab ke mutabiq kaun sa action concurrency sabse zyada badhata hai?
- Weights BF16 se INT4 (52 se 61)
- Weights already INT4, ab KV cache BF16 se INT8 (61 se 121)
- Prefill ka batch badhana
- Zyada bandwidth wali memory par shift
Concurrency = (available memory - weights) / per-sequence KV cache. 72 GB available mein BF16 weights 16 GB; INT4 par sirf lagbhag 10 GB bachte hain; per-sequence KV cache aadha hote hi fit hone wali sequences seedha double. Bandwidth speed ko, capacity ko nahi, asar deta hai।
5. Experiment 4 mein sirf K INT4 (per-token) = 59.62, sirf V INT4 = 16.51. Agla sabse logical step kya hai?
- KV cache quantization chhod dena
- K ki quantization granularity badalna: per-channel scaling, V abhi bhi per-token (KIVI ka tareeka)
- V ko INT8 karna, K same
- Calibration set badhana
Error lagbhag sab K se hai; V chhedne se kuch nahi hoga. K per-channel, V per-token, dono INT4 par perplexity 18.00 tak girti hai।
6. GPTQ aur RTN ka fundamental farq kya hai?
- GPTQ zyada bits use karta hai
- GPTQ column-by-column quantize karta hai aur har column ke quantization error ko se un-quantized columns par compensate karta hai, jisse layer ka output error chhota rehta hai
- GPTQ ko poora model retrain karna padta hai
- GPTQ sirf activations quantize karta hai
Experiment 3 mein, dono INT4 g128: RTN rel output error 0.0151, GPTQ 0.0055; perplexity 22.41 vs 18.40।
Exercises:
- Symmetric INT4 (integer range se ) se quantize karein: , integers , reconstructed aur max absolute error nikaalein. Phir 0.90 ko 0.30 kar dein - max error kitna? Yeh kya batata hai?
- Qwen2.5-0.5B har token ki KV cache 12,288 bytes. 8 concurrent 32K sequences kitni memory chahiye? KV cache INT8 (effective 8.25 bits) par? BF16 weights (988 MB) se compare karein।
- Is page ka GPTQ 168 linear layers ke liye har ek float32 matrix store karta hai ( layer ke input dim:
down_projka 4864, baaki sab 896). Total bytes ka expression likhein, result nikaalein, aur kaun si layer type sabse zyada leti hai batayein। - Experiment 1 mein group size 16 RTN = 5.0 bits, perplexity 18.08. Group size 8 tak aur ghataayein: pehle effective bit-width predict karein, phir run karke dekhein perplexity kitni behtar hui, aur GPTQ (4.125 bits, 18.40) se compare karein।
- SmoothQuant () aur per-token dynamic activation quantization ko stack karein:
act_quant(args[0] / scales[i], False)meinFalsekoTruekarein. Pehle predict karein perplexity sirf-per-token (16.75) se achhi hogi ya buri, W8A16 (16.29) se kitni door; phir run karke verify karein। - AWQ ka scaling factor pichhli layer mein merge kyun ho sakta hai bina inference overhead ke?
q/k/vko same share kyun karna padta hai?
Reference answers
- , , ; errors , max error 0.050: 0.05 ka 0 mein round ho jaana. 0.90 ko 0.30 karne par , , max error sirf 0.0086. Outlier ko 3x phula deta hai, error bound bhi 3x; is misaal mein actual max error lagbhag 5.8x badha, aur chhote numbers ki resolution khatam।
- Ek sequence bytes, lagbhag 403 MB; 8 sequences 3.22 GB - BF16 weights (988 MB) ka 3.3x. INT8 (8.25/16) par 1.66 GB. Lambe context + high concurrency par KV cache weights se bhi bada।
- Elements , x 4 bytes = 2.73 GB. Isme
down_projki ka hissa : ka size hai; 4864-dim layer 896-dim ka guna. Same-input wali layers ko share karwana (q/k/vek,gate/upek) sirf 2.50 GB tak le jaata hai, lagbhag 8% bachat। - Group size 8 ka effective bit-width bits. Measured perplexity 17.68 - g16 ke 18.08 se sirf 0.40 behtar, par 1 bit zyada kharch; GPTQ 4.125 bits par 18.40, RTN ke 5-bit 18.08 ke kareeb. Grouping ke returns ghat-te hain; calibration bits bachane ka doosra raasta hai।
- Measured 16.38 - sirf-per-token 16.75 se 0.37 kam, W8A16 16.29 se sirf 0.09 door. Experiment 2 ke do tarah ke bade values: fixed channels wale smoothing se handle, token-to-token magnitude differences per-token scaling se; stack dono ko handle karta hai, isliye behtar।
- input channel ka per-channel scaling hai; jo operator yeh input banata hai usme merge ho sakta hai: RMSNorm ke per-channel weight ko kar do, ya pichhli linear layer ke output channels ko se multiply - naya operator nahi.
q/k/vek hi RMSNorm ke output padhte hain, aur us output ka sirf ek hai - isliye teeno linear layers ko same share karna hota hai. Teaching version har layer independently search karta hai, yeh constraint nahi - isliye real implementation se thoda optimistic।
Aage padhein
- Quantization ke mukhya fayde KV cache aur memory-access bottleneck hain: KV cache aur inference performance; launch, monitoring aur framework selection: LLM inference service; PagedAttention ka original: vLLM paper।
- 4-bit base par fine-tuning (QLoRA): LoRA fine-tuning; bytes padhna kam karne ke alawa speed badhane ka raasta: speculative decoding; GQA KV cache kyun chhota karta hai: efficient attention: MQA, GQA, MLA aur FlashAttention।
- Original papers: Dettmers adi ka LLM.int8(); Xiao adi ka SmoothQuant; Frantar adi ka GPTQ; Lin adi ka AWQ; Dettmers adi ka QLoRA; Liu adi ka KIVI; Sun adi ka Massive Activations in Large Language Models।
- Engineering docs: vLLM docs ka Quantization section (weight quantization formats, hardware support matrix aur FP8 KV cache; yeh page November 2026 ke version par likha gaya)।
- Lin adi ka QuaRot (2024) aur Liu adi ka SpinQuant (2024): rotation matrices se activations ke outliers ko “flatten” karke 4-bit weight quantization ko per-layer fine calibration se mukt karna; PTQ ko QAT-jaisi quality ke kareeb le jaana।
- Shao adi ka OmniQuant (2023): learnable quantization ranges aur weight clipping - PTQ aur QAT ke beech।
- Kuzmin adi ka FP8 versus INT8 for efficient deep learning inference (2025) aur Kuzmin adi ka Scaling Laws for Precision (2024): integer vs float low-precision formats ka systematic comparison, aur “precision” ko scaling laws mein daalne ki koshish।
अक्सर पूछे जाने वाले सवाल
- Model quantization kya hai, aur kyun karte hain?
- Quantization weights, activations ya KV cache ko kam bits (jaise INT8, INT4) mein represent karta hai, taaki memory aur memory-access overhead ghatta hai. Teen fayde: model chhote GPU mein fit hota hai; decode phase har step kam bytes padhta hai isliye tez; KV cache chhota, isliye lamba context ya zyada concurrency. Keemat precision loss hai, aur speed fayda tabhi hai jab inference kernels aur hardware low-bit compute sach mein support karte hain।
- PTQ aur QAT mein kya farq hai?
- Post-training quantization (PTQ) model train hone ke baad quantize karta hai - sasta, deploy karne mein aasaan; open-source deployment ka aam raasta, GPTQ aur AWQ dono PTQ hain. Quantization-aware training (QAT) training ke dauran quantization error simulate karta hai, model dheere-dheere low-bit representation ke saath adjust hota hai - potential precision behtar, par implementation complex aur training cost zyada।
- GPTQ aur AWQ mein kya chunein?
- Dono weight-only post-training quantization hain, 4-bit ke aaspaas aam. GPTQ column-by-column quantize karta hai aur second-order info (Hessian) se error ko un-quantized columns par compensate karta hai; AWQ activation magnitudes se important input channels chunta hai, unhe badhakar quantize karta hai, backprop nahi chahiye. Is page ka measurement Qwen2.5-0.5B par (4-bit, group size 128): RTN perplexity 22.41, teaching AWQ 20.16, GPTQ 18.40, baseline 16.25. Asli selection mature support, framework compatibility aur task sensitivity par nirbhar hai; apne business samples se validate karein।
- Quantize karne ke baad zaroor tez hota hai?
- Hamesha nahi. Weight quantization mainly memory-access-bound decode ko tez karta hai; jitne kam bytes per step, utna tez. Prefill compute-bound hai, sirf weights quantize karne se madad nahi. Speed inference kernels aur hardware ke low-bit support par bhi nirbhar hai; kernel mismatch par gain chhota. Launch se pehle memory, tokens/s aur task quality teeno check karein, aur high-precision version par rollback ka raasta rakhein।
- 4-bit quantization ko grouping kyun chahiye, group size kaise chunein?
- Jab poora tensor ya poora row ek hi scaling factor use kare, ek outlier hi scaling ko phula deta hai aur baaki weights kuch hi integer levels mein simat jaate hain. Grouping outlier ke asar ko uske apne group mein seemit karta hai; keemat: har group ek scaling factor: group size 128 par effective bit-width 4.125. Qwen2.5-0.5B par INT4 perplexity: whole-tensor par 8x10^7 tak collapse, per-row 36.35, group size 128/64/32/16 par 22.41/20.36/19.50/18.08 (baseline 16.25). Aam compromise 128 hai।
- Activations aur KV cache bhi quantize ho sakte hain?
- Haan, par weights se mushkil. Activations mein kuch channels ki magnitude baaki se bahut badi hoti hai; whole-tensor INT8 mein perplexity 16.25 se 111.78 ho jaati hai, per-token scaling par 16.75. KV cache INT8 mein lagbhag lossless; INT4 mein K V se bahut zyada sensitive hai - K ko per-channel karne par perplexity 62.46 se 18.00 (sab Qwen2.5-0.5B measurements)।