72 / QUANTIZATION / MODEL INFRASTRUCTURE
72 / SPECIALIZED / PRECISION REDUCTION · MEMORY · THROUGHPUT · QUALITY TRADE-OFF

QUANTIZATION.

Quantization — представление model weights и/или activations в более низкой числовой точности, чтобы уменьшить память, storage, bandwidth и иногда ускорить inference. Вместо хранения/вычисления всего в FP32/BF16/FP16 система может использовать INT8, INT4, FP8-подобные или другие low-bit formats — полностью или частично.

Главный принцип: quantization — не магия «модель стала в 4 раза легче и такой же умной». Реальный эффект зависит от какие tensors quantized, какой algorithm, group size/scales, hardware kernels, batch size, context length, workload и quality sensitivity. Любой quantized artifact должен проходить task-specific evals и serving benchmark.
00. ARCHITECTURAL STATUS

QUANTIZATION — OPTIMIZATION LAYER, А НЕ ОБЯЗАТЕЛЬНАЯ ЧАСТЬ КАЖДОЙ MODEL PIPELINE

Если model already fits hardware and meets cost/latency targets, quantization may add unnecessary quality/compatibility risk. Она особенно ценна для self-hosting, edge, memory-constrained deployments, very large models and serving stacks where supported low-precision kernels deliver measurable gains.
TYPESPECIALIZEDModel representation / inference optimization.
DEFAULTCONDITIONALDo not quantize without a bottleneck.
ENABLE WHENMEMORY / COST / LATENCY BOTTLENECKAnd evals preserve quality.
SEPARATE COMPONENTYESArtifact transformation/evaluation pipeline.
LIVES INMODEL INFRASTRUCTUREFeeds №70 serving and №71 deployments.
COMPLEXITYLOW → HIGHSimple PTQ → calibration/QAT/mixed precision.
IMPLEMENT: AFTER BASELINE
Минимум 80% ценности: keep full-precision baseline, create immutable quantized candidate artifact, pin method/config/calibration dataset hash, measure disk/VRAM reduction, TTFT/TPOT/TPS on real hardware, run task evals and long-context/structured-output regressions, canary before promotion, retain rollback artifact. Start with weight-only post-training quantization where supported; move to activation/KV/QAT only if measured bottleneck justifies it.
01A. ARCHITECTURE BOUNDARIES & OPERATIONS

EXPLICIT SYSTEM CONTRACT

A. BOUNDARY WITH NEIGHBORS

№70 Model Serving owns runtime batching/KV/scheduler/latency and benchmarks the quantized artifact; №72 owns precision/compression transformation and quality/performance validation. №71 Self-Hosted owns deployment/topology decision and chooses which approved artifact to run. №39 Fine-Tuning/LoRA/Distillation changes model behavior/weights through learning; quantization primarily changes numeric representation for inference/storage efficiency. №65 Gateway may route to a quantized deployment but does not choose quantization algorithm. №40 Eval-Driven Optimization / №47 Evals provide measurement discipline; №72 defines quantization-specific comparisons.

B. PREREQUISITES / CROSS-REFERENCES

Prerequisites: №39 Fine-Tuning/LoRA/Distillation, №40 Eval-Driven Optimization, №46 Observability, №47 Evals, №65 Model Gateway, №70 Model Serving, №71 Local/Self-Hosted. Forward references: №73 Multimodal AI, №77 Production AI Architecture.

C. PLANE PLACEMENT

REQUEST-TIME: no special policy logic; serving executes quantized kernels. CONTROL PLANE: approved precisions, quantization configs, calibration data version, hardware/runtime compatibility, quality thresholds. DATA PLANE: low-precision weights/scales/zero-points/metadata, possibly activation/KV representations. OFFLINE: quantize, calibrate, evaluate, benchmark, package, sign/checksum, promote/rollback.

D. FAILURE & OPERATIONS CONTRACT

Success: candidate artifact loads on target runtime, remains within quality floor, improves intended resource metric and preserves serving stability. Permanent failure: unsupported kernel/format, unacceptable quality regression, incompatible tokenizer/model revision, numerical instability. Persist: base model hash, quantization method, bit-width, group size, scales scheme, calibration dataset hash, tool/runtime version, eval report, benchmark report. Security: quantized artifact is still a model artifact and follows the same supply-chain approval as №71.

E. WHAT THIS TOPIC DOES NOT OWN

№72 не владеет general model compression, distillation, pruning, serving scheduler, GPU allocation, self-hosting strategy or model routing. Она владеет NUMERIC PRECISION REDUCTION OF MODEL RUNTIME ARTIFACTS AND THE VALIDATION OF ITS QUALITY/PERFORMANCE TRADE-OFF.

01. WHY QUANTIZE

LOWER PRECISION МОЖЕТ УМЕНЬШИТЬ ЧЕТЫРЕ RESOURCE COSTS

STORAGE

