llm.quantization — Model Quantization¶
Post-training quantization (PTQ), GPTQ, and AWQ support for reducing
model size and inference latency. The CLI entry point is llm-quantize.
Overview¶
| Method | Description |
|---|---|
| GPTQ | Greedy row-wise pruning with second-order information |
| AWQ | Activation-aware per-channel scales with grid search |
| SmoothQuant | INT8 weights + activations with activation smoothing |
| Mixed-Precision | Per-layer quantization dispatch via LayerQuantPolicy |
SmoothQuant¶
smooth
¶
SmoothQuant (Xiao et al., ICML 2023) post-training quantization.
SmoothQuant makes INT8 weight+activation quantization tractable for LLMs by
migrating the quantization difficulty from activations to weights: per-input-
channel smoothing factors s_j = act_max[j]**alpha / w_max[j]**(1-alpha)
are folded into the weights (W·s), and the input is divided by s
before its per-tensor INT8 fake quantization.
This module mirrors the GPTQ / AWQ paths: a frozen config, a stateful per-layer quantizer, and model-level entry points that capture per-layer calibration activations through forward hooks.
SmoothQuantConfig
dataclass
¶
Configuration for SmoothQuant quantization.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
alpha |
float
|
Smoothing strength in [0, 1]. alpha=0 pushes all quantization difficulty onto activations (weights normalized), alpha=1 pushes it onto weights (activations normalized); the paper's default is 0.5 (balanced). |
search_alpha |
bool
|
If True, grid-search alpha per layer over {0.25, 0.5, 0.75, 1.0} using the calibration activations, picking the value with the lowest output reconstruction error. Requires retaining the calibration batches (more memory). |
bits |
int
|
Weight bit width. SmoothQuant is an INT8 method in v1 — only 8 is accepted; sub-8-bit weight variants are a follow-up. |
group_size |
int
|
Always -1 (per-channel) in v1 — SmoothQuant weights are
quantized per output row by design. Present only so
|
sym |
bool
|
If True, symmetric quantization (no zero-point). Asymmetric SmoothQuant is not yet implemented. |
act_order |
bool
|
Accepted for |
layer_policies |
tuple[LayerQuantPolicy, ...]
|
Atomic per-layer override policies. For v1 the only
meaningful overrides are |
源代码位于: src/llm/quantization/smooth.py
SmoothQuantQuantizer
¶
Stateful per-layer SmoothQuant processor.
Lifecycle
q = SmoothQuantQuantizer(layer, config) for batch in calib_iter_for_this_layer: q.add_batch(batch) components = q.quantize() # uses config.alpha or searches alpha
源代码位于: src/llm/quantization/smooth.py
add_batch
¶
Accumulate per-channel max abs activation (and optionally batches).
源代码位于: src/llm/quantization/smooth.py
quantize
¶
Quantize the layer; returns the packed component tuple.
源代码位于: src/llm/quantization/smooth.py
quantize_model_smoothquant
¶
Quantize a model with SmoothQuant (INT8 weights + activations).
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
Module
|
nn.Module containing nn.Linear layers to quantize. |
必需 |
calib_iter
|
Iterator[Tensor]
|
Iterator yielding input tensors for the model forward pass. |
必需 |
config
|
SmoothQuantConfig | None
|
SmoothQuantConfig (default: alpha=0.5, INT8 symmetric). |
None
|
target_modules
|
Iterable[str] | None
|
Iterable of fully-qualified layer names to quantize. If None, all nn.Linear layers are quantized. |
None
|
device
|
device | str | None
|
Device to run calibration on (default: model's device). |
None
|
返回:
| 类型 | 描述 |
|---|---|
Module
|
The model with nn.Linear layers replaced by SmoothQuantLinear. |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
If model has no nn.Linear, target_modules unmatched, layer already quantized, calibration empty, or a layer policy targets an unsupported override. |
源代码位于: src/llm/quantization/smooth.py
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | |
quantize_model_smoothquant_with_collector
¶
quantize_model_smoothquant_with_collector(model, collector, n_samples, config=None, target_modules=None, device=None)
Quantize a model using an existing calibration batch source.
Mirrors quantize_model_with_collector / quantize_model_awq_with_collector:
materializes up to n_samples batches, then funnels them into
quantize_model_smoothquant.
源代码位于: src/llm/quantization/smooth.py
AWQ¶
awq
¶
AWQ (Lin et al., MLSys 2024) post-training quantization.
Activation-aware Weight Quantization protects the ~1% of weight channels
that dominate quantization error: per-input-channel scales s are
searched over a power-of-two grid to minimize the activation-weighted
reconstruction error of the layer output, then the layer is group-quantized
from W·s with the scale compensation x/s applied at forward time.
This module mirrors the GPTQ path in gptq.py: a frozen config, a
stateful per-layer quantizer, and model-level entry points that capture
per-layer calibration activations through forward hooks.
AWQConfig
dataclass
¶
Configuration for AWQ quantization.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
bits |
int
|
Quantization bit width (4 or 8). |
group_size |
int
|
Quantization group size along input dim. -1 means per-channel (one scale per output row). |
sym |
bool
|
If True, symmetric quantization (no zero-point). Asymmetric AWQ (zero points) is not yet implemented. |
n_grid |
int
|
Number of power-of-two scale candidates in the grid search,
centered on 1 (ratios |
clip_ratio |
float | None
|
Optional weight clipping ratio in (0, 0.5]. When set,
each layer's weights are clipped to
|
layer_policies |
tuple[LayerQuantPolicy, ...]
|
Atomic per-layer override policies (algorithm-agnostic
|
源代码位于: src/llm/quantization/awq.py
AWQQuantizer
¶
Stateful per-layer AWQ processor.
Lifecycle
q = AWQQuantizer(layer, config) for batch in calib_iter_for_this_layer: q.add_batch(batch) scale = q.search_scale() # per-input-channel AWQ scale packed, scales, effective_group_size = q.quantize(scale)
源代码位于: src/llm/quantization/awq.py
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
add_batch
¶
Accumulate per-input-channel absolute activation sums.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
Tensor
|
Input activations to |
必需 |
源代码位于: src/llm/quantization/awq.py
act_mean
¶
Mean absolute activation per input channel [in_features].
源代码位于: src/llm/quantization/awq.py
search_scale
¶
Run the activation-aware grid search; returns per-channel scale [in_f].
源代码位于: src/llm/quantization/awq.py
quantize
¶
Quantize W·scale into packed storage.
返回:
| 名称 | 类型 | 描述 |
|---|---|---|
weight_packed |
Tensor
|
int8 packed weights. |
scales |
Tensor
|
per-group (or per-channel) fp32 scales. |
effective_group_size |
int
|
group size actually used for packing
(never larger than |
源代码位于: src/llm/quantization/awq.py
quantize_model_awq
¶
Quantize a model with AWQ.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
Module
|
nn.Module containing nn.Linear layers to quantize. |
必需 |
calib_iter
|
Iterator[Tensor]
|
Iterator yielding input tensors for the model forward pass. |
必需 |
config
|
AWQConfig | None
|
AWQConfig (default: 4-bit, group_size=128, symmetric, n_grid=20). |
None
|
target_modules
|
Iterable[str] | None
|
Iterable of fully-qualified layer names to quantize. If None, all nn.Linear layers are quantized. |
None
|
device
|
device | str | None
|
Device to run calibration on (default: model's device). |
None
|
返回:
| 类型 | 描述 |
|---|---|
Module
|
The model with nn.Linear layers replaced by AWQQuantizedLinear. |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
If model has no nn.Linear, target_modules unmatched, layer already quantized, or calibration is empty. |
源代码位于: src/llm/quantization/awq.py
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 | |
quantize_model_awq_with_collector
¶
quantize_model_awq_with_collector(model, collector, n_samples, config=None, target_modules=None, device=None)
Quantize a model using an existing calibration batch source.
Trainer-loop entry point mirroring quantize_model_with_collector:
materializes up to n_samples batches, then funnels them into
quantize_model_awq.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
Module
|
nn.Module to quantize. |
必需 |
collector
|
CalibrationDataCollector | Iterable[Tensor]
|
Iterable yielding Tensor batches. Up to |
必需 |
n_samples
|
int
|
Maximum number of batches to use for calibration. |
必需 |
config
|
AWQConfig | None
|
AWQConfig (default: 4-bit, group_size=128, symmetric). |
None
|
target_modules
|
Iterable[str] | None
|
Optional layer-name filter forwarded to
|
None
|
device
|
device | str | None
|
Target device forwarded to |
None
|
返回:
| 类型 | 描述 |
|---|---|
Module
|
The quantized model (same instance as |
源代码位于: src/llm/quantization/awq.py
GPTQ¶
gptq
¶
GPTQ (Frantar et al. 2022) post-training quantization.
Provides 4-bit / 8-bit Hessian-aware quantization orthogonal to
the simple-PTQ path in ptq.py.
GPTQConfig
dataclass
¶
Configuration for GPTQ quantization.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
bits |
int
|
Quantization bit width (4 or 8). |
group_size |
int
|
Quantization group size along input dim. -1 means per-channel (one scale per output row). Positive integer g means one scale per g consecutive input cols. |
sym |
bool
|
If True, symmetric quantization (no zero-point). |
percdamp |
float
|
Hessian damping as a fraction of mean(diag(H)). Prevents numerical issues when H is near-singular. |
blocksize |
int
|
Number of weight columns processed per Cholesky block. Larger = faster but more memory. Must be divisible by group_size when group_size > 0. |
act_order |
bool
|
If True, sort weight columns by diag(H) descending before quantization. Improves accuracy at slight cost. |
static_groups |
bool
|
If True, compute group partitions once and reuse across all layers. Faster, slight accuracy loss. |
layer_policies |
tuple[LayerQuantPolicy, ...]
|
Atomic per-layer override policies (algorithm-agnostic LayerQuantPolicy tuples). Empty tuple (default) → all layers use the base config; otherwise each policy dispatches its overrides to its target_modules subset. See ADR-008 and docs/superpowers/specs/2026-07-22-mixed-precision-quantization-design.md. |
源代码位于: src/llm/quantization/gptq.py
GPTQQuantizer
¶
Stateful per-layer GPTQ processor.
Lifecycle
q = GPTQQuantizer(layer, config) for batch in calib_iter_for_this_layer: q.add_batch(batch) W_packed, scales, zeros = q.quantize()
源代码位于: src/llm/quantization/gptq.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | |
add_batch
¶
Accumulate Hessian contribution from a calibration batch.
Maintains the invariant H == (2 / N_total) · Σ X_b^T X_b so that multiple mini-batches produce the same H as a single concatenated add_batch (Frantar 2022, eq. 3). Uses the canonical EMA-style rescale: H_new = (N_old / N_new) · H_old + (2 / N_new) · X^T X.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
Tensor
|
Input activations to |
必需 |
源代码位于: src/llm/quantization/gptq.py
quantize
¶
Run GPTQ on accumulated Hessian.
返回:
| 名称 | 类型 | 描述 |
|---|---|---|
W_q |
Tensor
|
Quantized weights (integer-valued, stored as fp32),
shape [out_features, in_features]. Multiply by |
scales |
Tensor
|
Per-row scale if group_size=-1 [out_features, 1], else per-group scale [out_features, in_features // group_size]. |
zeros |
Tensor | None
|
Per-group zero-points, or None (symmetric only in v1). |
引发:
| 类型 | 描述 |
|---|---|
RuntimeError
|
If calibration is empty or Hessian is ill-conditioned (rank-deficient with insufficient damping). |
源代码位于: src/llm/quantization/gptq.py
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | |
quantize_model_gptq
¶
Quantize a model with GPTQ.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
Module
|
nn.Module containing nn.Linear layers to quantize. |
必需 |
calib_iter
|
Iterator[Tensor]
|
Iterator yielding input tensors for the model forward pass. |
必需 |
config
|
GPTQConfig | None
|
GPTQConfig (default: 4-bit, group_size=128, symmetric). |
None
|
target_modules
|
Iterable[str] | None
|
Iterable of fully-qualified layer names to quantize. If None, all nn.Linear layers are quantized. |
None
|
device
|
device | str | None
|
Device to run calibration on (default: model's device). |
None
|
返回:
| 类型 | 描述 |
|---|---|
Module
|
The model with nn.Linear layers replaced by GPTQQuantizedLinear. |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
If model has no nn.Linear, target_modules unmatched, or layer already quantized. |
源代码位于: src/llm/quantization/gptq.py
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 | |
quantize_model_with_collector
¶
quantize_model_with_collector(model, collector, n_samples, config=None, target_modules=None, device=None)
Quantize a model using an existing CalibrationDataCollector.
Trainer-loop entry point: reuse the same calibration batches already
collected during training (e.g. for activation stats). Materializes
up to n_samples batches, then funnels into quantize_model_gptq.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
Module
|
nn.Module to quantize. |
必需 |
collector
|
CalibrationDataCollector | Iterable[Tensor]
|
CalibrationDataCollector (or any iterable yielding Tensor
batches). Up to |
必需 |
n_samples
|
int
|
Maximum number of batches to use for calibration. |
必需 |
config
|
GPTQConfig | None
|
GPTQConfig (default: 4-bit, group_size=128, symmetric). |
None
|
target_modules
|
Iterable[str] | None
|
Optional layer-name filter forwarded to
|
None
|
device
|
device | str | None
|
Target device forwarded to |
None
|
返回:
| 类型 | 描述 |
|---|---|
Module
|
The quantized model (same instance as |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
Forwarded from |
源代码位于: src/llm/quantization/gptq.py
Calibration¶
calibration
¶
Calibration for Quantization.
Collects activation statistics for quantization scale computation.
ActivationStats
dataclass
¶
Statistics for a single layer's activations.
源代码位于: src/llm/quantization/calibration.py
update
¶
Update statistics with new tensor.
源代码位于: src/llm/quantization/calibration.py
compute_scale
¶
Compute quantization scale.
源代码位于: src/llm/quantization/calibration.py
CalibrationDataCollector
¶
Collects activation statistics for quantization calibration.
Hooks into model forward passes to record min/max/mean/std of activations at each layer.
源代码位于: src/llm/quantization/calibration.py
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | |
register_hooks
¶
Register forward hooks on specified layer types.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
layer_types
|
tuple
|
Tuple of layer types to hook. |
(Linear,)
|
源代码位于: src/llm/quantization/calibration.py
collect
¶
Collect activation statistics from calibration data.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
dataloader
|
DataLoader
|
Calibration data loader. |
必需 |
num_batches
|
int | None
|
Maximum number of batches to process. |
None
|
device
|
str | device
|
Device to run on. |
'cuda'
|
返回:
| 类型 | 描述 |
|---|---|
dict[str, ActivationStats]
|
Dictionary of layer name to activation stats. |
源代码位于: src/llm/quantization/calibration.py
remove_hooks
¶
get_scales
¶
Compute quantization scales for all layers.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
bits
|
int
|
Quantization bit width. |
8
|
symmetric
|
bool
|
Whether to use symmetric quantization. |
True
|
返回:
| 类型 | 描述 |
|---|---|
dict[str, float]
|
Dictionary of layer name to scale. |
源代码位于: src/llm/quantization/calibration.py
Policies¶
_policy
¶
Per-layer quantization policy — algorithm-agnostic.
LayerQuantPolicy binds a set of target layer names to a bundle of override fields (bits / group_size / sym / act_order). All override fields are optional; None means "inherit from the algorithm's base config".
This module is intentionally algorithm-agnostic: the four override fields
are the public subset shared by all PTQ-style quantization algorithms
(GPTQ today, AWQ / SmoothQuant / QAT in future slices). The
resolve_layer_policies helper is generic over the base config dataclass,
so future algorithms reuse it without modification.
See ADR-008 and docs/superpowers/specs/2026-07-22-mixed-precision-quantization-design.md.
LayerQuantPolicy
dataclass
¶
Atomic per-layer quantization override policy. Algorithm-agnostic.
A LayerQuantPolicy binds a set of target layer names to a bundle of override fields. Fields set to None mean "inherit from the algorithm's base config". Multiple LayerQuantPolicy in a config are additive; each target module must appear in at most one policy (overlap raises ValueError at resolve time).
Field semantics are universal across PTQ-style algorithms
bits: 4 or 8 — quantization bit-width group_size: -1 (per-channel) or positive int — quantization group size sym: True (symmetric) or False (asymmetric) act_order: True (sort columns by diag(H) descending) or False
The last three fields are the FP8 knobs (RIL TASK-203). FP8's knobs are
NOT expressible in the shared fields above (an FP8 layer has no bits /
group_size / symmetry in the int-quant sense), so the policy model is
extended instead of abusing bits:
weight_dtype: "e4m3" (E4M3FN, default) or "e5m2" — the FP8 format
per_channel: True (per-output-row weight scale) or False (per-tensor)
activation: "static" (calibration-captured per-layer scale) or
"dynamic" (per-forward absmax, no calibration)
resolve_layer_policies applies ONLY the override fields the target
algorithm's base config actually has; an FP8 field on an int algorithm
(or an int field on FP8) is rejected loudly rather than silently dropped.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
target_modules |
tuple[str, ...]
|
Tuple of fully-qualified layer names (dotted notation,
matching the |
bits |
int | None
|
Override bit-width (None = inherit). |
group_size |
int | None
|
Override group size (None = inherit). |
sym |
bool | None
|
Override symmetry (None = inherit). |
act_order |
bool | None
|
Override act-order (None = inherit). |
weight_dtype |
str | None
|
Override FP8 format (None = inherit). |
per_channel |
bool | None
|
Override FP8 weight-scale granularity (None = inherit). |
activation |
str | None
|
Override FP8 activation mode (None = inherit). |
源代码位于: src/llm/quantization/_policy.py
resolve_layer_policies
¶
Build layer-name -> effective config map from policies.
Generic over the base config type (T). Works for GPTQConfig and AWQ /
SmoothQuantConfig today, and for Fp8Config since TASK-203 extended
LayerQuantPolicy with the FP8 knobs. Each override field is applied only
when the base config dataclass actually has that field — an FP8 override
on an int algorithm (or an int override on FP8) is rejected with a clear
error instead of crashing deep in dataclasses.replace or being
silently dropped.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
policies
|
tuple[LayerQuantPolicy, ...]
|
Tuple of LayerQuantPolicy to resolve. Empty tuple is a no-op. |
必需 |
available_names
|
set[str]
|
Set of layer names that are actually eligible to be
quantized (typically the post- |
必需 |
base_config
|
T
|
The base algorithm config to inherit from. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
dict[str, T]
|
Dict mapping each policy-targeted layer name to its effective config |
dict[str, T]
|
(= base_config with non-None policy fields applied via |
dict[str, T]
|
|
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
If any policy targets a name not in |
源代码位于: src/llm/quantization/_policy.py
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | |
PTQ¶
ptq
¶
Post-Training Quantization (PTQ).
Provides utilities for quantizing models after training.
Supports symmetric (scale-only) and asymmetric (scale + zero-point) 8-bit
weight quantization, per-tensor or per-channel. The asymmetric path stores
q - 128 in the int8 buffer and folds the offset into weight_zero_point
so dequantization stays (q - zp) * scale; it is exact on the grid and beats
symmetric on skewed (all-positive / all-negative) weight distributions.
QuantConfig
dataclass
¶
Configuration for quantization.
源代码位于: src/llm/quantization/ptq.py
QuantizedLinear
¶
Bases: Module
Quantized Linear layer with INT8/INT4 weights.
Stores quantized weights and scales, dequantizes during forward.
源代码位于: src/llm/quantization/ptq.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
forward
¶
Forward pass with dequantized weights.
Dequantizes to fp32, computes in fp32 for accuracy, and returns in
the layer's effective dtype (native nn.Linear semantics). This
keeps the layer a faithful drop-in even after the model is cast to
fp16/bf16 — the serving engine's model.to(device, dtype=fp16) or
selective quantization over a half base converts bias to half,
and passing it straight into F.linear against fp32 weights
crashed with a dtype mismatch (RIL TASK-196 / ISS-236, quant
deep-dive F1; same fix as the GPTQ/AWQ/SmoothQuant layers in
ISS-191).
源代码位于: src/llm/quantization/ptq.py
from_linear
classmethod
¶
Create QuantizedLinear from a regular Linear layer.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
linear
|
Linear
|
Source Linear layer. |
必需 |
config
|
QuantConfig | None
|
Quantization configuration. |
None
|
scale
|
float | Tensor | None
|
Pre-computed scale (optional). |
None
|
返回:
| 类型 | 描述 |
|---|---|
QuantizedLinear
|
Quantized layer. |
源代码位于: src/llm/quantization/ptq.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
quantize_linear_layer
¶
Quantize a single Linear layer.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
layer
|
Linear
|
Linear layer to quantize. |
必需 |
config
|
QuantConfig | None
|
Quantization configuration. |
None
|
scale
|
float | Tensor | None
|
Pre-computed scale. |
None
|
返回:
| 类型 | 描述 |
|---|---|
QuantizedLinear
|
Quantized layer. |
源代码位于: src/llm/quantization/ptq.py
quantize_model
¶
Quantize all Linear layers in a model.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
Module
|
Model to quantize. |
必需 |
config
|
QuantConfig | None
|
Quantization configuration. |
None
|
scales
|
dict[str, float] | None
|
Pre-computed scales per layer name. |
None
|
inplace
|
bool
|
Whether to modify model in-place. |
False
|
返回:
| 类型 | 描述 |
|---|---|
Module
|
Quantized model. |
源代码位于: src/llm/quantization/ptq.py
compute_model_size
¶
Compute model size statistics.
Recognizes all quantized layer flavors in the library:
:class:QuantizedLinear (simple PTQ), and the GPTQ / AWQ / SmoothQuant /
FP8 layers (:class:~llm.quantization._gptq_layer.GPTQQuantizedLinear,
:class:~llm.quantization._awq_layer.AWQQuantizedLinear,
:class:~llm.quantization._smooth_layer.SmoothQuantLinear,
:class:~llm.quantization._fp8_layer.Fp8QuantizedLinear). Those replace
nn.Linear entirely, so without explicit handling a
GPTQ/AWQ/Smooth/FP8-quantized model reported zero parameters and zero bytes.
total_params counts true weights: for 4-bit GPTQ/AWQ layers each
packed int8 byte stores two int4 weights, so total_params is the
unpacked weight count while total_bytes is the actual (packed) on-disk
size. Use total_params for parameter counts and total_bytes /
size_mb for footprint.
返回:
| 类型 | 描述 |
|---|---|
dict[str, Any]
|
Dictionary with size information. |
源代码位于: src/llm/quantization/ptq.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 | |
GPTQ Layer¶
_gptq_layer
¶
GPTQQuantizedLinear: GPTQ-quantized Linear with packed 4-bit (or 8-bit) storage.
Storage convention for bits=4: - weight_packed: int8 tensor, two int4 values per byte. Pair (w[2i], w[2i+1]) packed as (w[2i] << 4) | (w[2i+1] & 0x0F). - scales: float16 tensor, shape [out_features, in_features // group_size]. - zeros: int8 tensor (or None if sym=True), shape [out_features, in_features // group_size]. - group_size=-1: scales shape [out_features, 1] (per-channel).
GPTQQuantizedLinear
¶
Bases: Module
GPTQ-quantized Linear with packed 4-bit (or 8-bit) weight storage.
源代码位于: src/llm/quantization/_gptq_layer.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
forward
¶
Forward pass with dequantized weights.
Dequantizes to fp32 and computes the matmul in fp32 for accuracy,
then returns in the input's dtype — native nn.Linear semantics,
keeping the layer a faithful drop-in replacement even after the
model is cast to fp16/bf16 (serving default) or selectively
quantized over a half base (RIL ISS-191). Asymmetric quantization
(sym=False) is not yet implemented — raises NotImplementedError.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
Tensor
|
Input tensor of shape [..., in_features]. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Tensor
|
Output tensor of shape [..., out_features]. |
引发:
| 类型 | 描述 |
|---|---|
NotImplementedError
|
If |
源代码位于: src/llm/quantization/_gptq_layer.py
AWQ Layer¶
_awq_layer
¶
AWQQuantizedLinear: activation-aware quantized Linear with packed storage.
Storage convention mirrors :class:GPTQQuantizedLinear (symmetric INT4/INT8
group quantization with per-group scales), plus one AWQ-specific buffer:
input_scales: per-input-channel scaling factorssof shape[in_features](fp16). The layer was quantized fromW * sand compensates at forward time by dividing the input:y = Q(W·s)·(x/s).
Keeping the compensation in the layer (rather than folding it into the preceding layer) is exact and needs no graph analysis; cross-layer folding is a follow-up optimization (see ADR-009).
AWQQuantizedLinear
¶
Bases: Module
Activation-aware weight-quantized Linear (symmetric group quantization).
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
in_features |
/ out_features
|
linear geometry. |
bits |
4 or 8. |
|
group_size |
-1 (per-channel) or positive int (per-group). |
|
sym |
must be True (asymmetric AWQ is a follow-up). |
|
input_scales |
per-input-channel AWQ scale |
源代码位于: src/llm/quantization/_awq_layer.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
forward
¶
Forward pass: Q(W·s)·(x/s) with exact AWQ scale compensation.
Computes the matmul in fp32 for accuracy, then returns in the input's
dtype — native nn.Linear semantics — so post-quant fp16/bf16
casts (serving engine default, or selective quantization over a half
base) don't mix dtypes inside F.linear or emit fp32 into
half-precision residual linears (RIL ISS-191). An fp32 model is
unchanged.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
Tensor
|
Input tensor of shape [..., in_features]. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Tensor
|
Output tensor of shape [..., out_features]. |
引发:
| 类型 | 描述 |
|---|---|
NotImplementedError
|
If |
源代码位于: src/llm/quantization/_awq_layer.py
SmoothQuant Layer¶
_smooth_layer
¶
SmoothQuantLinear: weight+activation INT8 Linear with activation smoothing.
Storage convention:
- weight_packed: int8 weights, shape [out_features * in_features]
(SmoothQuant is an INT8 method; no nibble packing).
- weight_scales: per-output-row fp16 scales [out_features] —
w_int8 * weight_scales dequantizes the smoothed weights.
- act_scale: per-tensor fp16 activation scale (max abs / 127).
- input_scales: per-input-channel smoothing factors s [in_features]
(fp16). The layer was quantized from W·s and compensates at forward
time by dividing the input: y = Q8(W·s)·Q8(x/s).
Keeping the smoothing compensation in the layer (rather than folding it into the preceding layer) is exact and needs no graph analysis; cross-layer folding is a follow-up optimization (see ADR-010).
SmoothQuantLinear
¶
Bases: Module
INT8 weight+activation quantized Linear with per-channel smoothing.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
in_features |
/ out_features
|
linear geometry. |
sym |
must be True (asymmetric SmoothQuant is a follow-up). |
|
input_scales |
per-input-channel smoothing scale |
源代码位于: src/llm/quantization/_smooth_layer.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
forward
¶
Forward pass: Q8(W·s)·Q8(x/s) with INT8 fake quantization.
Activations are quantized per-tensor (the SmoothQuant contract), then
multiplied by the dequantized smoothed weights. The matmul runs in
fp32 for accuracy and the result returns in the input's dtype —
native nn.Linear semantics — so post-quant fp16/bf16 casts don't
mix dtypes inside F.linear or emit fp32 into half-precision
residual linears (RIL ISS-191). An fp32 model is unchanged.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
Tensor
|
Input tensor of shape [..., in_features]. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Tensor
|
Output tensor of shape [..., out_features]. |
引发:
| 类型 | 描述 |
|---|---|
NotImplementedError
|
If |