kvquant

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 3 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package kvquant implements a pure-Go CPU reference for NVFP4 and MXFP4 KV-cache quantization and single-query decode attention.

The package models the microscaling FP4 numerics used by Blackwell block-scaled Tensor Cores without requiring a GPU or cgo:

  • NVFP4: 16-element blocks of E2M1 values with an 8-bit FP8 E4M3 scale.
  • MXFP4: 32-element blocks of E2M1 values with an 8-bit E8M0 power-of-two scale.
  • Dual-residual query quantization: represents the query as the sum of two FP4 blocks, quantizing the first term's rounding residual.
  • Underflow-aware probability scaling: folds a constant factor c = 8 into the online-softmax exponent and selects scale divisor 2 instead of 6 for small probability blocks (max(p) <= tau/c, tau = 21/1024), preventing E4M3 scales from flushing to zero when max(p) < 6*2^-10.
  • Outlier-aware key quantization: combines static per-channel mean subtraction, normalized Walsh-Hadamard rotation, and per-block scale search (Four-Over-Six for NVFP4, adjacent exponents for MXFP4).
  • FP64 reference attention (AttentionFP64) for evaluating quantization error on CPU.

This package is CPU-only; it does not load a CUDA driver or execute device kernels.

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Example
package main

import (
	"fmt"
	"math"

	"github.com/tmc/lib/nvidia/x/nn/kvquant"
)

func main() {
	const (
		n = 16
		d = 16
	)
	q := make([]float32, d)
	k := make([]float32, n*d)
	v := make([]float32, n*d)
	for j := 0; j < d; j++ {
		q[j] = 1.0
	}
	for i := 0; i < n; i++ {
		for j := 0; j < d; j++ {
			k[i*d+j] = float32(i%4) * 0.25
			v[i*d+j] = float32(i) * 0.1
		}
	}

	ref, err := kvquant.AttentionFP64(q, k, v, n, d)
	if err != nil {
		panic(err)
	}
	out, err := kvquant.DecodeAttention(q, k, v, n, d, kvquant.DefaultAttentionConfig(kvquant.NVFP4))
	if err != nil {
		panic(err)
	}
	fmt.Printf("ok=%v\n", math.Abs(float64(out[0])-ref[0]) < 0.05)
}
Output:
ok=true

Index

Examples

Constants

View Source
const (
	// DefaultProbScaleC is the constant factor c = 8 folded into the online
	// softmax exponent (log2(8) = 3) to lift NVFP4 probability block scales
	// above the E4M3 subnormal floor.
	DefaultProbScaleC = 8.0

	// DefaultProbScaleTau is the calibrated threshold (21/1024, E4M3 code 10/11
	// midpoint) below which c*max(p_b) uses scale divisor 2 instead of 6.
	DefaultProbScaleTau = 21.0 / 1024.0
)

Variables

This section is empty.

Functions

func AttentionFP64

func AttentionFP64(q, k, v []float32, n, d int) ([]float64, error)

AttentionFP64 computes exact single-query decode attention in float64:

out = softmax((q @ K^T) / sqrt(d)) @ V

q has length d; k and v are row-major [n, d] slices of length n*d.

func DecodeAttention

func DecodeAttention(q, k, v []float32, n, d int, cfg AttentionConfig) ([]float32, error)

DecodeAttention runs quantized single-query decode attention on CPU using cfg.

q has length d; k and v are row-major [n, d] slices of length n*d. d must be a positive multiple of cfg.Format.BlockSize(); when cfg.Hadamard is true, d must also be a power of two. The quantized prefix length qEnd = n - RecentTokens (when larger than SinkTokens) must be a multiple of cfg.Format.BlockSize().

func DecodeE2M1

func DecodeE2M1(code uint8) float32

DecodeE2M1 decodes the low 4 bits of code to its exact float32 value.

func DecodeE4M3Scale

func DecodeE4M3Scale(code uint8) (float32, error)

DecodeE4M3Scale decodes an unsigned FP8 E4M3FN scale byte. It rejects NaN (0x7F, 0xFF) and negative non-zero scale bytes.

func DecodeE8M0Scale

func DecodeE8M0Scale(code uint8) (float32, error)

DecodeE8M0Scale decodes an OCP E8M0 scale byte to 2^(code-127). Code 0xFF is the E8M0 NaN sentinel and returns an error.