Smaller artifact

Low-bit weights reduce disk/object-store footprint and model distribution time.

VRAM

More room

Smaller weight footprint can make model fit one device or leave more memory for KV cache/concurrency.

BANDWIDTH

Less memory traffic

Decode often benefits when fewer bytes must move from accelerator memory.

THROUGHPUT / COST

Potential gain

Supported low-precision kernels can improve tokens/sec or reduce hardware requirement.

But not every format accelerates every hardware/runtime. Sometimes quantization only saves memory while compute speed stays similar or even worsens due to dequantization overhead.
02. WHAT GETS QUANTIZED

WEIGHTS, ACTIVATIONS И KV CACHE — РАЗНЫЕ TARGETS

WEIGHT-ONLY

Most common first step

Weights stored in lower precision; activations may remain FP16/BF16. Often simpler and safer for LLM inference.

WEIGHTS + ACTIVATIONS

More aggressive

Can improve compute efficiency on supported hardware but requires calibration/robust kernels and may hurt quality more.

KV CACHE

Long-context memory

Lower-precision KV can increase concurrency/context capacity, but affects decode quality/stability and requires runtime support.

Different tensors have different sensitivity. «Model is INT4» often oversimplifies a mixed-precision runtime where only certain weights are actually 4-bit.
03. PRECISION LADDER

ЧЕМ НИЖЕ BIT-WIDTH, ТЕМ БОЛЬШЕ POTENTIAL SAVINGS И РИСК DISTORTION

RepresentationTypical roleTrade-off
FP32Training/reference/debug in some pipelines.High memory/compute cost; rarely necessary for inference.
BF16 / FP16Common high-quality inference baseline.Good quality; moderate memory footprint.
FP8-likeSupported accelerator inference/training paths.Good efficiency potential; hardware/runtime dependent.
INT8-likeWeights and/or activations.Often strong quality/memory compromise.
INT4 / 4-bit-likeWeight-only inference especially for large models.Large memory reduction; higher sensitivity to method/grouping/model/task.
<4-bitResearch/extreme compression/edge cases.Quality/kernel complexity grows sharply; validate very carefully.
Bit-width label alone is insufficient. Need method + block/group size + scale type + symmetry + outlier handling + kernel/runtime.
04. BASIC MAPPING

FLOAT VALUE → SCALE / ZERO-POINT → INTEGER CODE → APPROXIMATE RECONSTRUCTION

FLOAT RANGE:
  -1.20 ... 0 ... +1.20

QUANTIZED INTEGER RANGE:
  e.g. INT8 → -128 ... 127

ONE SIMPLE SCHEME:

  q = round(x / scale) + zero_point

  x_approx = (q - zero_point) * scale

ERROR:
  e = x - x_approx

QUANTIZATION DOES NOT STORE
THE ORIGINAL CONTINUOUS VALUE.

IT STORES A DISCRETE APPROXIMATION.

THE ENTIRE GAME IS:
  choose representation
  so approximation error
  hurts model behavior as little as possible
  while resource savings are useful.
05. SYMMETRIC VS ASYMMETRIC

ZERO-POINT И RANGE MAPPING ВЛИЯЮТ НА IMPLEMENTATION И ERROR

SYMMETRIC

Zero centered

Usually uses scale around zero with no arbitrary offset. Simpler kernels and common for weights whose distributions are roughly centered.

ASYMMETRIC

Scale + zero-point

Can better cover non-symmetric ranges, especially some activations, at additional complexity.

Choose based on algorithm/runtime support; don't treat one scheme as universally superior.
06. GRANULARITY

ОДИН SCALE НА ВСЮ MODEL — СЛИШКОМ ГРУБО. ЧАСТО НУЖНЫ CHANNEL / GROUP SCALES

PER-TENSOR

One scale

Lowest metadata cost, but outliers can waste most integer range.

PER-CHANNEL

Scale by channel

Better adapts to differing ranges across output/input channels.

GROUP-WISE

Scale per block

Common for low-bit LLM weight quantization; group size trades metadata/kernel complexity for fidelity.

PER-TOKEN / DYNAMIC

Runtime scales

Used in some activation schemes; adds runtime work but adapts to changing input distribution.

Smaller groups usually reduce quantization error but increase scale metadata and may reduce kernel efficiency. Benchmark the whole deployment.
07. OUTLIERS

НЕСКОЛЬКО БОЛЬШИХ VALUES МОГУТ ИСПОРТИТЬ QUANTIZATION RANGE ДЛЯ ВСЕХ ОСТАЛЬНЫХ

PROBLEM

Wide range

Most values cluster near zero, few outliers force a large scale → small values lose precision.

MIXED PRECISION

Keep sensitive parts higher precision

Outlier channels/layers can remain FP16/BF16 while bulk is quantized.

TRANSFORM / CLIP

Algorithm-specific

Calibration algorithms may rescale, clip or rearrange activations/weights to reduce error.

