torch_to_nnef.tensor.quant.qtract_ggml
tract ggml reference block formats (Q8_0, K-quants, IQ formats).
Like the formats of qtract, the u8 storage holds one quantized code per
value and the qscheme holds the block parameters as torch tensors. tract
bytes, laid out exactly like llama.cpp block_* structures, are only made
when written.
Quantization ports the ggml reference quantizers in torch: every f32
operation runs in ggml order (sums accumulate sequentially, no fused
multiply add), so on CPU the written bytes match llama.cpp reference
quantizers built without floating point contraction (-ffp-contract=off;
compilers fusing multiply adds give slightly different bytes).
Warning
tract (<= 0.23.10) has no matmul or convolution kernel for these formats: only embedding/gathering operations are supported.
Classes:
| Name | Description |
|---|---|
GGMLUnderflowCheck |
Blocks erased to zeros by f16 scales underflow, over a whole tensor. |
QScaleGGMLIQ2S |
ggml IQ2_S super-block scheme. |
QScaleGGMLK |
Common base of ggml super-block schemes (K-quants, IQ formats). |
QScaleGGMLK6 |
ggml Q6_K symmetric super-block scheme. |
QScaleGGMLKMin |
ggml K-quant super-block scheme with mins (Q4_K, Q5_K). |
QScaleQ8_0 |
Q8_0 f16 scale |
QTensorTractGGMLK |
Common base of tract ggml super-block formats ( |
QTensorTractGGMLKMin |
Common base of Q4_K and Q5_K: |
QTensorTractIQ2_S |
Tract data format it serializes to: IQ2_S (ggml |
QTensorTractQ4_K |
Tract data format it serializes to: Q4_K (ggml |
QTensorTractQ5_K |
Tract data format it serializes to: Q5_K (ggml |
QTensorTractQ6_K |
Tract data format it serializes to: Q6_K (ggml |
QTensorTractQ8_0 |
Tract data format it serializes to: Q8_0 (ggml |
Functions:
| Name | Description |
|---|---|
fp_to_tract_iq2_s |
Quantize float tensor to tract supported IQ2_S (ggml reference). |
fp_to_tract_q4_k |
Quantize float tensor to tract supported Q4_K (ggml reference). |
fp_to_tract_q5_k |
Quantize float tensor to tract supported Q5_K (ggml reference). |
fp_to_tract_q6_k |
Quantize float tensor to tract supported Q6_K (ggml reference). |
fp_to_tract_q8_0_with_min_max_calibration |
Min-Max method to quantize float tensor to tract supported Q8_0. |
ggml_f16_to_bytes |
(n,) f32 to (n, 2) u8: little endian f16 bytes (ggml_fp16_t). |
ggml_f32 |
f32 scalar, to keep ggml f32 arithmetic on python constants. |
ggml_first_absmax |
Signed value of max |x| per row (first one on ties), and that |x|. |
ggml_iter_blocks |
Yield (start, f32 chunk (n, block_len)) of |
ggml_k_min_sub_weights |
Weights of ggml K-quants |
ggml_make_qkx2_quants |
Port of ggml |
ggml_make_qx_quants |
Port of ggml |
ggml_nearest_int |
Port of ggml |
ggml_pack_scale_min_k4 |
Pack 6bit (n, 8) sub-block scales and mins in ggml 12 bytes (n, 12). |
ggml_quant_iq2_s |
IQ2_S super-blocks (ggml |
ggml_quant_k_scales_mins |
Q4_K/Q5_K super-block parameters (ggml |
ggml_quant_q6_k_scales |
Q6_K super-block parameters (ggml |
ggml_seq_sum |
f32 sum over last dim accumulated sequentially, like ggml loops. |
ggml_sqrt |
Correctly rounded f32 square root (IEEE |
round_half_away |
C |
GGMLUnderflowCheck
Blocks erased to zeros by f16 scales underflow, over a whole tensor.
Like llama.cpp and tract quantizers, such blocks are kept as zeros
(with a warning) when their weights are negligible against the tensor
largest weight (below GGML_UNDERFLOW_REL_TOL of it, the f16
precision): this is a quantization error below what the f16
dequantized tensor can represent. Otherwise the weights are too small
as a whole for the format f16 scales. A partial underflow (like Q4_K
d rounded to 0 while dmin is not) is not reported: it only drops
variations far below the remaining f16 scale, within the quantization
error.
Feed each chunk of blocks to update, then call check.
Methods:
| Name | Description |
|---|---|
check |
Warn on negligible erased blocks, raise otherwise. |
update |
Account (n, block) fp weights and their dequantized values. |
check
Warn on negligible erased blocks, raise otherwise.
Raises:
| Type | Description |
|---|---|
T2NErrorImpossibleQuantization
|
when erased weights are not negligible. |
QScaleGGMLIQ2S
Bases: QScaleGGMLK
ggml IQ2_S super-block scheme.
Per super-block of 256 values: f16 d (n,), and per group of 16
values a 4bit scale scales (n, 16). Each u8 code holds the grid
level of its value in bits 1-0 (0, 1 or 2 for magnitudes 8, 25 and
43) and its sign in bit 2 (set for negative), so codes are in
{0, 1, 2, 4, 5, 6}. A code dequantizes to
(d * (0.5 + scale) * 0.25) * (magnitude * sign).
Each octet of 8 levels is a point of the ggml kgrid_2bit_1024 grid
(its index is looked up when packed). Levels come from a search that
the parameters alone do not determine: quantize_blocks runs the
deterministic ggml quantizer again and checks it finds these
parameters.
Methods:
| Name | Description |
|---|---|
levels |
F32 signed grid magnitudes (multiplying by +-1 is exact). |
quantize_blocks |
Codes of the ggml quantizer, checked against these parameters. |
sub_scales |
F32 group scales |
quantize_blocks
Codes of the ggml quantizer, checked against these parameters.
Raises:
| Type | Description |
|---|---|
T2NErrorMisuse
|
|
QScaleGGMLK
Bases: QScheme
Common base of ggml super-block schemes (K-quants, IQ formats).
Holds, as torch tensors with a leading super-block dimension (n,),
a f16 super-block scale d and per sub-block of SUB_LEN values
integer scales, plus format specific parameters (PARAM_NAMES).
A code dequantizes in f32 to
sub_scales * levels(code) - sub_offsets (tract op order), then is
casted.
Subclass contract
SUB_LEN,PARAM_NAMES(constructor tensor arguments, in order),F16_PARAMS(checked for f16 overflow)_settings(): non tensor constructor argumentsfit_blocks(x, **settings) -> (scheme, codes): ggml reference quantizer of f32 (n, 256) super-blocksquantize_blocks(x) -> codes: codes of (n, 256) super-blocks with this scheme parameterssub_scales(), optionallysub_offsets()andlevels(codes)
Methods:
| Name | Description |
|---|---|
calibrate |
Fit ggml reference parameters and codes of |
dequantize |
F32 |
fit_blocks |
Fit ggml reference parameters and u8 codes of (n, 256) blocks. |
levels |
F32 levels of (n, 256 // SUB_LEN, SUB_LEN) u8 codes. |
quantize_as_u8 |
Codes of |
quantize_blocks |
U8 codes (n, 256) of f32 (n, 256) blocks with these params. |
sub_offsets |
F32 (n, 256 // SUB_LEN) offset of each sub-block, if any. |
sub_scales |
F32 (n, 256 // SUB_LEN) scale of each sub-block. |
calibrate
classmethod
Fit ggml reference parameters and codes of fp_tensor.
Returns:
| Type | Description |
|---|---|
Tuple[QScaleGGMLK, Tensor]
|
(scheme, u8 codes of |
Raises:
| Type | Description |
|---|---|
T2NErrorImpossibleQuantization
|
on f16 overflow of a
|
dequantize
F32 sub_scales * levels - sub_offsets like tract, then cast.
fit_blocks
classmethod
Fit ggml reference parameters and u8 codes of (n, 256) blocks.
quantize_as_u8
Codes of fp_tensor with these parameters.
quantize_blocks
U8 codes (n, 256) of f32 (n, 256) blocks with these params.
sub_offsets
F32 (n, 256 // SUB_LEN) offset of each sub-block, if any.
QScaleGGMLK6
Bases: QScaleGGMLK
ggml Q6_K symmetric super-block scheme.
Per super-block of 256 values: f16 d (n,), and per sub-block of
16 values i8 scales sc (n, 16). A code q in [0, 63] dequantizes
to (d * sc) * (q - 32).
ggml keeps its make_qx_quants search levels for sub-blocks whose
d * sc is 0, and zeros for super-blocks without any scale.
Methods:
| Name | Description |
|---|---|
quantize_blocks |
Final ggml levels with the f16 rounded super-block scale. |
QScaleGGMLKMin
Bases: QScaleGGMLK
ggml K-quant super-block scheme with mins (Q4_K, Q5_K).
Per super-block of 256 values: f16 d and dmin (n,), and per
sub-block of 32 values 6bit scales sc and mins m (n, 8). A code
q in [0, nmax] dequantizes to (d * sc) * q - (dmin * m).
nmax, rmin and nstep are the format make_qkx2_quants settings:
ggml keeps its search levels for sub-blocks whose d * sc is 0.
Methods:
| Name | Description |
|---|---|
quantize_blocks |
Final ggml levels with the f16 rounded super-block scales. |
QScaleQ8_0
Bases: QScalePerGroupF16
Q8_0 f16 scale d per block of 32 (ggml block_q8_0).
Codes are q + 128 with q in [-127, 127], dequantized in f32 as
d * q (like tract), then casted.
Like llama.cpp quantize_row_q8_0_ref, q = roundf(x / d_f32) with
d_f32 = absmax / 127 of the block in f32, before its f16 rounding.
quantize_as_u8 recomputes d_f32 from each block of the given
tensor and uses it whenever it rounds to the stored f16 scale: this is
the case of fp_to_tract_q8_0_with_min_max_calibration (positive
scales). Otherwise, the block falls back to the stored f16 scale
itself: scales set by an external calibration (GPTQ, clipping, a
negative or any other scale than f16(absmax / 127) of the block), or
a tensor quantized with scales calibrated on other weights.
Methods:
| Name | Description |
|---|---|
dequantize |
F32 |
QTensorTractGGMLK
Bases: QTensorTractBlockQuant
Common base of tract ggml super-block formats (QScaleGGMLK).
Subclasses define FORMAT_NAME, OFFLOAD_STATE_TAG, BLOCK_BYTES,
ITEM_TYPE, QSCHEME_CLS, optionally _scheme_settings(), and
_pack_blocks.
Methods:
| Name | Description |
|---|---|
from_fp |
Quantize a float tensor with the ggml reference quantizer. |
QTensorTractGGMLKMin
Bases: QTensorTractGGMLK
Common base of Q4_K and Q5_K: QScaleGGMLKMin super-blocks.
Subclasses define the make_qkx2_quants settings (NMAX, RMIN,
NSTEP) and pack levels after the shared 16 bytes header (f16 d,
f16 dmin, 12 bytes of 6bit scales and mins) in _pack_levels.
QTensorTractIQ2_S
Bases: QTensorTractGGMLK
Tract data format it serializes to: IQ2_S (ggml block_iq2_s).
Each super-block of 256 values is stored as 82 bytes (2.5625bpw):
f16 d, 32 low grid index bytes then 32 sign bytes (one per octet
of 8 values), 8 bytes of 2bit high grid index parts, then sixteen
4bit scales (one per group of 16 values).
Each octet is a point of the ggml 1024 entries kgrid_2bit_1024
grid (magnitudes in {8, 25, 43}), value is
d * (0.5 + scale) * 0.25 * magnitude * sign.
Its u8 storage holds one code per value (grid level and sign, see
QScaleGGMLIQ2S), grid indices are only looked up when written.
Quantization ports llama.cpp quantize_row_iq2_s_ref without
importance matrix (grid nearest neighbour search with a weighted
scale fit, about 2s per 16384 super-blocks on CPU), dequantization
matches tract bit exactly.
Warning
tract (<= 0.23.10) only supports IQ2_S weights in embedding/gathering operations: there is no matmul or convolution kernel for it yet.
QTensorTractQ4_K
Bases: QTensorTractGGMLKMin
Tract data format it serializes to: Q4_K (ggml block_q4_K).
Each super-block of 256 values is stored as 144 bytes:
f16 d, f16 dmin, 12 bytes of eight 6bit scales and mins
(one per sub-block of 32 values), then 256 4bit levels (4.5bpw).
Value is d * scale * level - dmin * min.
Quantization ports llama.cpp quantize_row_q4_K_ref (no importance
matrix), dequantization matches tract bit exactly.
Warning
tract (<= 0.23.10) only supports Q4_K weights in embedding/gathering operations: there is no matmul or convolution kernel for it yet.
QTensorTractQ5_K
Bases: QTensorTractGGMLKMin
Tract data format it serializes to: Q5_K (ggml block_q5_K).
Each super-block of 256 values is stored as 176 bytes:
f16 d, f16 dmin, 12 bytes of eight 6bit scales and mins
(one per sub-block of 32 values), 32 bytes of level high bits,
then 256 low 4bit levels (5.5bpw).
Value is d * scale * level - dmin * min with 5bit levels.
Quantization ports llama.cpp quantize_row_q5_K_ref (no importance
matrix), dequantization matches tract bit exactly.
Warning
tract (<= 0.23.10) only supports Q5_K weights in embedding/gathering operations: there is no matmul or convolution kernel for it yet.
QTensorTractQ6_K
Bases: QTensorTractGGMLK
Tract data format it serializes to: Q6_K (ggml block_q6_K).
Each super-block of 256 values is stored as 210 bytes:
128 bytes of low 4 bits and 64 bytes of high 2 bits of 256 6bit
levels, sixteen i8 scales (one per sub-block of 16 values), then
f16 d (6.5625bpw). It is symmetric: value is
d * scale * (level - 32).
Quantization ports llama.cpp quantize_row_q6_K_ref (no importance
matrix), dequantization matches tract bit exactly.
Warning
tract (<= 0.23.10) only supports Q6_K weights in embedding/gathering operations: there is no matmul or convolution kernel for it yet.
QTensorTractQ8_0
Bases: QTensorTractScalePerGroupF16
Tract data format it serializes to: Q8_0 (ggml block_q8_0).
Each group of 32 values is stored as 34 bytes:
f16 scale d, then 32 int8 (8.5bpw). Value is d * q.
Use fp_to_tract_q8_0_with_min_max_calibration to construct it:
quantization matches llama.cpp quantize_row_q8_0_ref bytes,
dequantization matches tract bit exactly. External calibrations
provide their scales with a QScaleQ8_0.
Warning
tract (<= 0.23.10) only supports Q8_0 weights in embedding/gathering operations: there is no matmul or convolution kernel for it yet. Export requires tract >= 0.23.10; older targets warn and are rejected.
fp_to_tract_iq2_s
Quantize float tensor to tract supported IQ2_S (ggml reference).
Only use it on embedding weights (see QTensorTractIQ2_S).
Raises:
| Type | Description |
|---|---|
T2NErrorImpossibleQuantization
|
invalid dtype or shape, non finite
values, a super-block scale |
fp_to_tract_q4_k
Quantize float tensor to tract supported Q4_K (ggml reference).
Only use it on embedding weights (see QTensorTractQ4_K).
Raises:
| Type | Description |
|---|---|
T2NErrorImpossibleQuantization
|
invalid dtype or shape, non finite values, block scales that overflow f16, or that underflow it for weights not negligible against the tensor largest one. |
fp_to_tract_q5_k
Quantize float tensor to tract supported Q5_K (ggml reference).
Only use it on embedding weights (see QTensorTractQ5_K).
Raises:
| Type | Description |
|---|---|
T2NErrorImpossibleQuantization
|
invalid dtype or shape, non finite values, block scales that overflow f16, or that underflow it for weights not negligible against the tensor largest one. |
fp_to_tract_q6_k
Quantize float tensor to tract supported Q6_K (ggml reference).
Only use it on embedding weights (see QTensorTractQ6_K).
Raises:
| Type | Description |
|---|---|
T2NErrorImpossibleQuantization
|
invalid dtype or shape, non finite
values, a super-block scale |
fp_to_tract_q8_0_with_min_max_calibration
fp_to_tract_q8_0_with_min_max_calibration(fp_tensor: Tensor, percentile: float = 1.0) -> QTensorTractQ8_0
Min-Max method to quantize float tensor to tract supported Q8_0.
Block scale is absmax / 127 (ggml reference). With percentile < 1
each block is first clamped to its percentile absolute value.
Only use it on embedding weights (see QTensorTractQ8_0).
Raises:
| Type | Description |
|---|---|
T2NErrorImpossibleQuantization
|
invalid dtype or shape, non finite values, block scales that overflow f16, or that underflow it for weights not negligible against the tensor largest one. |
ggml_f16_to_bytes
(n,) f32 to (n, 2) u8: little endian f16 bytes (ggml_fp16_t).
ggml_f32
f32 scalar, to keep ggml f32 arithmetic on python constants.
ggml_first_absmax
Signed value of max |x| per row (first one on ties), and that |x|.
Explicit scan like ggml loops (argmax ties differ across platforms).
ggml_iter_blocks
Yield (start, f32 chunk (n, block_len)) of fp_tensor blocks.
Blocks follow the row-major order; only one chunk at a time is casted to f32 (bounds peak memory).
ggml_k_min_sub_weights
Weights of ggml K-quants make_qkx2_quants for (n, 32) sub-blocks.
ggml_make_qkx2_quants
ggml_make_qkx2_quants(x: Tensor, weights: Tensor, nmax: int, rmin: float, rdelta: float, nstep: int) -> T.Tuple[torch.Tensor, torch.Tensor, torch.Tensor]
Port of ggml make_qkx2_quants vectorized over rows of x (n, group).
Returns:
| Type | Description |
|---|---|
Tuple[Tensor, Tensor, Tensor]
|
(scale (n,), levels u8 (n, group) in [0, nmax], the_min (n,)) |
ggml_make_qx_quants
Port of ggml make_qx_quants (rmse_type 1) over rows of x.
Each value is weighted by its square.
Returns:
| Type | Description |
|---|---|
Tuple[Tensor, Tensor]
|
(scale (n,), levels u8 (n, group) in [0, 2 * nmax)) |
ggml_nearest_int
Port of ggml nearest_int (f32 mantissa trick, round half to even).
Exact like ggml for |x| <= 2**22 (ggml asserts it), and platform independent beyond, unlike a float to int32 cast.
ggml_pack_scale_min_k4
Pack 6bit (n, 8) sub-block scales and mins in ggml 12 bytes (n, 12).
Inverse of ggml get_scale_min_k4.
ggml_quant_iq2_s
IQ2_S super-blocks (ggml quantize_row_iq2_s_ref, no imatrix).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Tensor
|
fp32 (n, 256) super-blocks |
required |
Returns:
| Type | Description |
|---|---|
Tuple[Tensor, Tensor, Tensor]
|
(d f16 (n,), 4bit group scales u8 (n, 16), u8 codes (n, 256),
see |
ggml_quant_k_scales_mins
ggml_quant_k_scales_mins(x: Tensor, nmax: int, rmin: float, nstep: int) -> T.Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]
Q4_K/Q5_K super-block parameters (ggml quantize_row_q*_K_ref).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Tensor
|
fp32 (n, 256) super-blocks |
required |
|
int
|
maximum level (15 for Q4_K, 31 for Q5_K) |
required |
|
float
|
|
required |
|
int
|
|
required |
Returns:
| Type | Description |
|---|---|
Tuple[Tensor, Tensor, Tensor, Tensor]
|
(d f16 (n,), dmin f16 (n,), 6bit scales u8 (n, 8), 6bit mins u8 (n, 8)) |
ggml_quant_q6_k_scales
Q6_K super-block parameters (ggml quantize_row_q6_K_ref).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Tensor
|
fp32 (n, 256) super-blocks |
required |
Returns:
| Type | Description |
|---|---|
Tuple[Tensor, Tensor]
|
(d f16 (n,), i8 sub-block scales (n, 16)) |
ggml_seq_sum
f32 sum over last dim accumulated sequentially, like ggml loops.
torch.sum (pairwise) and CPU torch.cumsum (double accumulator)
round differently.
ggml_sqrt
Correctly rounded f32 square root (IEEE sqrtf), on every platform.
torch.sqrt is not: x86 builds compute it with MKL vector math, accurate
to about 1 ulp only, and its result depends on the CPU model. The f32
rounding of the f64 root is fixed up with exact f64 checks: the midpoint
of two consecutive f32 has at most 25 significant bits, so its f64 square
is exact (and never equals a f32, so there are no ties).