Skip to content

torch_to_nnef.tensor.quant

Advanced QTensor (<= 8bits) with complex quant scheme non torch native.

Modules:

Name Description
base
qtract

tract quantization formats serialized as custom .dat items.

qtract_ggml

tract ggml reference block formats (Q8_0, K-quants, IQ formats).

Classes:

Name Description
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).

QScalePerGroupF16

f16 scale only per group.

QScaleQ8_0

Q8_0 f16 scale d per block of 32 (ggml block_q8_0).

QScheme
QTensor

Common interface for all Compressed storage.

QTensorTract

All QTensorTract implementations.

QTensorTractIQ2_S

Tract data format it serializes to: IQ2_S (ggml block_iq2_s).

QTensorTractQ2_0_T

Tract ternary weights: f16 scale and 32 two-bit codes per block.

QTensorTractQ4_K

Tract data format it serializes to: Q4_K (ggml block_q4_K).

QTensorTractQ5_K

Tract data format it serializes to: Q5_K (ggml block_q5_K).

QTensorTractQ6_K

Tract data format it serializes to: Q6_K (ggml block_q6_K).

QTensorTractQ8_0

Tract data format it serializes to: Q8_0 (ggml block_q8_0).

QTensorTractQ8_1

Tract data format it serializes to: Q8_1 (GGML style).

QTensorTractScaleOnly

Tract data format it serializes to: Q4_0.

U8Compressor

Abstract class to add u8 compression methods.

Functions:

Name Description
fp_to_tract_iq2_s

Quantize float tensor to tract supported IQ2_S (ggml reference).

fp_to_tract_q4_0_with_min_max_calibration

Min-Max method to quantize float tensor to tract supported Q4_0.

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.

fp_to_tract_q8_1_with_min_max_calibration

Min-Max method to quantize float tensor to tract supported Q8_1.

qscale_per_group_f16_min_max_calibration

Build QScalePerGroupF16 and calibrate requested float tensor.

ternary_to_tract_q2_0_t

Pack existing ternary weights, rounding only their scales to f16.

QScaleGGMLIQ2S

QScaleGGMLIQ2S(d: Tensor, scales: Tensor)

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 d * (0.5 + scale) * 0.25 like tract.

levels

levels(codes)

F32 signed grid magnitudes (multiplying by +-1 is exact).

quantize_blocks

quantize_blocks(x)

Codes of the ggml quantizer, checked against these parameters.

Raises:

Type Description
T2NErrorMisuse

x quantizes to other parameters.

sub_scales

sub_scales()

F32 group scales d * (0.5 + scale) * 0.25 like tract.

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 arguments
  • fit_blocks(x, **settings) -> (scheme, codes): ggml reference quantizer of f32 (n, 256) super-blocks
  • quantize_blocks(x) -> codes: codes of (n, 256) super-blocks with this scheme parameters
  • sub_scales(), optionally sub_offsets() and levels(codes)

Methods:

Name Description
calibrate

Fit ggml reference parameters and codes of fp_tensor.

dequantize

F32 sub_scales * levels - sub_offsets like tract, then cast.

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 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.

sub_scales