This is why naive min/max rounding is rarely the best 4-bit LLM quantizer.
08. POST-TRAINING QUANTIZATION

PTQ: ВЗЯТЬ ГОТОВУЮ MODEL И СОЗДАТЬ LOWER-PRECISION ARTIFACT БЕЗ FULL RETRAINING

BASE MODELApproved BF16/FP16 revision.
SELECT METHODWeight-only / activation-aware / format.
CALIBRATE?Representative samples if algorithm requires.
QUANTIZECreate scales/codes/artifact.
LOAD TESTTarget runtime/hardware.
EVALQuality regressions.
BENCHMARKVRAM/TTFT/TPOT/TPS.
PTQ is the default first experiment because it is cheap to reverse and does not require training loop changes.
09. WEIGHT-ONLY PTQ

ОБЫЧНО ЛУЧШИЙ MVP ДЛЯ LLM SELF-HOSTING

WHY

Large memory win

Model weights dominate static memory footprint, especially at low concurrency.

ACTIVATIONS

Remain higher precision

Reduces risk and lets existing compute paths handle dynamic values.

LIMIT

Not all speedups guaranteed

Runtime may dequantize into higher precision or use specialized kernels; actual speed varies by hardware.

First goal may simply be: fit model on one GPU and free VRAM for KV cache. That alone can be valuable even if raw token throughput barely changes.
10. CALIBRATION

НЕКОТОРЫЕ METHODS НУЖДАЮТСЯ В REPRESENTATIVE DATA, ЧТОБЫ ПОНЯТЬ SENSITIVE RANGES

REPRESENTATIVE

Match production

Include actual languages, domains, prompt lengths and task types.

SMALL BUT DIVERSE

Not training corpus

Calibration can use a manageable sample if it covers relevant activation distributions.

HASH / VERSION

Reproducibility

Store exact calibration dataset/version and preprocessing config.

NO SECRET LEAK

Governance

Calibration data can contain sensitive content; handle under same data policy as evaluation/training assets.

A quantizer calibrated only on English web text may regress badly on your Russian legal tables or code-heavy workload. Calibration distribution matters.
11. QUANTIZATION-AWARE TRAINING

QAT: MODEL УЧИТСЯ С УЧЁТОМ QUANTIZATION ERROR

WHEN

PTQ quality isn't enough

Very low bit-width or sensitive model/task may require training adaptation.

HOW

Simulate quantization during training

Forward path approximates low-precision effects so weights adapt to them.

COST

Training pipeline complexity

Requires data, compute, optimization and much more lifecycle discipline than PTQ.

QAT should not be the first response to «4-bit lost 0.5%». First ask whether that loss matters, whether a better PTQ method/group size fixes it, or whether INT8 meets the economics.
12. MIXED PRECISION

НЕ ОБЯЗАТЕЛЬНО QUANTIZE ВСЕ ОДИНАКОВО

SENSITIVE LAYERS

Higher precision

Keep first/last/output or empirically sensitive modules in BF16/FP16.

BULK WEIGHTS

Lower precision

Quantize the majority where quality impact is small.

ACTIVATIONS

Selective

Some operations stay higher precision even in nominal low-precision pipeline.

KERNEL PATH

Hardware-aware

Mixed formats only help if runtime executes them efficiently.

The best artifact is often not «everything 4-bit» but a hardware-aware mixed-precision compromise.
13. ACTIVATION QUANTIZATION

ACTIVATIONS ЗАВИСЯТ О INPUT И ПОЭТОМУ СЛОЖНЕЕ STATIC WEIGHTS

DYNAMIC RANGE

Input-dependent

Different prompts can produce very different activation distributions and outliers.

CALIBRATION / DYNAMIC SCALE

Adapt range

Use representative calibration or runtime scaling depending on method.

BENEFIT

Compute kernel opportunity

On suitable hardware, lower-precision activation matmuls can increase throughput and reduce bandwidth.

Activation quantization is more hardware/runtime-specific than weight-only storage compression.
14. KV CACHE QUANTIZATION

LONG CONTEXT / HIGH CONCURRENCY МОЖЕТ СДЕЛАТЬ KV БОЛЬШЕЙ ПРОБЛЕМОЙ, ЧЕМ WEIGHTS

WHY

Memory grows with active tokens

KV footprint scales with context and concurrent sequences.

GAIN

More active tokens

Lower KV precision may increase concurrency or context capacity on same hardware.

RISK

Generation quality / stability

Approximation is used repeatedly during decode, so long-context regressions must be tested carefully.

№70 owns KV allocation/runtime. №72 decides/validates precision representation if the serving stack supports it.
15. MODEL SIZE ESTIMATE

ГРУБАЯ MATH ПОЛЕЗНА ДЛЯ FIRST-PASS SIZING

IDEALIZED WEIGHT STORAGE:

parameters × bits_per_weight / 8

