Quantization I: foundations
Quantization reduces weight storage and can accelerate memory-bound decoding. Build symmetric and affine quantizers, analyze rounding and clipping, calibrate ranges, compare granularities and simulate integer matrix multiplication. A local lab measures packed weights on an RTX 3060.
After this lesson you can
- Calculate scale and zero point for symmetric or affine quantizers and quantize and dequantize tensors.
- Separate quantization error into rounding and clipping components and find an optimal range.
- Compare calibration methods and granularities by error and actual bits per weight.
- Simulate INT8 matrix multiplication with an INT32 accumulator and requantization and explain when it is faster.
- Measure memory, decoding speed and perplexity for a small LLM with 8-bit and 4-bit weights.
Before you start
A grid to reduce memory
A BF16 parameter occupies two bytes. Ideally, seven billion parameters would occupy 14 decimal GB in weights alone; at four bits they would take 3.5 GB before scales, metadata, KV cache and other memory. Reducing bytes can speed up memory-bound decoding, but storing fewer bits is not enough: the kernel must read and use them efficiently. Memory accounting and the latency-throughput tradeoff determine the actual gain.
A roofline calculation helps decide what to measure. A dense multiplication reusing weights for a batch of vectors performs approximately arithmetic operations. If each weight occupies bits and is read once, weight traffic is bytes and corresponding intensity is approximately operations per byte. This omits activations, scales, repeated reads and dequantization. As grows, weight reuse improves and memory may stop being the bottleneck. Compare effective intensity with the machine’s compute-to-bandwidth ratio and measure the kernel to check which cost dominates.
The figures in this lesson use the first four rows and 128 columns of model.layers.0.self_attn.q_proj.weight from SmolLM2-135M, revision 93efa2f097d58c2a74874c7e644dbc9b0cee75a2. These 512 weights are not a representative sample of all layers. Scale and error are recalculated on them in the browser. The histogram groups weights outside the displayed interval at the ends.
Scale and zero point
Uniform affine quantization maps a real number to an integer in using
Here is the scale and is a representable integer, the zero point. Thus represents exactly. For a desired range including zero, a common recipe is and . Rounding slightly shifts the representable real endpoints. The degenerate case needs an explicit convention to avoid division by zero.
A symmetric variant uses and a symmetric integer range , with and . This leaves the most negative integer of a signed -bit representation unused. The rounding tie-break rule also matters: NumPy uses ties-to-even, while other runtimes may choose another convention. Jacob et al. detail an affine integer inference implementation.
For example, with four bits and symmetric range , and the step is . The value falls halfway between and ; the tie rule decides which to choose. In an affine implementation requesting , the scale is and integer zero is 10. Its integers from 0 to 15 represent to . If requested endpoints do not exactly match the grid after rounding , a fraction of a step can be lost at an endpoint.
Rounding, clipping and calibration
Quantization error has two sources. Inside the range, rounding to the nearest level introduces error of magnitude up to ; outside, clipping also occurs. If rounding error is modeled as uniform in , it has zero mean and variance , calculated by integrating . That assumption is not an identity for arbitrary data or clipped values.
To make the assumption explicit, write . If were independent of the signal and uniform on that interval, and
On a fixed grid without added noise, error is determined by : it is not independent by definition. It can correlate with a structured signal and concentrate at certain grid phases. The approximation is often more useful when many levels are occupied and the range fits well. If you algebraically separate , squaring introduces a cross term; you cannot add two variances without justification. In the figure’s quantizer, clipping endpoints are representable levels. Outside the range, rounding the clipped value gives zero error; inside, clipping error is zero. The cross product vanishes and the two squared errors add, apart from numerical rounding.
With fixed range, doubling levels approximately halves and quarters error power. Under those assumptions the signal-to-noise ratio rises dB per additional bit. Clipped tails and few levels break the approximation. The figure calculates sample error directly and does not assume the 6 dB rule.
Range calibration estimates the grid using data: minimum and maximum avoid clipping the observed sample, but an outlier can make interior steps too coarse. Percentiles sacrifice extremes; minimizing squared error seeks a compromise for the sample; an entropy criterion compares reconstructed distributions. The calibration set should resemble deployment inputs, especially for activations. A range optimal for squared error does not guarantee optimal task accuracy.
MSE search must define the range space, quantizer, zero-point treatment and calibration sample. The KL criterion also requires specifying how histograms are built and division by zero mass is avoided. When static scales are applied to activations, the distribution can change across tasks or positions; with dynamic scales, range calculation is repeated during inference and also has a cost. A value absent during calibration can fall outside the range at deployment.
Granularity and metadata cost
Granularity determines which values share a scale. Per-tensor scaling has little overhead, but a channel with small values can lose resolution if another contains outliers. Per-output-channel scaling assigns one scale to each row of the weight matrix. Grouping divides each row into smaller blocks and increases the number of scales. With groups of weights, FP16 scale and FP16 zero point, the ideal cost is bits per weight, excluding padding and headers.
If final groups are incomplete, count one scale for each actual group: for values and groups that is bits per weight if only an FP16 scale is stored and the zero point is implicit. A packed format may require extra alignment space. The figure assumes a 16-bit scale in the count, but reconstruction uses JavaScript precision to show the effect of the weight grid: quantizing the scale too would introduce another error.
Matmul and requantization
In integer matmul with requantization, represent input and weights as and . Then
The sum is typically accumulated in INT32, and a quantized output uses another scale and zero point with rounding and saturation. The product of scales per output channel can be applied after the sum because it does not depend on . A different scale per input channel does depend on and cannot be extracted as one factor. The accumulator can overflow: bound the dimension and magnitudes or use another strategy.
Expanding the centered sum yields four terms: , , and . The third can be precomputed while weights are fixed; the second depends on the input. If the weight is symmetric, removes two terms. To requantize an output with scale and zero point , multiply the accumulator by , round, add and saturate to the output range. In an entirely integer path, that real multiplication is approximated with a fixed-point multiplier and a shift, with its own rounding error.
Taxonomy and codebooks
Post-training and quantization-aware quantization distinguishes PTQ, which quantizes after training, from QAT, which simulates the grid during training. W4A16 denotes four-bit weights and 16-bit activations; W8A8 quantizes both. The labels alone do not specify granularity, metadata or kernel.
In QAT the forward pass usually applies simulated quantization and reconstruction while the optimizer keeps higher-precision parameters. Since rounding has zero derivative almost everywhere and discontinuities, a surrogate gradient estimator is often used. It is a training approximation, not the exact derivative of rounding. PTQ avoids that tuning but needs calibration compatible with deployment; QAT adds training cost and may adapt better to the chosen format’s error. The study by Nagel et al. presents both approaches and their tradeoffs.
Codebook quantization assigns each value to a table center, which can be nonuniform. Lloyd’s algorithm alternates assignment and center updates to minimize squared error on the sample. Indices consume bits and the codebook also takes memory. Rate-distortion theory studies lossy compression limits under a specified source and distortion; it does not guarantee that a particular table reaches them.
With a codebook of centers, a fixed-length index costs bits plus the shared cost of the table. Quantiles can reserve more levels for dense regions, while k-means adapts centers to squared error. The codebook can reduce error for the same number of indices, but requires lookups or decoding that a kernel must support. Best numerical error does not automatically mean lowest time or best task accuracy.
An affine quantizer from scratch
import numpy as np
def affine(x, low, high, bits=8):
if not low < high or low > 0 or high < 0:
raise ValueError('el rango debe ser no degenerado e incluir cero')
qmax = 2**bits - 1
scale = (high-low)/qmax
zero = int(np.clip(np.rint(-low/scale), 0, qmax))
q = np.clip(np.rint(np.asarray(x)/scale)+zero, 0, qmax).astype(np.int32)
return q, scale, zero, scale*(q-zero)
q, s, z, xhat = affine([-0.4, 0.5, 1.2], -0.4, 1.2)
print('escala', s, 'punto cero', z, 'enteros', q, 'reconstrucción', xhat)The rounded zero point slightly shifts the endpoints: in this example reconstructs as approximately . For , the integer is 144 and its reconstruction is approximately . Endpoint rounding is not an implementation error: it follows from requiring zero to be exactly representable with an integer zero point.
Lab: choosing the range
Compare two seeded samples: one normal and one with Laplace tails. They are not real weights or results from a trained model. To isolate the tradeoff we use a symmetric quantizer with representable endpoints. The function calculates squared clipping error separately from rounding error on the clipped signal. Since outside the range the clipped endpoint is already a grid level, one of the two errors is zero for each sample and their sum matches total error up to numerical precision.
import numpy as np
def symmetric(x, bits, bound):
if bound <= 0 or bits < 2:
raise ValueError('rango positivo y al menos dos bits')
Q = 2**(bits-1)-1
scale = bound/Q
codes = np.clip(np.rint(np.asarray(x)/scale), -Q, Q).astype(np.int32)
return codes, scale, codes*scale
def error_parts(x, reconstruction, bound):
clipped = np.clip(x, -bound, bound)
clip_error = np.mean((x-clipped)**2)
round_error = np.mean((clipped-reconstruction)**2)
assert np.isclose(clip_error+round_error, np.mean((x-reconstruction)**2))
return clip_error, round_error
gen = np.random.default_rng(31)
normal = gen.normal(size=4096)
laplace = gen.laplace(scale=1/np.sqrt(2), size=4096)
for label, x in [('normal', normal), ('laplace', laplace)]:
candidates = np.linspace(np.max(np.abs(x))*.1, np.max(np.abs(x)), 100)
errors = np.array([np.mean((x-symmetric(x, 4, bound)[2])**2) for bound in candidates])
best = candidates[np.argmin(errors)]
for name, bound in [('máximo', np.max(np.abs(x))), ('percentil 99', np.quantile(np.abs(x), .99)), ('MSE', best)]:
_, _, rec = symmetric(x, 4, bound)
clipping, rounding = error_parts(x, rec, bound)
print(label, name, 'rango', round(bound, 3), 'MSE', round(clipping+rounding, 5),
'recorte', round(clipping, 5), 'redondeo', round(rounding, 5))The range minimizing MSE in this sample was chosen among 100 candidates, not by continuous optimization. The percentile criterion ignores how costly errors in discarded samples are, so it need not match minimum MSE. When calibrating activations, separate calibration and evaluation data and preserve the usage domain.
A KL-divergence criterion requires defining histograms and treatment of empty cells. The following uses fixed bins, a small smoothing mass and the same edges for originals and reconstructions. This is one pedagogical implementation, not an equivalent of every entropy calibration used in libraries.
def histogram_kl(original, reconstructed, edges, epsilon=1e-8):
p = np.histogram(original, bins=edges)[0].astype(float) + epsilon
q = np.histogram(reconstructed, bins=edges)[0].astype(float) + epsilon
p /= p.sum()
q /= q.sum()
return np.sum(p*np.log(p/q))
x = laplace
extent = np.max(np.abs(x)) + 1e-6
edges = np.linspace(-extent, extent, 33)
candidates = np.linspace(extent*.2, extent, 50)
scores = [histogram_kl(x, symmetric(x, 4, bound)[2], edges) for bound in candidates]
best_kl = candidates[np.argmin(scores)]
print('rango KL aproximado:', round(best_kl, 3), 'KL:', round(min(scores), 4))Changing the number of bins or smoothing changes the criterion and may change the chosen range. Histogram KL is not directly model loss or necessarily the best metric for a task.
For granularity, cost depends on shape and whether groups align with rows. This example builds four channels with different magnitudes, quantizes each group independently and counts one 16-bit scale per group. It includes incomplete final groups: a real format can also add padding so kernels read aligned blocks.
rng = np.random.default_rng(22)
matrix = rng.normal(size=(4, 64))*np.array([.1, .4, 1., 2.])[:, None]
def reconstruct_groups(matrix, bits, group):
result = np.empty_like(matrix)
scales = []
for i, row in enumerate(matrix):
for start in range(0, row.size, group):
part = row[start:start+group]
bound = np.max(np.abs(part))
if bound == 0:
result[i, start:start+group] = 0
scales.append(1.)
else:
_, scale, rec = symmetric(part, bits, bound)
result[i, start:start+group] = rec
scales.append(scale)
return result, np.array(scales)
_, scale_tensor, rec_tensor = symmetric(matrix, 4, np.max(np.abs(matrix)))
print('tensor MSE:', round(np.mean((matrix-rec_tensor)**2), 6), 'bits/peso:', 4+16/matrix.size)
for group in (64, 16):
rec, scales = reconstruct_groups(matrix, 4, group)
print('grupo', group, 'MSE:', round(np.mean((matrix-rec)**2), 6),
'bits/peso:', 4+16*len(scales)/matrix.size)With one scale per row, the group has 64 values in this matrix. In this run the four magnitudes fit better separately than with a global scale; the result belongs to this sample. Reducing group size does not guarantee an improvement in a downstream metric, although it gives more freedom to fit the grid to the local range.
Integer matmul and accumulation
With one activation scale per tensor and one per weight row, the centered integer product is calculated before applying scales. Expanding allows sum terms to be precomputed to reduce work, while respecting dimensions and sign. The next cell uses INT64 to check that the sum fits in INT32 before conversion. The reconstructed product is compared with multiplication of the already quantized tensors, not the original values.
X = np.array([[0.1, -0.4, 0.8], [-0.2, 0.3, 0.5]])
W = np.array([[0.2, -0.1, 0.6], [-0.7, 0.2, 0.1]])
qx, sx, zx, xr = affine(X, -1, 1)
weight_codes, scales, weight_rec = [], [], []
for row in W:
q, s, rec = symmetric(row, 8, np.max(np.abs(row)))
weight_codes.append(q)
scales.append(s)
weight_rec.append(rec)
qw = np.asarray(weight_codes, dtype=np.int32)
wide = (qx.astype(np.int64)-zx) @ qw.astype(np.int64).T
assert np.max(np.abs(wide)) <= np.iinfo(np.int32).max
acc = wide.astype(np.int32)
y = acc.astype(float)*sx*np.asarray(scales)[None,:]
reference = xr @ np.asarray(weight_rec).T
assert np.allclose(y, reference)
qy, sy, zy, yr = affine(y, -2, 2)
print('acumulador INT32:', acc.tolist())
print('producto descuantizado:', np.round(y, 5))
print('salida recuantizada:', qy.tolist(), 'reconstrucción:', np.round(yr, 5))A fast implementation does not convert each operation individually in Python: it uses instructions and kernels that fuse reading, multiplication and scaling. The centered integer may need more bits than the original integer; a conservative bound is . If it exceeds the accumulator’s maximum there is no guarantee against overflow.
Lab: a small MLP and data separation
Train a two-layer classifier on a known synthetic distribution and compare accuracy before and after quantizing its weights. The seed, split and rule are shown in full. Evaluation measures accuracy on unseen examples from the same generator, not LLM perplexity or quality. This result is not extrapolated to another model.
rng = np.random.default_rng(43)
features = rng.normal(size=(800, 2))
labels = ((features[:,0]**2 + features[:,1]**2) > 1.2).astype(float)[:,None]
train_x, test_x = features[:600], features[600:]
train_y, test_y = labels[:600], labels[600:]
W1 = rng.normal(0, .5, size=(2, 16)); b1 = np.zeros((1,16))
W2 = rng.normal(0, .5, size=(16, 1)); b2 = np.zeros((1,1))
def forward(x, w1, b1, w2, b2):
hidden = np.tanh(x@w1+b1)
logits = np.clip(hidden@w2+b2, -30, 30)
return hidden, 1/(1+np.exp(-logits))
for _ in range(400):
h, p = forward(train_x, W1, b1, W2, b2)
dz = (p-train_y)/len(train_x)
gW2 = h.T@dz; gb2 = dz.sum(axis=0, keepdims=True)
dh = ([email protected])*(1-h*h)
gW1 = train_x.T@dh; gb1 = dh.sum(axis=0, keepdims=True)
W1 -= .2*gW1; b1 -= .2*gb1; W2 -= .2*gW2; b2 -= .2*gb2
def accuracy(w1, w2):
return np.mean((forward(test_x,w1,b1,w2,b2)[1] >= .5) == test_y)
print('sin cuantizar:', round(accuracy(W1,W2), 3))
for bits in (2, 3, 4, 8):
w1 = symmetric(W1, bits, np.max(np.abs(W1)))[2]
w2 = symmetric(W2, bits, np.max(np.abs(W2)))[2]
print(bits, 'bits:', round(accuracy(w1,w2), 3))This test keeps biases and activations in floating-point precision. Differences between precisions can vary with seed and distribution. To select a configuration, reserve a validation set separate from test and do not choose the best variant by repeatedly looking at the test set.
Local lab: packed weights from a real model
This lab uses SmolLM2-135M and the test split of WikiText-2 raw. It requires PyTorch, Transformers and Datasets, and downloads the model and dataset if uncached. Both revisions are pinned. For a short check, 1016 tokens are scored in eight independent windows of 128 tokens; the first token of each window is not scored. This is not benchmark perplexity over the entire test set and does not use sliding context. Set MAX_TOKENS to None to traverse complete windows of the entire split, and specify the protocol before comparing with other work.
Internal linear layers are replaced by a teaching implementation with groups of 128, FP16 scale and INT8 weights or two four-bit codes per byte. The head and embeddings retain their original precision. Each call unpacks weights to floating point: it is not a fused INT4 kernel and can be slower than the original model. Persistent memory counts tensors and buffers without double-counting shared storage; peak CUDA includes temporaries during measurement. Time includes cached generation, with prior warmup and CUDA synchronization. Since hardware may be shared, repeat several times and report the distribution of times; do not treat one pass as a GPU property.
import time, math, gc
import torch
from torch import nn
from torch.nn import functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer
from datasets import load_dataset
torch.set_num_threads(4)
MODEL = 'HuggingFaceTB/SmolLM2-135M'
REV = '93efa2f097d58c2a74874c7e644dbc9b0cee75a2'
MAX_TOKENS = 1024 # None: todas las ventanas completas del test
device = 'cuda' if torch.cuda.is_available() else 'cpu'
dtype = torch.bfloat16 if device == 'cuda' and torch.cuda.is_bf16_supported() else torch.float32
tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=REV)
test = load_dataset('Salesforce/wikitext', 'wikitext-2-raw-v1', split='test', revision='b08601e04326c79dfdd32d625aee71d232d685c3')
text = chr(10).join(row['text'] for row in test if row['text'].strip())
tokens = tokenizer(text, return_tensors='pt', truncation=MAX_TOKENS is not None, max_length=MAX_TOKENS).input_ids[0]
prompt = tokenizer('Explain how quantization changes neural network inference:', return_tensors='pt').input_ids.to(device)
class PackedLinear(nn.Module):
def __init__(self, layer, bits=4, group=128):
super().__init__()
assert bits in (4, 8) and group % 2 == 0
self.bits, self.group = bits, group
self.rows, self.cols = layer.weight.shape
groups = math.ceil(self.cols/group)
w = F.pad(layer.weight.detach().float(), (0, groups*group-self.cols)).reshape(self.rows, groups, group)
Q = 2**(bits-1)-1
scale = w.abs().amax(dim=-1).clamp_min(1e-8)/Q
q = (w/scale[...,None]).round().clamp(-Q,Q).to(torch.int8)
self.register_buffer('scale', scale.to(torch.float16))
if bits == 4:
u = (q.to(torch.int16)+7).to(torch.uint8)
packed = u[...,0::2] | (u[...,1::2] << 4)
else:
packed = q
self.register_buffer('packed', packed)
self.register_buffer('bias', layer.bias.detach().clone() if layer.bias is not None else None)
def forward(self, x):
if self.bits == 4:
u = self.packed
q = torch.stack(((u & 15).to(torch.int16)-7, (u >> 4).to(torch.int16)-7), dim=-1).flatten(-2)
else:
q = self.packed
w = (q.to(x.dtype)*self.scale.to(x.dtype)[...,None]).reshape(self.rows,-1)[:,:self.cols]
return F.linear(x, w, self.bias)
def replace_linears(module, bits):
for name, child in list(module.named_children()):
if isinstance(child, nn.Linear):
setattr(module, name, PackedLinear(child, bits))
else:
replace_linears(child, bits)
def test_packing():
torch.manual_seed(31)
layer = nn.Linear(131, 3)
for bits in (4, 8):
packed = PackedLinear(layer, bits)
w = F.pad(layer.weight.detach().float(), (0, 125)).reshape(3, 2, 128)
Q = 2**(bits-1)-1
scales = w.abs().amax(dim=-1).clamp_min(1e-8)/Q
expected = (w/scales[...,None]).round().clamp(-Q,Q).to(torch.int16)
if bits == 4:
u = packed.packed
actual = torch.stack(((u & 15).to(torch.int16)-7, (u >> 4).to(torch.int16)-7), dim=-1).flatten(-2)
else:
actual = packed.packed.to(torch.int16)
assert torch.equal(expected, actual)
print('empaquetado verificado, incluido grupo final incompleto')
def persistent_bytes(model):
seen, total = set(), 0
for tensor in list(model.parameters()) + list(model.buffers()):
storage = tensor.untyped_storage()
ptr = storage.data_ptr()
if ptr not in seen:
seen.add(ptr)
total += storage.nbytes()
return total
@torch.inference_mode()
def perplexity(model):
loss, count = 0., 0
for start in range(0, len(tokens)-128+1, 128):
ids = tokens[start:start+128].unsqueeze(0).to(device)
logits = model(ids, use_cache=False).logits[:, :-1].float()
loss += F.cross_entropy(logits.reshape(-1, logits.shape[-1]), ids[:,1:].reshape(-1), reduction='sum').item()
count += 127
return math.exp(loss/count), count
@torch.inference_mode()
def speed(model):
model.generate(prompt, max_new_tokens=3, do_sample=False, pad_token_id=tokenizer.eos_token_id)
if device == 'cuda': torch.cuda.synchronize()
start = time.perf_counter()
output = model.generate(prompt, max_new_tokens=32, do_sample=False, pad_token_id=tokenizer.eos_token_id)
if device == 'cuda': torch.cuda.synchronize()
return (output.shape[1]-prompt.shape[1])/(time.perf_counter()-start)
test_packing()
for bits in (None, 8, 4):
model = AutoModelForCausalLM.from_pretrained(MODEL, revision=REV, dtype=dtype).eval()
if bits is not None:
replace_linears(model.model.layers, bits)
model.to(device)
if device == 'cuda': torch.cuda.reset_peak_memory_stats()
ppl, scored = perplexity(model)
rate = speed(model)
peak = torch.cuda.max_memory_allocated() if device == 'cuda' else 0
print('bits', bits, 'device', device, 'dtype', dtype, 'persistent_bytes', persistent_bytes(model),
'peak_allocated', peak, 'scored_tokens', scored, 'ppl', round(ppl,4), 'tokens_per_s', round(rate,3))
del model
gc.collect()
if device == 'cuda': torch.cuda.empty_cache()npm run lab and open the connection link.The experiment keeps floating-point activations and quantizes weights by group. It does not measure W8A8. The next optional test checks native INT8 matmul if the PyTorch version and hardware expose it. It is an example of centered integers without scales, not the kernel from the previous class. The underscore name indicates an internal interface that can change: if it fails, this is reported and execution continues. Compare input codes, scales and results before measuring an optimized library. A fast integer operation and compact representation are distinct properties.
if device == 'cuda' and hasattr(torch, '_int_mm'):
a = torch.randint(-128, 128, (64, 128), dtype=torch.int8, device=device)
b = torch.randint(-128, 128, (128, 64), dtype=torch.int8, device=device)
try:
c = torch._int_mm(a, b)
expected = a.cpu().to(torch.int32) @ b.cpu().to(torch.int32)
assert torch.equal(c.cpu(), expected)
print('INT8 nativa: igual al producto INT32 de referencia; forma', tuple(c.shape))
except RuntimeError as exc:
print('INT8 nativa no disponible para esta configuración:', str(exc)[:200])
else:
print('INT8 nativa no disponible en este dispositivo o versión')npm run lab and open the connection link.In a short run on RTX 3060 with BF16, using this model and protocol, recorded persistent memory was 269030272 bytes unquantized, 173506432 with 8 bits and 115998592 with 4 bits. Perplexity over the 1016 scored tokens was 36.0877, 36.2329 and 58.9927 respectively. This is a small sample and simple quantizer, not a complete method comparison or precise estimate of general quality. The teaching decompression was slower than BF16 in that run; time depends on the GPU’s shared state and is not presented as a stable benchmark. Uncompressed embeddings and head explain part of the difference between the total memory reduction factor and the internal weight reduction factor.
Exercises
Step 1 of 3. What is the mean?
quantize_per_group(w, bits, group) and dequantize(q, scales, group). Use contiguous groups, symmetric range [-Q,Q], Q = 2^(bits-1)-1, maximum absolute scale per group and 1 for zero groups.import numpy as np
def quantize_per_group(w, bits, group):
pass
def dequantize(q, scales, group):
pass