F32 (n, 256 // SUB_LEN) scale of each sub-block.

calibrate classmethod

calibrate(fp_tensor: Tensor, format_name: str, **settings) -> T.Tuple[QScaleGGMLK, torch.Tensor]

Fit ggml reference parameters and codes of fp_tensor.

Returns:

Type Description
Tuple[QScaleGGMLK, Tensor]

(scheme, u8 codes of fp_tensor shape)

Raises:

Type Description
T2NErrorImpossibleQuantization

on f16 overflow of a F16_PARAMS scale, or not negligible f16 underflow.

dequantize

dequantize(u8_tensor: Tensor, target_dtype)

F32 sub_scales * levels - sub_offsets like tract, then cast.

fit_blocks classmethod

fit_blocks(x: Tensor, **settings) -> T.Tuple[QScaleGGMLK, torch.Tensor]

Fit ggml reference parameters and u8 codes of (n, 256) blocks.

levels

levels(codes: Tensor) -> torch.Tensor

F32 levels of (n, 256 // SUB_LEN, SUB_LEN) u8 codes.

quantize_as_u8

quantize_as_u8(fp_tensor: Tensor) -> torch.Tensor

Codes of fp_tensor with these parameters.

quantize_blocks

quantize_blocks(x: Tensor) -> torch.Tensor

U8 codes (n, 256) of f32 (n, 256) blocks with these params.

sub_offsets

sub_offsets() -> T.Optional[torch.Tensor]

F32 (n, 256 // SUB_LEN) offset of each sub-block, if any.

sub_scales

sub_scales() -> torch.Tensor

F32 (n, 256 // SUB_LEN) scale of each sub-block.

QScaleGGMLK6

QScaleGGMLK6(d: Tensor, sc: Tensor)

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.

quantize_blocks

quantize_blocks(x)

Final ggml levels with the f16 rounded super-block scale.

QScaleGGMLKMin

QScaleGGMLKMin(d: Tensor, dmin: Tensor, sc: Tensor, m: Tensor, nmax: int, rmin: float, nstep: int)

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.

quantize_blocks

quantize_blocks(x)

Final ggml levels with the f16 rounded super-block scales.

QScalePerGroupF16

QScalePerGroupF16(group_size: int, scale: Tensor, n_bits: int, restricted_range: bool = False)

Bases: QScheme

f16 scale only per group.

Tract aligned using negative scales.

QScaleQ8_0

QScaleQ8_0(group_size: int, scale: Tensor, n_bits: int, restricted_range: bool = False)

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 d * q like tract, then cast.

dequantize

dequantize(u8_tensor, target_dtype)

F32 d * q like tract, then cast.

QScheme

Bases: ABC

Methods:

Name Description
to_device

Specific device handling.

to_device

to_device(new_device)

Specific device handling.

Each QScheme may implement support for specific device switching for internal quant/dequant (like GPU, ...) allowing faster computation

QTensor

QTensor(fp_tensor: Tensor, qscheme: QScheme, dequant_to_dtype=torch.float32, u8_compressors: Optional[List[U8Compressor]] = None)

Bases: OpaqueTensor

Common interface for all Compressed storage.

Methods:

Name Description
cpu

Move to host memory and stay quantized, as to("cpu") does.

cuda

Move to a CUDA device and stay quantized, as to(device) does.

to_device

Specific device handling.

write_in_file

Called at NNEF write time.

xpu

Move to an XPU device and stay quantized, as to(device) does.

cpu

cpu(memory_format=torch.preserve_format)

Move to host memory and stay quantized, as to("cpu") does.

Without this override the call reaches __torch_function__, which returns the dequantized torch.Tensor instead, so nn.Module.cpu cannot move a quantized parameter. memory_format is accepted for signature compatibility only; the packed codes keep their layout.

cuda

cuda(device=None, non_blocking=False, memory_format=torch.preserve_format)

Move to a CUDA device and stay quantized, as to(device) does.

device is a device, an index or None for the current CUDA device. non_blocking and memory_format are accepted for signature compatibility only.

to_device

to_device(new_device)

Specific device handling.

write_in_file

write_in_file(dirpath: Union[str, Path], label: str)

Called at NNEF write time.

Each specific inference engine format should implement the file dump prefered.

xpu

xpu(device=None, non_blocking=False, memory_format=torch.preserve_format)

Move to an XPU device and stay quantized, as to(device) does.

device is a device, an index or None for the current XPU device. non_blocking and memory_format are accepted for signature compatibility only.

QTensorTract

QTensorTract(fp_tensor: Tensor, qscheme: QScheme, dequant_to_dtype=torch.float32, u8_compressors: Optional[List[U8Compressor]] = None)

Bases: QTensor

All QTensorTract implementations.

QTensorTractIQ2_S

QTensorTractIQ2_S(*args, **kwargs)

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.

QTensorTractQ2_0_T

QTensorTractQ2_0_T(*args, **kwargs)

Bases: QTensorTractScalePerGroupF16

Tract ternary weights: f16 scale and 32 two-bit codes per block.

Use ternary_to_tract_q2_0_t to construct from existing ternary weights. Codes 0, 1 and 2 represent -scale, zero and +scale. Each block occupies 10 bytes, with four consecutive codes packed low bits first per byte. Export requires tract >= 0.23.11; older targets warn and are rejected.

QTensorTractQ4_K

QTensorTractQ4_K(*args, **kwargs)

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

QTensorTractQ5_K(*args, **kwargs)

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

QTensorTractQ6_K(*args, **kwargs)

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

QTensorTractQ8_0(*args, **kwargs)

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.

QTensorTractQ8_1

QTensorTractQ8_1(*args, **kwargs)

Bases: QTensorTractScalePerGroupF16

Tract data format it serializes to: Q8_1 (GGML style).

Each group of 32 values is stored as 36 bytes: f16 scale, f16 sum of dequantized values, then 32 int8.

Warning

tract (<= 0.23.10) only supports Q8_1 weights in embedding/gathering operations: there is no matmul or convolution kernel for it yet.

QTensorTractScaleOnly

QTensorTractScaleOnly(*args, specific_machine: Optional[str] = None, **kwargs)

Bases: QTensorTractScalePerGroupF16

Tract data format it serializes to: Q4_0.

Each group of 32 values is stored as 18 bytes: f16 scale, then 32 packed 4bit values.

Methods:

Name Description
decompress

Tract Q4_0 dequantization depends on hardware.

decompress

decompress()

Tract Q4_0 dequantization depends on hardware.

Typically dequantization happen with ops in f16 on ARM and f32 (scale directly casted) on others so we overwrite the function to be consistant with tract.

U8Compressor

Abstract class to add u8 compression methods.

This can be used to

Apply bitpack elements bellow 8bit Apply classic compression algorithm

Warning !! .shape of u8_tensor compressed must be same as .shape once decompressed

Methods:

Name Description
compress

Compress a u8 tensor (into u8).

decompress

Decompress an u8 torch tensor (into u8).

to_device

Specific device handling.

compress abstractmethod

compress(u8_tensor) -> torch.Tensor

Compress a u8 tensor (into u8).

Parameters:

Name Type Description Default

u8_tensor

tensor to be compressed with dtype torch.uint8

required

Return: compressed tensor with dtype torch.uint8

decompress abstractmethod

decompress(u8_tensor) -> torch.Tensor

Decompress an u8 torch tensor (into u8).

Parameters:

Name Type Description Default

u8_tensor

compressed tensor with dtype torch.uint8

required

Return: tensor decompressed with dtype torch.uint8

to_device

to_device(new_device)

Specific device handling.

Each compressor may implement support for specific device (like GPU, ...)

Allowing faster computation

fp_to_tract_iq2_s

fp_to_tract_iq2_s(fp_tensor: Tensor) -> QTensorTractIQ2_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 d that overflows f16, or that underflows it for weights not negligible against the tensor largest one.

fp_to_tract_q4_0_with_min_max_calibration

fp_to_tract_q4_0_with_min_max_calibration(fp_tensor, percentile: float = 1.0) -> QTensorTractScaleOnly

Min-Max method to quantize float tensor to tract supported Q4_0.

fp_to_tract_q4_k

fp_to_tract_q4_k(fp_tensor: Tensor) -> QTensorTractQ4_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

fp_to_tract_q5_k(fp_tensor: Tensor) -> QTensorTractQ5_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

fp_to_tract_q6_k(fp_tensor: Tensor) -> QTensorTractQ6_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 d that overflows f16, or that underflows it for weights not negligible against the tensor largest one.

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.

fp_to_tract_q8_1_with_min_max_calibration

fp_to_tract_q8_1_with_min_max_calibration(fp_tensor, percentile: float = 1.0) -> QTensorTractQ8_1

Min-Max method to quantize float tensor to tract supported Q8_1.

Only use it on embedding weights (see QTensorTractQ8_1).

qscale_per_group_f16_min_max_calibration

qscale_per_group_f16_min_max_calibration(fp_tensor: Tensor, n_bits: int, group_size: int, percentile: float = 1.0, restricted_range: bool = False) -> QScalePerGroupF16

Build QScalePerGroupF16 and calibrate requested float tensor.

Parameters:

Name Type Description Default

fp_tensor

Tensor

float tensor to calibrate.

required

n_bits

int

number of bits per quantized element.

required

group_size

int

number of elements sharing a scale.

required

percentile

float

absolute value percentile used as max per group.

1.0

restricted_range

bool

use [-(2(n_bits-1) - 1), 2(n_bits-1) - 1] instead of full range (GGML Q8 convention).

False
Return

Tuple( QScalePerGroupF16 qscheme, torch.Tensor[uint8] )

ternary_to_tract_q2_0_t

ternary_to_tract_q2_0_t(fp_tensor: Tensor) -> QTensorTractQ2_0_T

Pack existing ternary weights, rounding only their scales to f16.

Accepts floating tensors of rank 2 to 4 whose flattened rows are a multiple of 32. Each consecutive group of 32 must contain only zero and a single absolute nonzero value. Larger source groups (e.g. 128) naturally split into blocks of 32. All-zero blocks are supported.

Raises:

Type Description
T2NErrorImpossibleQuantization

Invalid shape, non-ternary values, or nonzero scales that overflow or underflow in f16.