Example:
  70B parameters

FP16 ideal:
  70e9 × 16 / 8
  ≈ 140 GB

INT8 ideal:
  ≈ 70 GB

INT4 ideal:
  ≈ 35 GB

BUT REAL ARTIFACT / VRAM ALSO HAS:
  scales
  zero-points
  metadata
  non-quantized layers
  padding/alignment
  runtime buffers

SO:
  "70B INT4 = exactly 35 GB"
is only a rough lower-bound intuition.
And model fit still excludes KV cache/workspace. Use actual artifact/runtime benchmark before hardware purchase.
16. QUALITY LOSS IS NON-UNIFORM

AVERAGE BENCHMARK МОЖЕТ СКРЫТЬ РЕГРЕССИЮ В КРИТИЧНОМ TASK SEGMENT

GENERAL QA

May stay stable

Broad score moves little.

CODE / MATH

Can be sensitive

Exact reasoning/logit margins may degrade disproportionately.

STRUCTURED OUTPUT

Schema reliability

Small changes can raise JSON/tool-call format failures.

LONG CONTEXT

Hidden regressions

Low precision may behave differently at long sequence lengths.

Use the exact task/eval suite that deployment must pass. Generic leaderboard delta alone is insufficient.
17. LOGIT MARGINS

НЕБОЛЬШАЯ NUMERIC ERROR МОЖЕТ ИЗМЕНИТЬ TOKEN CHOICE, А ПОТОМ ВСЮ GENERATION TRAJECTORY

FULL PRECISION

token A logit = 5.01
token B = 4.99

QUANTIZATION ERROR

A = 4.97
B = 5.00

DIFFERENT TOKEN

Next context changes → future token distribution diverges.

Therefore exact token-match against full precision is not the right general success criterion. Measure task outcome quality and behavioral regressions.
18. DETERMINISM & COMPARISON

СРАВНИВАТЬ CANDIDATES НА ОДИНАКОВЫХ GENERATION SETTINGS

GREEDY / FIXED

Deterministic-ish baseline

Useful for low-noise artifact comparison when model/runtime permit deterministic execution.

SAME PROMPTS

Paired evaluation

Base and quantized model receive identical task inputs/context.

SAMPLING TASKS

Repeat / aggregate

When production uses sampling, compare pass rates/distributions rather than single outputs.

Quantization evaluation should isolate artifact change from prompt/model revision/runtime config changes.
19. QUANTIZATION EVAL MATRIX

КАЖДЫЙ CANDIDATE ПРОХОДИТ QUALITY + PERFORMANCE + MEMORY + STABILITY

DimensionBaselineCandidateDecision rule
Task pass rateFull precisionQuantizedRegression ≤ allowed threshold by critical segment.
Structured output successJSON/tool-call pass %Candidate %No material increase in contract failures.
Long-context qualityReference testsCandidate testsNo unacceptable degradation.
VRAMMeasuredMeasuredMust improve target memory bottleneck.
TTFT / TPOTSame hardware/runtimeCandidateGain or no unacceptable regression.
Throughputtokens/sectokens/secMeasured under same SLO.
StabilityOOM/error rateCandidateNo new numerical/runtime instability.
A candidate that halves VRAM but loses critical structured-output reliability may be a bad production optimization even if average QA benchmark stays high.
20. PERFORMANCE BENCHMARK

QUANTIZATION НУЖНО МЕРИТЬ НА TARGET HARDWARE, А НЕ ПО ТЕОРЕТИЧЕСКИМ FLOPS

VRAM

Static + active

Measure loaded model and KV/workspace under real concurrency.

TTFT

Prefill impact

Lower precision may or may not speed prompt processing.

TPOT

Decode speed

Often where memory-bandwidth gains can show up.

TPS

Throughput

Compare under same prompt/output distribution and SLO.

POWER

Energy efficiency

Useful for edge/high-volume TCO.

LOAD TIME

Cold start

Smaller artifact can improve model distribution/startup.

CONCURRENCY

KV headroom

Weight savings may allow more active sequences even without faster single request.

SOAK

Stability

Long runs reveal kernel/runtime bugs and memory fragmentation.

21. HARDWARE COMPATIBILITY

FORMAT БЕСПОЛЕЗЕН, ЕСЛИ TARGET ACCELERATOR НЕ ИМЕЕТ ЭФФЕКТИВНОГО KERNEL PATH

SUPPORTED

Native low-precision path

Hardware/runtime executes quantized matmul efficiently.

DEQUANTIZE-HEAVY

Memory-only benefit

Weights are compressed in memory but expanded for compute, limiting speed gain.

UNSUPPORTED

Artifact cannot run

Format/kernel/model architecture mismatch may make candidate unusable.

Quantization choice belongs to a model × method × runtime × hardware compatibility matrix.
22. RUNTIME FORMAT