func EncodeE2M1

func EncodeE2M1(x float32) uint8

EncodeE2M1 encodes x to a 4-bit E2M1 code using round-to-nearest-even with saturation at +/-6 (matching PTX cvt.rn.satfinite.e2m1x2.f32).

Bit 3 is the sign bit; bits 0..2 index the magnitude grid {0, 0.5, 1, 1.5, 2, 3, 4, 6}. Midpoints between adjacent codes break ties toward the even code (0.25 -> 0, 0.75 -> 1, 1.25 -> 1, 1.75 -> 2, 2.5 -> 2, 3.5 -> 4, 5.0 -> 4). NaN maps to 0.

func EncodeE4M3Scale

func EncodeE4M3Scale(x float32) uint8

EncodeE4M3Scale encodes a non-negative block scale to an unsigned FP8 E4M3FN byte using round-to-nearest-even with saturation at 448 (matching cvt.rn.satfinite.e4m3x2.f32).

Values at or below 2^-10 (half the smallest subnormal 2^-9) round to 0x00. Non-positive values and NaN return 0x00.

func EncodeE8M0Scale

func EncodeE8M0Scale(exp int) uint8

EncodeE8M0Scale encodes a power-of-two exponent exp (representing 2^exp) as an OCP E8M0 byte (exp + 127), saturating exp to [-127, 127].

func Hadamard

func Hadamard(src []float32) ([]float32, error)

Hadamard returns the normalized Sylvester Walsh-Hadamard transform of src.

len(src) must be a positive power of two. The transform is orthogonal (H^T H = I), so Hadamard(q) . Hadamard(k) == q . k up to floating-point rounding, while dispersing single-channel outliers across all coordinates.

func MeanKeys

func MeanKeys(k []float32, n, d int) ([]float32, error)

MeanKeys computes the per-channel mean of n key vectors of dimension d stored row-major in k (length n*d), for static key smoothing.

Types

type AttentionConfig

type AttentionConfig struct {
	Format         Format
	TileSize       int             // key tile size Bk (multiple of Format.BlockSize(); 0 defaults to 64)
	KeyMean        []float32       // optional static per-channel key mean mu_k (len == d)
	Hadamard       bool            // apply normalized Walsh-Hadamard rotation to Q and smoothed K
	KeyScaleSearch bool            // use Four-Over-Six (NVFP4) or adjacent-exponent (MXFP4) on K
	DualQuery      bool            // use dual-residual query quantization
	ProbScale      ProbScaleConfig // NVFP4 underflow-aware probability scaling
	// SinkTokens retains leading positions [0, min(n, SinkTokens)) in BF16
	// instead of FP4, modeling attention-sink retention. 0 disables it.
	SinkTokens int
	// RecentTokens retains trailing positions [max(SinkTokens, n-RecentTokens), n)
	// in BF16 instead of FP4, modeling an unpromoted recent tail window.
	// 0 disables it (all non-sink positions are quantized in FP4).
	RecentTokens int
}

AttentionConfig configures quantized single-head decode attention.

func DefaultAttentionConfig

func DefaultAttentionConfig(format Format) AttentionConfig

DefaultAttentionConfig returns the full BitDecoding-FP4 recipe for format.

type Block

type Block struct {
	Format Format
	Len    int
	Packed []byte
	Scales []uint8
}

Block holds microscaled E2M1 data and its per-block scale bytes.

Packed stores two 4-bit E2M1 nibbles per byte: the low nibble holds the even element (2*i) and the high nibble holds the odd element (2*i + 1). Scales holds one FP8 E4M3 byte per 16 elements for NVFP4, or one E8M0 byte per 32 elements for MXFP4.

func QuantizeMXFP4

func QuantizeMXFP4(src []float32) (Block, error)

QuantizeMXFP4 quantizes src into 32-element MXFP4 blocks using the OCP E8M0 scale rule e = floor(log2(amax)) - 2.

len(src) must be a positive multiple of 32 and all elements must be finite. An all-zero block receives scale code 0x00 (2^-127) and all-zero nibbles.

func QuantizeMXFP4Search

func QuantizeMXFP4Search(src []float32) (Block, error)

QuantizeMXFP4Search quantizes src into 32-element MXFP4 blocks using adjacent-exponent block-scale search: for each block, it evaluates 2^e_ocp and 2^(e_ocp+1) and selects the one with lower squared reconstruction error (ties keep e_ocp).

