Skip to content

torch_to_nnef.tensor.quant.qtract

tract quantization formats serialized as custom .dat items.

QTensorTractDat is the base of every tract custom .dat format: offload state, tract version gate and .dat writing workflow, with no assumption on the serialized layout.

QTensorTractBlockQuant is the base of every ggml style block format: its u8 storage holds one quantized code per value, its qscheme the block parameters as torch tensors, and tract bytes are only packed when written. This module holds the formats with one f16 scale per block of 32 values (Q4_0, Q8_1, Q2_0_T, QScalePerGroupF16 that a torch calibration sets: min max, percentile, or external methods like GPTQ). Formats whose calibration reproduces a llama.cpp reference quantizer (Q8_0, K-quants, IQ formats) live in qtract_ggml.

Classes:

Name Description
QTensorTract

All QTensorTract implementations.

QTensorTractBlockQuant

Common base of tract (ggml style) block quantization formats.

QTensorTractDat

Common base of QTensor serialized as tract custom .dat item types.

QTensorTractQ2_0_T

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

QTensorTractQ8_1

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

QTensorTractScaleOnly

Tract data format it serializes to: Q4_0.

QTensorTractScalePerGroupF16

Common base of formats with one f16 scale per block of 32 codes.

Functions:

Name Description
check_block_quant_input

Reject weights a tract block quantization format can not store.

check_f16_scales

Reject f16 rounded block scales out of f16 range.

fp_to_tract_q4_0_with_min_max_calibration

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

fp_to_tract_q8_1_with_min_max_calibration

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

ternary_to_tract_q2_0_t

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

QTensorTract

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

Bases: QTensor

All QTensorTract implementations.

QTensorTractBlockQuant

QTensorTractBlockQuant(*args, **kwargs)

Bases: QTensorTractDat

Common base of tract (ggml style) block quantization formats.

Values are split in blocks of BLOCK_LEN consecutive values (in row-major order), each serialized as BLOCK_BYTES bytes.

The u8 storage holds one quantized code per value (same shape as the float tensor) and the qscheme holds the block parameters (scales, mins, ...) as torch tensors. tract bytes are only made when written, by _pack_blocks.

Subclass contract
  • OFFLOAD_STATE_TAG, FORMAT_NAME, MIN_TRACT_VERSION
  • BLOCK_LEN, BLOCK_BYTES: serialized block layout
  • QSCHEME_CLS: its qscheme class, checked by _check_qscheme (QScalePerGroupF16 by default: one f16 scale per block of N_BITS codes)
  • _item_type(inference_target): tract .dat item type
  • _block_params(qscheme, n_blocks): qscheme tensors with a leading n_blocks dimension, sliced per chunk of blocks
  • _pack_blocks(codes, params, inference_target): pack u8 codes (n, BLOCK_LEN) and their params chunk into u8 (n, BLOCK_BYTES)

Methods:

Name Description
data_size_bytes

Serialized size of a tensor of shape.

data_size_bytes classmethod

data_size_bytes(shape: Tuple[int, ...]) -> int

Serialized size of a tensor of shape.

QTensorTractDat

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

Bases: QTensorTract, SupportsOffloadState

Common base of QTensor serialized as tract custom .dat item types.

It handles offload state, tract version gating and the .dat file writing workflow. Subclasses implement _write_binary_dat_from_qtensor_parts which dumps header and content from a (decompressed) u8 storage and its qscheme.

It makes no assumption on the serialized layout (block quantization, vector quantization codebooks, ...): each format computes its own .dat data size. Subclasses set decompressed_shape to the float tensor shape at construction. Their u8 storage layout is format specific: numel must stay the float tensor one.

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.

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.

QTensorTractScalePerGroupF16

QTensorTractScalePerGroupF16(*args, **kwargs)

Bases: QTensorTractBlockQuant

Common base of formats with one f16 scale per block of 32 codes.

Its qscheme is a QScalePerGroupF16 (Q4_0, Q8_1, Q2_0_T) that a torch calibration sets: min max, percentile, or external methods like GPTQ.

check_block_quant_input

check_block_quant_input(fp_tensor: Tensor, block_len: int, format_name: str) -> None

Reject weights a tract block quantization format can not store.

tract reads block quantized .dat as shape[0] rows of prod(shape[1:]) values split in blocks of block_len.

Raises:

Type Description
T2NErrorImpossibleQuantization

non floating, empty, rank not in 2..4, prod(shape[1:]) not a multiple of block_len or non finite values.

check_f16_scales

check_f16_scales(scales: Tensor, format_name: str, nonzero_mask: Optional[Tensor] = None, scale_name: str = 'scale') -> None

Reject f16 rounded block scales out of f16 range.

Parameters:

Name Type Description Default

scales

Tensor

block scales already rounded to f16.

required

format_name

str

format named in the error message.

required

nonzero_mask

Optional[Tensor]

same shape as scales, True where the scale represents nonzero weights. When given, such scales rounded to 0 are rejected (f16 underflow would erase those weights).

None

scale_name

str

scale named in the error message.

'scale'

Raises:

Type Description
T2NErrorImpossibleQuantization

on f16 overflow (inf) or underflow.

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

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.