НЕ ПУТАТЬ LOGICAL PRECISION С FILE FORMAT И SERVING KERNEL

LOGICAL SCHEME

How values are quantized

Bit width, group size, scales, symmetry, outlier handling.

ARTIFACT FORMAT

How stored

Container/layout/metadata for runtime loading.

KERNEL IMPLEMENTATION

How executed

Actual accelerator operator path determines performance.

Two artifacts both described as «4-bit» can have very different quality, size and speed because their schemes/layouts/kernels differ.
23. QUANTIZED ARTIFACT CONTRACT

КАНДИДАТ ДОЛЖЕН БЫТЬ ВОСПРОИЗВОДИМЫМ, А НЕ «ФАЙЛ model-int4-final2.bin»

{
  "artifact_ref": "modelq://model-x/q17",
  "base_model_ref": "model://model-x/r42",
  "base_model_hash": "sha256:...",
  "quantization": {
    "method": "weight_only",
    "algorithm": "...",
    "weight_bits": 4,
    "group_size": 128,
    "symmetric": true,
    "activation_bits": 16,
    "kv_bits": 16
  },
  "calibration": {
    "dataset_hash": "sha256:...",
    "sample_count": 512
  },
  "tool_version": "...",
  "artifact_hash": "sha256:...",
  "compatible_runtime": ["serve-profile-v8"],
  "quality_report_ref": "eval://...",
  "benchmark_ref": "bench://...",
  "status": "APPROVED"
}
PROMOTION REQUIREMENTS

Artifact is a release

  • exact base model;
  • exact quantizer/tool version;
  • all precision/grouping parameters;
  • calibration provenance;
  • artifact checksum;
  • runtime compatibility;
  • quality report;
  • hardware benchmark;
  • approval status;
  • rollback target.
24. QUANTIZE AFTER FINE-TUNING?

BASE + ADAPTER / MERGED WEIGHTS НУЖДАЮТСЯ В ЯВНОМ PIPELINE ORDER

COMMON

Fine-tune → quantize

First produce final adapted model, then quantize the exact deployment candidate and evaluate it.

ADAPTER SERVING

Base + LoRA separately

Runtime may support quantized base with higher-precision adapters; compatibility must be tested.

QAT

Training-aware path

If low precision is a hard deployment requirement, training may explicitly optimize for it.

№39 owns training/adaptation. №72 owns the deployment precision artifact and post-quantization eval.
25. QUANTIZATION ≠ DISTILLATION

ОДНО МЕНЯЕТ NUMERIC REPRESENTATION, ДРУГОЕ — MODEL CAPACITY / WEIGHTS THROUGH LEARNING

TechniqueWhat changesMain goal
QUANTIZATIONPrecision/encoding of parameters/activations.Memory/bandwidth/compute efficiency.
DISTILLATIONStudent model trained to imitate teacher.Smaller/faster learned model.
PRUNINGRemove/zero parameters/structures.Reduce compute/model size if runtime exploits sparsity.
FINE-TUNINGUpdate weights/adapters on task/domain data.Change behavior/quality.
These methods can be combined, but they are separate optimization levers and should be evaluated independently.
26. STRUCTURED OUTPUT & TOOL CALLING

ПРОВЕРЯТЬ НЕ ТОЛЬКО «СМЫСЛ ОТВЕТА», НО И CONTRACT RELIABILITY

JSON

Syntax success

Does candidate still produce valid schema-conforming outputs?

TOOL SELECTION

Routing fidelity

Does low precision change function/tool choice on borderline cases?

ARGUMENTS

Exactness

Names, numbers, IDs and enum values may be more sensitive than broad prose similarity.

For agents, 1% drop in JSON/tool-call reliability can be more damaging than 1% generic benchmark drop.
27. LONG-CONTEXT EVAL

КВАНТИЗАЦИЯ МОЖЕТ ВЫГЛЯДЕТЬ НОРМАЛЬНО НА 2K TOKENS И РЕГРЕССИРОВАТЬ НА 64K

RETRIEVAL

Needle / evidence

Can model still recover exact relevant facts from long context?

ORDER

Temporal/sequence reasoning

Does it preserve relation/order at long lengths?

KV QUANT

Extra sensitivity

Quantized KV should be tested at p95/p99 expected context, not just short examples.

STABILITY

Runtime memory

Measure OOM, latency and output degeneration as context grows.

28. MULTILINGUAL / DOMAIN REGRESSION

QUANTIZATION ERROR МОЖЕТ БЫТЬ НЕРАВНОМЕРЕН ПО ЯЗЫКАМ И DOMAIN

LANGUAGE SEGMENTS

Test real locales

Russian, English and other production languages separately.

DOMAIN

Special vocabulary

Legal, medical, code, finance, internal terminology can have different sensitivity.

FORMAT

Tables / numbers / IDs

Exact factual extraction should be evaluated as its own task class.

Calibration and eval data should reflect the domain actually served, not generic benchmark convenience.
29. CANARY / AB TEST