func QuantizeNVFP4

func QuantizeNVFP4(src []float32) (Block, error)

QuantizeNVFP4 quantizes src into 16-element NVFP4 blocks using the standard scale rule s = amax / 6 encoded in FP8 E4M3.

len(src) must be a positive multiple of 16 and all elements must be finite. An all-zero block receives scale 0x00 and all-zero nibbles.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/nn/kvquant"
)

func main() {
	src := make([]float32, 16)
	for i := range src {
		src[i] = float32(i-8) * 0.5
	}
	b, err := kvquant.QuantizeNVFP4(src)
	if err != nil {
		panic(err)
	}
	got, err := b.Dequantize()
	if err != nil {
		panic(err)
	}
	fmt.Printf("format=%s blocks=%d len=%d\n", b.Format, len(b.Scales), len(got))
}
Output:
format=nvfp4 blocks=1 len=16

func QuantizeNVFP4Search

func QuantizeNVFP4Search(src []float32) (Block, error)

QuantizeNVFP4Search quantizes src into 16-element NVFP4 blocks using Four-Over-Six block-scale search: for each block, it evaluates the E4M3 scales for divisors 6 and 4 and selects the one with lower squared reconstruction error (ties keep 6).

func QuantizeProbsNVFP4

func QuantizeProbsNVFP4(p []float32, cfg ProbScaleConfig) (Block, error)

QuantizeProbsNVFP4 quantizes unnormalized softmax probabilities p (where p[i] = exp2(S[i] - m) >= 0) into 16-element NVFP4 blocks using underflow-aware scaling.

Each probability is scaled by c (default 8) before quantization, and each 16-element block uses scale divisor kappa = 2 when c*max(p_b) <= tau (default 21/1024), or kappa = 6 otherwise. The returned block represents c*p; the constant factor c cancels during softmax normalization o / l.

func (Block) Dequantize

func (b Block) Dequantize() ([]float32, error)

Dequantize unpacks b into a new float32 slice of length b.Len.

type DualQuery

type DualQuery struct {
	First  Block
	Second Block
}

DualQuery holds a dual-residual FP4 query representation: First approximates q, and Second approximates the residual q - Dequantize(First).

func QuantizeDualQuery

func QuantizeDualQuery(q []float32, format Format) (DualQuery, error)

QuantizeDualQuery quantizes q into two FP4 blocks whose sum approximates q.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/nn/kvquant"
)

func main() {
	q := make([]float32, 16)
	q[0] = 6.0
	for i := 1; i < 16; i++ {
		q[i] = 0.35
	}
	dq, err := kvquant.QuantizeDualQuery(q, kvquant.NVFP4)
	if err != nil {
		panic(err)
	}
	q1, _ := dq.First.Dequantize()
	q2, _ := dq.Second.Dequantize()
	fmt.Printf("single=%.2f dual=%.2f\n", q1[1], q1[1]+q2[1])
}
Output:
single=0.50 dual=0.35

type Format

type Format uint8

Format selects a 4-bit microscaling format.

const (
	// NVFP4 uses 16-element E2M1 blocks with 8-bit FP8 E4M3 scales.
	NVFP4 Format = iota
	// MXFP4 uses 32-element E2M1 blocks with 8-bit E8M0 power-of-two scales.
	MXFP4
)

func (Format) BlockSize

func (f Format) BlockSize() int

BlockSize returns the number of E2M1 elements per scale block (16 for NVFP4, 32 for MXFP4), or 0 for an unknown format.

func (Format) String

func (f Format) String() string

String returns the canonical name of f.

type ProbScaleConfig

type ProbScaleConfig struct {
	// C is the multiplier folded into the softmax exponent.
	// Values <= 0 default to DefaultProbScaleC (8). Set C = 1 to disable.
	C float32
	// Tau is the c*max(p_b) threshold for selecting divisor 2 instead of 6.
	// Values <= 0 default to DefaultProbScaleTau (21/1024).
	Tau float32
	// DisableAdaptiveKappa disables the divisor-2 rule, always using divisor 6.
	DisableAdaptiveKappa bool
}

ProbScaleConfig configures underflow-aware NVFP4 probability scaling. Zero values for C and Tau select DefaultProbScaleC and DefaultProbScaleTau.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL