Skip to main content

trueno_quant/
lib.rs

1#![cfg_attr(
2    test,
3    allow(
4        clippy::expect_used,
5        clippy::unwrap_used,
6        clippy::disallowed_methods,
7        clippy::float_cmp,
8        clippy::panic,
9        clippy::cast_precision_loss
10    )
11)]
12//! K-Quantization formats for GGUF/APR model weights (Toyota Way: ONE source of truth)
13//!
14//! This crate provides quantization functions for converting F32 data to
15//! K-quantization formats (`Q4_K`, `Q5_K`, `Q6_K`). This is the ONLY implementation
16//! in the Sovereign AI Stack - aprender and realizar import from here.
17//!
18//! ## Stack Architecture (Toyota Way)
19//!
20//! ```text
21//!        ┌─────────┐
22//!        │ apr CLI │
23//!        └────┬────┘
24//!             │
25//!     ┌───────┼───────┬───────────┐
26//!     ▼       ▼       ▼           ▼
27//! ┌────────┐ ┌────────┐ ┌─────────┐
28//! │entrenar│ │aprender│ │realizar │
29//! └───┬────┘ └───┬────┘ └────┬────┘
30//!     │          │           │
31//!     └────┬─────┴───────────┴────┘
32//!          ▼
33//!       ┌────────────────┐
34//!       │  trueno-quant  │  ← YOU ARE HERE
35//!       └───────┬────────┘
36//!               ▼
37//!       ┌────────────────┐
38//!       │     trueno     │
39//!       └────────────────┘
40//! ```
41//!
42//! ## Format Specifications
43//!
44//! - `Q4_K`: 256-element super-blocks, 144 bytes (4.5 bits/weight)
45//! - `Q5_K`: 256-element super-blocks, 176 bytes (5.5 bits/weight)
46//! - `Q6_K`: 256-element super-blocks, 210 bytes (6.5 bits/weight)
47//!
48//! ## Usage
49//!
50//! ```rust
51//! use trueno_quant::{quantize_q4_k, dequantize_q4_k_to_f32};
52//!
53//! let data: Vec<f32> = (0..256).map(|i| i as f32 / 10.0).collect();
54//! let quantized = quantize_q4_k(&data);
55//! let restored = dequantize_q4_k_to_f32(&quantized, 256);
56//! ```
57
58#![warn(missing_docs)]
59
60mod dequantize;
61pub mod ggml_type;
62pub mod iq;
63mod quantize;
64mod transpose;
65
66#[cfg(test)]
67mod tests;
68
69#[cfg(test)]
70mod roundtrip_fidelity_tests;
71
72// Re-export all public functions so the public API doesn't change
73pub use dequantize::{dequantize_q4_k_to_f32, dequantize_q5_k_to_f32, dequantize_q6_k_to_f32};
74pub use quantize::{
75    quantize_q4_k, quantize_q4_k_matrix, quantize_q5_k, quantize_q5_k_matrix, quantize_q6_k,
76    quantize_q6_k_matrix,
77};
78pub use transpose::{transpose_q4k_for_matmul, transpose_q5k_for_matmul, transpose_q6k_for_matmul};
79// #3947: IQ4_NL / IQ3_S / IQ4_XS, so aprender-core can inspect IQ tensors.
80pub use iq::{dequantize_iq_to_f32, iq_block_layout, IqDequantError};
81
82// PMAT-3430: the one ggml tensor-type enum and its upstream-extracted table.
83// Re-exported at the crate root so a consumer writes `trueno_quant::GgmlType`
84// and never has to know which module it lives in.
85pub use ggml_type::{
86    GgmlFamily, GgmlType, GgmlTypeError, QuantTraits, ALL, GGML_TYPE_COUNT, TRAITS,
87};
88
89// ============================================================================
90// Constants
91// ============================================================================
92
93/// Minimum valid f16 normal value (~6.1e-5)
94/// Prevents NaN on round-trip through f16 encoding
95pub const F16_MIN_NORMAL: f32 = 6.1e-5;
96
97/// `Q4_K` super-block size (elements per block)
98pub const Q4_K_BLOCK_SIZE: usize = 256;
99
100/// `Q4_K` super-block byte size
101pub const Q4_K_BLOCK_BYTES: usize = 144;
102
103/// `Q5_K` super-block size (elements per block)
104pub const Q5_K_BLOCK_SIZE: usize = 256;
105
106/// `Q5_K` super-block byte size
107pub const Q5_K_BLOCK_BYTES: usize = 176;
108
109/// `Q6_K` super-block size (elements per block)
110pub const Q6_K_BLOCK_SIZE: usize = 256;
111
112/// `Q6_K` super-block byte size
113pub const Q6_K_BLOCK_BYTES: usize = 210;
114
115// THESE SIX CONSTANTS PREDATE `TRAITS` AND SAY THE SAME THING (PMAT-3430).
116// They are kept — they are public API — but they may no longer drift from the
117// upstream-extracted table: a mismatch is a COMPILE error, not a test failure.
118const _: () = {
119    assert!(Q4_K_BLOCK_SIZE == TRAITS[GgmlType::Q4K.as_id() as usize].blck_size as usize);
120    assert!(Q4_K_BLOCK_BYTES == TRAITS[GgmlType::Q4K.as_id() as usize].type_size as usize);
121    assert!(Q5_K_BLOCK_SIZE == TRAITS[GgmlType::Q5K.as_id() as usize].blck_size as usize);
122    assert!(Q5_K_BLOCK_BYTES == TRAITS[GgmlType::Q5K.as_id() as usize].type_size as usize);
123    assert!(Q6_K_BLOCK_SIZE == TRAITS[GgmlType::Q6K.as_id() as usize].blck_size as usize);
124    assert!(Q6_K_BLOCK_BYTES == TRAITS[GgmlType::Q6K.as_id() as usize].type_size as usize);
125};
126
127// ============================================================================
128// f16 Conversion Helpers
129// ============================================================================
130
131/// Convert f32 to f16 (using half crate)
132#[inline]
133#[must_use]
134pub fn f32_to_f16(value: f32) -> u16 {
135    half::f16::from_f32(value).to_bits()
136}
137
138/// Convert f16 to f32 (using half crate)
139#[inline]
140#[must_use]
141pub fn f16_to_f32(bits: u16) -> f32 {
142    half::f16::from_bits(bits).to_f32()
143}