QUANTIZED MODEL — НОВЫЙ DEPLOYMENT REVISION, ДАЖЕ ЕСЛИ «ЭТО ТА ЖЕ MODEL»

FULL PRECISIONCurrent stable target.
QUANTIZED CANDIDATESeparate deployment_ref.
SHADOWOptional duplicate offline comparison.
CANARYSmall eligible traffic.
COMPAREQuality + latency + errors + VRAM.
PROMOTE / ROLLBACKEvidence-based.
№65 should treat each approved quantized artifact as a distinct model deployment with its own capability/quality/capacity profile.
30. WHEN SPEED GETS WORSE

SMALLER WEIGHTS МОГУТ ДАТЬ МЕНЬШЕ SPEED, ЕСЛИ RUNTIME DEQUANTIZES ИЛИ KERNEL НЕОПТИМАЛЕН

DEQUANT OVERHEAD

Extra conversion

Low-bit values expanded before compute.

BAD KERNEL

No optimized path

Generic kernels may underperform well-optimized BF16 path.

SMALL BATCH

Overhead dominates

Some optimizations only win at certain batch/concurrency sizes.

MEMORY WIN

Still valuable

Even slower single request can be acceptable if quantization makes deployment possible or increases concurrency enough.

Define optimization objective before testing: fit, concurrency, TTFT, TPOT, throughput, power or TCO. One artifact may improve some and worsen others.
31. ACCURACY BUDGET

QUANTIZATION ДОЛЖНА ИМЕТЬ ЯВНЫЙ ALLOWED REGRESSION

EXAMPLE POLICY:

critical tasks:
  structured output pass rate
    regression <= 0.2 percentage points

high-risk factual tasks:
  verification pass rate
    no statistically meaningful regression

general chat:
  preference win/loss
    quantized not worse than threshold

code:
  unit-test pass rate
    regression <= 1%

long-context:
  retrieval accuracy
    regression <= 0.5%

IF candidate violates a critical segment:
  reject
  OR use it only for eligible task classes
  via №65 routing.
Quantization can be task-scoped. A 4-bit deployment may be excellent for summarization but excluded from code generation or tool-use tasks.
32. HARDWARE-AWARE ROUTING

ОДНА MODEL FAMILY МОЖЕТ ИМЕТЬ НЕСКОЛЬКО DEPLOYMENTS С РАЗНОЙ PRECISION

BF16 POOL

High fidelity

Critical/high-risk or tasks where quantized artifact failed quality threshold.

INT8 / FP8 POOL

Balanced

General production workload where supported hardware gives good throughput.

4-BIT POOL

Memory-efficient

Local/edge/high-volume helper tasks where evals prove sufficiency.

№65 can route by task/quality/cost class; quantization does not need to be one global choice per model family.
33. ARTIFACT VERSIONING

BASE MODEL REVISION CHANGE INVALIDATES PREVIOUS QUANTIZED ARTIFACT

BASE PIN

Exact source weights

Quantized candidate points to immutable base model hash.

CONFIG PIN

Exact method

Bit-width/group/calibration/tool/runtime metadata.

REBUILD

New base → new candidate

Do not assume quantization settings transfer unchanged to a new model revision.

Quantized artifacts are derived model releases and should have their own version lifecycle.
34. FAILURE MODES

КАК QUANTIZATION ПРЕВРАЩАЕТСЯ В BENCHMARK THEATER

"INT4 = 4× FASTER"
Speed assumed from bit-width without target hardware/runtime benchmark.
MEASURE ACTUAL SERVING
GENERIC BENCH ONLY
Critical domain/tool/structured-output regressions stay invisible.
TASK-SEGMENT EVALS
NO BASELINE
Cannot attribute quality/performance change to quantization.
PIN FULL-PRECISION BASE
BIT-WIDTH ONLY
Group size/scales/method/kernel differences ignored.
FULL ARTIFACT CONTRACT
NO CALIBRATION VERSION
Candidate cannot be reproduced or explained.
HASH CALIBRATION DATA
ALL TASKS USE ONE Q MODEL
Sensitive workloads forced onto artifact that failed their quality threshold.
ROUTE BY ELIGIBILITY
MODEL FIT = DONE
KV/cache/workspace leaves no room for real concurrency.
SERVING BENCHMARK
NO ROLLBACK
Runtime/kernel regression forces emergency rebuild.
KEEP PRIOR ARTIFACT
QAT FIRST
Training complexity added before simple PTQ alternatives are tested.
PTQ → EVAL → ESCALATE
35. OBSERVABILITY

QUANTIZED DEPLOYMENT ДОЛЖЕН БЫТЬ ВИДЕН КАК ОТДЕЛЬНЫЙ MODEL ARTIFACT

ΔQ

Quality Delta

Task/eval regression vs pinned full-precision baseline.

VRAM

Memory Saved

