quantization #
INT8 quantization
vtl.quantization provides opt-in affine signed INT8 conversion for f32/f64 tensors. Quantization parameters use
q = clamp(round_to_even(x / scale + zero_point), qmin, qmax)
x = (q - zero_point) * scale
The API includes per-tensor and per-channel parameters, finite-value min/max calibration observers, and explicit f32/f64 quantize/dequantize entry points. Quantized results are ordinary Tensor[i8] values. linear_int8_f32 provides a CPU inference path with per-tensor activation quantization, per-output-channel weight quantization, exact i64 accumulation, and f32 output with bias. Linear inference uses VSL's AVX2-dispatched INT16 dot product for reductions of at least 128 features on supported x86 CPUs, with a scalar fallback elsewhere. CUDA builds also provide linear_int8_f32_cuda(dev, ...), an explicit cuBLAS path that returns a CPU-resident f32 tensor. It pads GEMM dimensions and keeps integer accumulation exact, including reductions larger than INT32. This one-shot function transposes and uploads weights per call. For repeated inference, upload_quantized_linear_layer_cuda(dev, layer) returns a CudaQuantizedLinearLayer that retains the aligned INT8 weights on the device; call forward(input) for inference and release() when finished. The CPU QuantizedLinearLayer remains available for host inference. CUDA builds also provide conv2d_int8_f32_cuda(dev, ...), an explicit cuBLAS inference path for NCHW/OIHW tensors. It supports groups, padding, stride, and dilation; bounds its temporary im2col blocks to 64 MiB when one row fits; and returns a CPU-resident f32 tensor. This Conv2D path is one-shot and uploads weights for each GEMM call; unlike CUDA Linear, it does not yet retain weights across inference calls. Quantized Conv2D is available through conv2d_int8_f32 for NCHW/OIHW tensors, including groups, padding, stride, and dilation via QuantizedConv2DConfig. Layer conversion helpers quantize_linear_layer_f32 and quantize_conv2d_layer_f32 create forward-only inference wrappers from trained f32 weight/bias tensors and externally calibrated activation parameters. quantize_sequential_f32 converts a whole Sequential made of Linear, ReLU, and Sigmoid layers into a forward-only QuantizedSequential; unsupported layer types fail explicitly. Activation parameters are caller-supplied as one QuantizationParams per Linear layer, in forward order, so hidden activations with a different range from the network input are not clipped. The number of parameter sets must match the number of Linear layers, and forward validates the input feature count against the model's InputLayer. CUDA INT8 Linear and Conv2D are experimental explicit paths. Accelerator-backed whole-model conversion, further layer types, and performance parity remain open under issue #792.
See the runnable INT8 quantization example. The end-to-end f32-vs-INT8 latency and weight-payload benchmark is ../benchmarks/quantization_int8_bench.v; compile with -prod from ~/.vmodules and run the resulting binary separately under the memory limit documented in docs/DEV_LIGHTWEIGHT.md.
The benchmark runs [32, 256] x [512, 256] with two warmups and eight timed calls per process. It includes activation quantization and output allocation in the INT8 timing, while weights are quantized before timing as they would be for inference. It reports the maximum absolute difference from the f32 result and weight tensor payload plus per-channel metadata; bias and V object overhead are excluded. On an AMD Ryzen 9 5900X with V 0.5.2 (7f5b9a3) and GCC 16.2.1, three independent runs measured a median f32/INT8 latency ratio of 6.792x (per-run ratios 6.521x-6.864x), with maximum absolute error 0.015401. Weight payload was 524,288 bytes for f32 versus 131,072 bytes plus 8,192 bytes of per-channel metadata for INT8 (3.765x smaller including that metadata). This is one CPU, shape, and implementation only; it is not evidence of general PyTorch, NumPy, or accelerator performance parity.
The opt-in CUDA benchmark is ../benchmarks/quantization_int8_cuda_bench.v. On an NVIDIA GeForce RTX 3060 with V 0.5.2, three independent production runs of the same [32, 256] x [512, 256] workload measured median f32 latency 21.1657 ms, CPU INT8 latency 0.7157 ms, and CUDA INT8 latency 0.8749 ms. CUDA's maximum absolute error matched CPU INT8 at 0.015401, but the per-call transfers made it 1.22x slower than CPU INT8 on this small workload. These results are specific to this machine and shape; they do not establish a general GPU speedup.
The same benchmark accepts optional batch in_features out_features arguments. Across seven production runs of [128, 512] x [1024, 512], median f32, CPU INT8, and CUDA INT8 latencies were 56.467 ms, 6.7714 ms, and 4.4597 ms, respectively; CUDA was 1.52x faster than CPU INT8 at the median with the same 0.021986 maximum absolute error. CUDA timings ranged from 4.3181 to 9.7551 ms, so these host measurements show workload scaling, not a universal speedup.
The current CUDA benchmark additionally measures CudaQuantizedLinearLayer after its one-time device upload. Five production runs with three warmups and 24 timed calls measured the [32, 256] x [512, 256] workload at median 1.0820 ms for one-shot CUDA and 0.2312 ms for resident weights; CPU INT8 was 0.7181 ms. One resident run had a 2.0705 ms outlier (the other four ranged from 0.2296 to 0.2566 ms). For [128, 512] x [1024, 512], medians were 6.8626 ms one-shot, 1.6359 ms resident, and 8.7833 ms CPU INT8; resident timings ranged from 1.6126 to 1.7129 ms. Maximum absolute error versus f32 was unchanged at 0.015401 and 0.021986, respectively. Timing includes per-call activation quantization, allocations, transfers, and output conversion; resident-layer construction and its one-time weight upload are excluded. Results are specific to this RTX 3060 host and these shapes, and do not establish general accelerator parity.
Run reproducibly from ~/.vmodules:
systemd-run --user --scope --working-directory="$HOME/.vmodules" \
-p MemoryMax=2G -p MemorySwapMax=0 -p CPUQuota=200% -E VJOBS=1 -- \
v -no-parallel -prod -o /tmp/vtl-quantization-int8-bench \
./vtl/benchmarks/quantization_int8_bench.v
systemd-run --user --scope --working-directory="$HOME/.vmodules" \
-p MemoryMax=2G -p MemorySwapMax=0 -p CPUQuota=200% -- \
/tmp/vtl-quantization-int8-bench
The Conv2D benchmark is ../benchmarks/quantization_int8_conv2d_bench.v. It uses input [1, 8, 32, 32], weights [16, 8, 3, 3], padding 1, one warmup, and three timed calls. The CPU path packs each input patch once and reuses it across output channels. On the same Ryzen 9 5900X / V 0.5.2 / GCC 16.2.1 host, three independent runs had median f32 latency 0.8562 ms and INT8 latency 0.9818 ms (median per-run f32/INT8 ratio 0.857x; range 0.769x-0.924x), so INT8 remained slower on this shape. Maximum absolute error was 0.038690. Effective INT8 weight payload plus per-channel metadata was 1,408 bytes versus 4,608 bytes f32 (3.273x smaller, excluding bias and V object overhead). This reference CPU kernel is currently a storage/accuracy path, not a Conv2D speedup.
The opt-in CUDA comparison is ../benchmarks/quantization_int8_conv2d_cuda_bench.v. It compares CPU and one-shot CUDA INT8 Conv2D on the same deterministic [1, 8, 32, 32] input and [16, 8, 3, 3] weights, including quantization, im2col, transfer, output conversion, and allocation in each timed path. On an NVIDIA GeForce RTX 3060 with V 0.5.2 (7f5b9a3), seven 24-call process runs had median CPU and CUDA latencies of 2.6613 ms and 2.7184 ms (0.979x CPU/CUDA ratio; ranges 2.6276– 3.7435 ms and 2.5280–4.1102 ms, respectively). These noisy results show no repeatable speedup for this small one-shot workload. The CUDA output matched the CPU INT8 result exactly. Persistent CUDA Conv2D weights are not implemented.
systemd-run --user --scope --working-directory="$HOME/.vmodules" \
-p MemoryMax=2G -p MemorySwapMax=0 -p CPUQuota=200% -E VJOBS=1 -- \
v -d cuda -no-parallel -prod -o /tmp/vtl-quantization-int8-conv2d-cuda-bench \
./vtl/benchmarks/quantization_int8_conv2d_cuda_bench.v
systemd-run --user --scope --working-directory="$HOME/.vmodules" \
-p MemoryMax=2G -p MemorySwapMax=0 -p CPUQuota=200% -- \
/tmp/vtl-quantization-int8-conv2d-cuda-bench
systemd-run --user --scope --working-directory="$HOME/.vmodules" \
-p MemoryMax=2G -p MemorySwapMax=0 -p CPUQuota=200% -E VJOBS=1 -- \
v -no-parallel -prod -o /tmp/vtl-quantization-int8-conv2d-bench \
./vtl/benchmarks/quantization_int8_conv2d_bench.v
systemd-run --user --scope --working-directory="$HOME/.vmodules" \
-p MemoryMax=2G -p MemorySwapMax=0 -p CPUQuota=200% -- \
/tmp/vtl-quantization-int8-conv2d-bench
Run the CUDA benchmark from ~/.vmodules:
systemd-run --user --scope --working-directory="$HOME/.vmodules" \
-p MemoryMax=2G -p MemorySwapMax=0 -p CPUQuota=200% -E VJOBS=1 -- \
v -d cuda -no-parallel -prod -o /tmp/vtl-quantization-int8-cuda-bench \
./vtl/benchmarks/quantization_int8_cuda_bench.v
systemd-run --user --scope --working-directory="$HOME/.vmodules" \
-p MemoryMax=2G -p MemorySwapMax=0 -p CPUQuota=200% -- \
/tmp/vtl-quantization-int8-cuda-bench 128 512 1024
Per-channel conversion accepts an axis and one scale/zero point per channel. Negative axes are normalized against the tensor rank. Conversion traverses logical tensor order, including strided views, and returns a row-major tensor with the same shape. Non-finite calibration or input values are errors rather than silently saturating NaNs or infinities.
Validation
Run from ~/.vmodules with a local memory cap:
VJOBS=2 systemd-run --user --scope -p MemoryMax=4G -p MemorySwapMax=0 -- v test ./vtl/quantization
fn affine_params #
fn affine_params(minimum f64, maximum f64, qmin i8, qmax i8) !QuantizationParams
affine_params derives asymmetric affine parameters from a finite value range.
fn conv2d_int8_f32 #
fn conv2d_int8_f32(input &vtl.Tensor[f32], weights &vtl.Tensor[i8], input_params QuantizationParams, weight_params PerChannelParams, bias &vtl.Tensor[f32], kernel_size []int, config QuantizedConv2DConfig) !&vtl.Tensor[f32]
conv2d_int8_f32 runs a CPU affine-INT8 Conv2D operator and returns f32 values. Weights use one per-channel parameter set along output-channel axis 0.
fn conv2d_int8_f32_cuda #
fn conv2d_int8_f32_cuda(_dev voidptr, input &vtl.Tensor[f32], weights &vtl.Tensor[i8], input_params QuantizationParams, weight_params PerChannelParams, bias &vtl.Tensor[f32], kernel_size []int, config QuantizedConv2DConfig) !&vtl.Tensor[f32]
conv2d_int8_f32_cuda is unavailable unless VTL is built with -d cuda.
fn dequantize_per_channel_f32 #
fn dequantize_per_channel_f32(input &vtl.Tensor[i8], params PerChannelParams) !&vtl.Tensor[f32]
dequantize_per_channel_f32 converts signed INT8 values to f32 values.
fn dequantize_per_channel_f64 #
fn dequantize_per_channel_f64(input &vtl.Tensor[i8], params PerChannelParams) !&vtl.Tensor[f64]
dequantize_per_channel_f64 converts signed INT8 values to f64 values.
fn dequantize_per_tensor_f32 #
fn dequantize_per_tensor_f32(input &vtl.Tensor[i8], params QuantizationParams) !&vtl.Tensor[f32]
dequantize_per_tensor_f32 converts signed INT8 values to f32 values.
fn dequantize_per_tensor_f64 #
fn dequantize_per_tensor_f64(input &vtl.Tensor[i8], params QuantizationParams) !&vtl.Tensor[f64]
dequantize_per_tensor_f64 converts signed INT8 values to f64 values.
fn linear_int8_f32 #
fn linear_int8_f32(input &vtl.Tensor[f32], weights &vtl.Tensor[i8], input_params QuantizationParams, weight_params PerChannelParams, bias &vtl.Tensor[f32]) !&vtl.Tensor[f32]
linear_int8_f32 runs a CPU affine-INT8 linear operator and returns f32 values. Weights use one per-channel parameter set along output-feature axis 0.
fn linear_int8_f32_cuda #
fn linear_int8_f32_cuda(_dev voidptr, input &vtl.Tensor[f32], weights &vtl.Tensor[i8], input_params QuantizationParams, weight_params PerChannelParams, bias &vtl.Tensor[f32]) !&vtl.Tensor[f32]
linear_int8_f32_cuda is unavailable unless VTL is built with -d cuda.
fn new_params #
fn new_params(scale f64, zero_point int, qmin i8, qmax i8) !QuantizationParams
new_params validates and creates signed INT8 affine quantization parameters.
fn new_per_channel_min_max_observer #
fn new_per_channel_min_max_observer(axis int) PerChannelMinMaxObserver
new_per_channel_min_max_observer creates a per-channel calibration observer.
fn new_per_channel_params #
fn new_per_channel_params(scales []f64, zero_points []int, axis int, qmin i8, qmax i8) !PerChannelParams
new_per_channel_params validates per-channel INT8 affine parameters.
fn quantize_conv2d_layer_f32 #
fn quantize_conv2d_layer_f32(weights &vtl.Tensor[f32], bias &vtl.Tensor[f32], input_params QuantizationParams, kernel_size []int, config QuantizedConv2DConfig, qmin i8, qmax i8) !&QuantizedConv2DLayer
quantize_conv2d_layer_f32 converts trained f32 Conv2D weights and bias for INT8 inference.
fn quantize_linear_layer_f32 #
fn quantize_linear_layer_f32(weights &vtl.Tensor[f32], bias &vtl.Tensor[f32], input_params QuantizationParams, qmin i8, qmax i8) !&QuantizedLinearLayer
quantize_linear_layer_f32 converts trained f32 weights and bias for INT8 inference.
fn quantize_per_channel_f32 #
fn quantize_per_channel_f32(input &vtl.Tensor[f32], params PerChannelParams) !&vtl.Tensor[i8]
quantize_per_channel_f32 applies one scale and zero point per selected channel.
fn quantize_per_channel_f64 #
fn quantize_per_channel_f64(input &vtl.Tensor[f64], params PerChannelParams) !&vtl.Tensor[i8]
quantize_per_channel_f64 applies one scale and zero point per selected channel.
fn quantize_per_tensor_f32 #
fn quantize_per_tensor_f32(input &vtl.Tensor[f32], params QuantizationParams) !&vtl.Tensor[i8]
quantize_per_tensor_f32 maps finite f32 values into signed INT8 values.
fn quantize_per_tensor_f64 #
fn quantize_per_tensor_f64(input &vtl.Tensor[f64], params QuantizationParams) !&vtl.Tensor[i8]
quantize_per_tensor_f64 maps finite f64 values into signed INT8 values.
fn quantize_sequential_f32 #
fn quantize_sequential_f32(nn &models.Sequential[f32], layer_input_params []QuantizationParams,
qmin i8, qmax i8) !&QuantizedSequential
quantize_sequential_f32 converts supported layers in order. InputLayer entries are skipped; any other layer type fails explicitly rather than being silently dropped or executed on CPU. layer_input_params must have one entry per LinearLayer, in forward order.
fn QuantizedStepKind.from #
fn QuantizedStepKind.from[W](input W) !QuantizedStepKind
from returns the QuantizedStepKind value of an integer or of a field name, or an error if there is none.
enum QuantizedStepKind #
enum QuantizedStepKind {
linear
relu
sigmoid
}
QuantizedStepKind identifies one replayable inference step.
struct MinMaxObserver #
struct MinMaxObserver {
pub mut:
minimum f64
maximum f64
initialized bool
}
MinMaxObserver accumulates finite scalar range statistics for calibration.
fn (MinMaxObserver) observe_f32 #
fn (mut observer MinMaxObserver) observe_f32(input &vtl.Tensor[f32]) !
observe_f32 adds finite f32 tensor values to the calibration range.
fn (MinMaxObserver) observe_f64 #
fn (mut observer MinMaxObserver) observe_f64(input &vtl.Tensor[f64]) !
observe_f64 adds finite f64 tensor values to the calibration range.
fn (MinMaxObserver) params #
fn (observer &MinMaxObserver) params(qmin i8, qmax i8) !QuantizationParams
params derives affine quantization parameters from observed values.
struct PerChannelMinMaxObserver #
struct PerChannelMinMaxObserver {
pub:
axis int
pub mut:
minimums []f64
maximums []f64
initialized []bool
}
PerChannelMinMaxObserver accumulates independent ranges along one tensor axis.
fn (PerChannelMinMaxObserver) observe_f32 #
fn (mut observer PerChannelMinMaxObserver) observe_f32(input &vtl.Tensor[f32]) !
observe_f32 adds finite f32 values to matching channel ranges.
fn (PerChannelMinMaxObserver) observe_f64 #
fn (mut observer PerChannelMinMaxObserver) observe_f64(input &vtl.Tensor[f64]) !
observe_f64 adds finite f64 values to matching channel ranges.
fn (PerChannelMinMaxObserver) params #
fn (observer &PerChannelMinMaxObserver) params(qmin i8, qmax i8) !PerChannelParams
params derives one affine parameter set per observed channel.
struct PerChannelParams #
struct PerChannelParams {
pub:
scales []f64
zero_points []int
axis int
qmin i8 = -128
qmax i8 = 127
}
PerChannelParams stores one affine scale and zero point for each channel.
struct QuantizationParams #
struct QuantizationParams {
pub:
scale f64
zero_point int
qmin i8 = -128
qmax i8 = 127
}
QuantizationParams describes affine signed INT8 quantization.
struct QuantizedConv2DConfig #
struct QuantizedConv2DConfig {
pub:
padding []int = [0, 0]
stride []int = [1, 1]
dilation []int = [1, 1]
groups int = 1
}
QuantizedConv2DConfig describes NCHW/OIHW convolution geometry.
struct QuantizedConv2DLayer #
struct QuantizedConv2DLayer {
pub:
weights &vtl.Tensor[i8]
weight_params PerChannelParams
input_params QuantizationParams
bias &vtl.Tensor[f32]
kernel_size []int
config QuantizedConv2DConfig
}
QuantizedConv2DLayer is a forward-only INT8 Conv2D inference layer.
fn (QuantizedConv2DLayer) forward #
fn (layer &QuantizedConv2DLayer) forward(input &vtl.Tensor[f32]) !&vtl.Tensor[f32]
forward runs the quantized Conv2D operation without autograd.
struct QuantizedLinearLayer #
struct QuantizedLinearLayer {
pub:
weights &vtl.Tensor[i8]
weight_params PerChannelParams
input_params QuantizationParams
bias &vtl.Tensor[f32]
}
QuantizedLinearLayer is a forward-only INT8 Linear inference layer.
fn (QuantizedLinearLayer) forward #
fn (layer &QuantizedLinearLayer) forward(input &vtl.Tensor[f32]) !&vtl.Tensor[f32]
forward runs the quantized Linear operation without autograd.
struct QuantizedSequential #
struct QuantizedSequential {
pub:
steps []QuantizedStep
input_features int = -1
}
QuantizedSequential is a forward-only INT8 inference model converted from an f32 Sequential containing Linear, ReLU, and Sigmoid layers. Each Linear boundary carries its own calibrated activation parameters, because hidden ranges can differ substantially from the network input range.
fn (QuantizedSequential) step_count #
fn (q &QuantizedSequential) step_count() int
step_count reports the number of converted inference steps.
fn (QuantizedSequential) forward #
fn (q &QuantizedSequential) forward(input &vtl.Tensor[f32]) !&vtl.Tensor[f32]
forward runs the converted model on CPU-resident f32 tensors. Activations use the calibrated parameters of the Linear boundary being executed.
struct QuantizedStep #
struct QuantizedStep {
pub:
kind QuantizedStepKind
linear &QuantizedLinearLayer = unsafe { nil }
}
QuantizedStep holds a converted Linear layer or an activation.
- README
- fn affine_params
- fn conv2d_int8_f32
- fn conv2d_int8_f32_cuda
- fn dequantize_per_channel_f32
- fn dequantize_per_channel_f64
- fn dequantize_per_tensor_f32
- fn dequantize_per_tensor_f64
- fn linear_int8_f32
- fn linear_int8_f32_cuda
- fn new_params
- fn new_per_channel_min_max_observer
- fn new_per_channel_params
- fn quantize_conv2d_layer_f32
- fn quantize_linear_layer_f32
- fn quantize_per_channel_f32
- fn quantize_per_channel_f64
- fn quantize_per_tensor_f32
- fn quantize_per_tensor_f64
- fn quantize_sequential_f32
- fn QuantizedStepKind.from
- enum QuantizedStepKind
- struct MinMaxObserver
- struct PerChannelMinMaxObserver
- struct PerChannelParams
- struct QuantizationParams
- struct QuantizedConv2DConfig
- struct QuantizedConv2DLayer
- struct QuantizedLinearLayer
- struct QuantizedSequential
- struct QuantizedStep