Loaded/static and active workload memory reduction.

ΔTTFT

Prefill Delta

Time-to-first-token change under same workload.

ΔTPOT

Decode Delta

Inter-token/decode speed improvement or regression.

TPS

Throughput Delta

Tokens/sec under same SLO and concurrency.

FIT

Capacity Gain

More active sequences/context or reduced device count.

ERR

Runtime Error Rate

Kernel/numerical/load/OOM issues by artifact.

$

Cost / Success

Full deployment cost normalized by verified successful tasks.

36. FAILURE INJECTION / TESTING

ПРОВЕРИТЬ НЕ ТОЛЬКО QUALITY, НО И DEPLOYMENT ROBUSTNESS

LOAD

Cold start

Artifact loads reliably on every supported node/runtime version.

LONG SOAK

Stability

No kernel crashes, memory leaks or numerical degeneration after sustained traffic.

MAX CONTEXT

Boundary

Test declared context/output limits, especially with KV quantization.

CONCURRENCY RAMP

Capacity

Find actual saturation and OOM-safe limit.

BAD ARTIFACT

Checksum

Corrupted quantized file is rejected before serving.

ROLLBACK

Canary failure

Router returns traffic to previous model revision quickly.

STRUCTURED

Tool/JSON

High-volume contract tests reveal small reliability regressions.

DOMAIN

Languages/tasks

Critical production segments separately evaluated.

37. MVP IMPLEMENTATION

ОДИН BASELINE + ОДИН QUANTIZED CANDIDATE + ОДИН TARGET HARDWARE BENCHMARK

quantization/
├── configs/
│   └── q4_candidate.yaml
├── calibrate.py
├── quantize.py
├── package.py
├── eval_quality.py
├── benchmark_serving.py
├── reports/
└── registry.json

candidate config:

base_model_ref: model://x/r42
method: weight_only
weight_bits: 4
group_size: 128
symmetric: true
activation_bits: 16
kv_bits: 16
calibration_ref: dataset://qcal/v3
target_runtime: serve-profile-v8
target_hardware: gpu-class-A

pipeline:

base artifact
  ↓
quantize
  ↓
artifact checksum
  ↓
load on target runtime
  ↓
quality eval
  ↓
serving benchmark
  ↓
compare against baseline
  ↓
APPROVE / REJECT
  ↓
canary deployment
80% VALUE MVP

Do one controlled experiment

  • Keep full-precision baseline.
  • Choose one memory bottleneck.
  • Try one supported weight-only PTQ method.
  • Use representative calibration if required.
  • Pin every config/version/hash.
  • Measure artifact size + loaded VRAM.
  • Measure TTFT/TPOT/TPS on target hardware.
  • Run critical task evals.
  • Test long-context and structured outputs.
  • Canary behind №65.
  • Keep immediate rollback.

If the candidate does not materially improve the target bottleneck at acceptable quality, stop. Do not add QAT/more exotic formats just because they exist.

38. WHEN TO UPGRADE

СЛЕДУЮЩИЙ УРОВЕНЬ — ТОЛЬКО ЕСЛИ SIMPLE PTQ НЕ ДОСТАТОЧЕН

Observed needNext move
4-bit quality too lowTry higher precision, different grouping/method, mixed precision or exclude sensitive task classes.
Weights fit but KV dominatesEvaluate KV-cache quantization or more memory/replicas.
Memory improves but speed does notCheck runtime kernel support/hardware path; benchmark alternative format.
INT8 is almost enough but hardware underutilizedEvaluate supported activation quantization / FP8-like path.
PTQ cannot meet hard low-bit targetConsider QAT or distillation only if economics justify training pipeline.
Different workloads have different sensitivityMaintain multiple precision deployments and let №65 route by eligibility.
Edge device still cannot fit modelSmaller/distilled model may be better than ever more aggressive quantization.
39. PRACTICAL DECISION

СТОИТ ЛИ ДЕЛАТЬ ОТДЕЛЬНЫЙ КОМПОНЕНТ?

ВопросОтвет
Стоит ли реализовывать?Условно. После full-precision baseline, если есть измеренный memory/cost/latency bottleneck.
Separate Component?YES логически. Offline artifact transformation/evaluation pipeline feeding Model Infrastructure.
Минимум 80% ценности?Weight-only PTQ, exact artifact/config metadata, quality eval, target-hardware benchmark, canary and rollback.
Когда overkill?QAT/mixed ultra-low-bit pipeline для модели, которая уже помещается и удовлетворяет SLO/TCO.
Trigger?Model doesn't fit, KV headroom too low, owned hardware cost is high, edge constraints, or low-precision hardware kernels can materially improve serving.
Как измерить uplift?VRAM reduction, capacity increase, TTFT/TPOT/TPS delta, power/cost per successful task and task-specific quality delta.
Можно ли rule/tool/code вместо LLM-agent?Да. Quantization is deterministic artifact tooling + eval pipeline. LLM-agent is not needed to choose scales at runtime.
40. DESIGN RULES

ПРАВИЛА ДЛЯ РЕАЛЬНОЙ СИСТЕМЫ

RULE 01

Baseline first

Know full-precision quality and serving profile before optimizing.

RULE 02

Optimize a named bottleneck

Memory, KV capacity, TPOT, power or TCO — not «lower bits» as a goal.

RULE 03

Bit-width is not the artifact

Method, group size, scales, runtime, hardware and calibration define behavior.

RULE 04

Evaluate critical segments

Tool calls, JSON, code, long context and domain language may regress unevenly.

RULE 05

Benchmark target hardware

Theoretical compression does not guarantee speedup.

RULE 06

Prefer PTQ before QAT

Use the cheapest reversible optimization first.

RULE 07

Mixed precision is valid

Sensitive layers/tasks can stay higher precision.

RULE 08

Quantized artifact is a release

Version, checksum, eval, benchmark, canary and rollback.

RULE 09

Route by eligibility

Different precision deployments can serve different task classes.

41. FINAL MAP

QUANTIZATION IS A CONTROLLED TRADE: NUMERIC PRECISION FOR DEPLOYMENT EFFICIENCY

FULL-PRECISION BASELINE
  exact model revision
  exact tokenizer
  task evals
  serving benchmark
        ↓
IDENTIFY BOTTLENECK

model does not fit?
VRAM leaves no KV room?
decode is bandwidth-limited?
edge power/storage too high?
TCO too high?
        ↓
SELECT QUANTIZATION TARGET

weights only
weights + activations
KV cache
mixed precision
        ↓
SELECT METHOD / FORMAT

bit-width
group size
scale scheme
symmetry
outlier handling
calibration
target runtime
target hardware
        ↓
CREATE IMMUTABLE CANDIDATE
  base model hash
  quantizer version
  calibration hash
  artifact checksum
        ↓
LOAD ON TARGET HARDWARE
        ↓
QUALITY EVAL
  critical tasks
  structured outputs
  tools
  code/math
  languages/domain
  long context
        ↓
SERVING BENCHMARK
  artifact size
  loaded VRAM
  TTFT
  TPOT / ITL
  TPS
  concurrency
  power
  stability
        ↓
COMPARE WITH BASELINE
        ↓

IF:
  quality within budget
  AND target bottleneck improves
  AND runtime stable
        ↓
CANARY
        ↓
PROMOTE
        ↓
REGISTER DISTINCT DEPLOYMENT IN №65

ELSE:
  reject
  try higher precision /
  different method /
  mixed precision /
  smaller model /
  more hardware
        ↓
DO NOT FORCE QUANTIZATION

BOUNDARIES:

№39
  changes model behavior through learning

№70
  serves artifact and measures runtime performance

№71
  decides where/how to self-host

№72
  changes numeric precision of deployment artifact

№65
  routes tasks to approved deployment profiles

CORE PRINCIPLE:

QUANTIZATION IS NOT
"MAKE THE MODEL 4-BIT."

IT IS:

"CAN WE REPRESENT
THIS MODEL WITH
LESS NUMERIC PRECISION
ON THIS HARDWARE
FOR THIS WORKLOAD
WITHOUT LOSING
THE QUALITY WE ACTUALLY NEED?"

THE WIN IS NOT
THE SMALLEST FILE.

THE WIN IS
LOWER REAL SYSTEM COST
AT THE SAME
ACCEPTABLE TASK QUALITY.

ECC RETROFIT / PRACTICAL HARNESS INTEGRATION

A. Related ECC ideas. Context-as-cache, scoped memory, lifecycle hooks, selective capabilities, feature flags, deterministic enforcement, provider-neutral adapters and eval-gated learning are applied only where relevant to №72 Quantization.

B–E. Existing boundary and placement. The existing conceptual boundary, class SPECIALIZED, default CONDITIONAL and owner Model Infrastructure remain authoritative. Runtime/control/data/offline placement is unchanged; durable state stays outside model context.

F–H. Hooks and contracts. Use bounded PRE_MODEL/POST_MODEL, PRE_TOOL/POST_TOOL, CHECKPOINT and TASK_COMPLETED events as applicable. Illustrative fields and canonical contracts are defined in NEW_CONTRACTS_SPEC.md; no universal schema is implied.

I–J. Security and evaluation. Host-side schema, permission, secret, budget, idempotency and audit checks take precedence over LLM output. Optional mechanisms require a feature flag and WITH/WITHOUT ablation; measure quality, acceptance, correction, latency, cost, escalations and severe errors.

K–L. Task profiles and cross-references. A TaskProfile selects the relevant skill, tool/context slice, memory scope and enforcement profile independently from FAST/STANDARD/DEEP. See cross-reference map, hook spec and ablation plan. Provider adapters remain outside the core.