Documentation
¶
Overview ¶
Package calibrate implements post-training NVFP4 and INT4 weight and activation calibration, NVIDIA ModelOpt safetensors export, exact float64 teacher-forced perplexity and KL-divergence evaluation, and VRAM/latency reporting.
Calibration supports four methods selected by Method:
- MethodAbsMax: block or group maximum scaling (baseline).
- MethodMSE: Four-Over-Six (4/6) and clip-ratio grid search minimizing per-block reconstruction error (or activation-weighted error when ActStats is supplied).
- MethodAWQ: activation-aware per-channel scaling s_j = rms(x_j)^alpha grid-searched over alpha in [0, 1] to minimize output error.
- MethodSmoothQuant: per-channel outlier migration s_j = max(|X_j|)^alpha / max(|W_j|)^(1-alpha) for W4A16 and W4A4 paths.
Output formats are selected by Format: FormatNVFP4 produces two-level E2M1 + unsigned FP8 E4M3 per-16 block scale + FP32 tensor scale weights compatible with quant.NVFP4Weight and ckpt.ReadNVFP4Linear; FormatINT4 produces symmetric signed 4-bit group-wise weights (INT4Weight).
Evidence Discipline ¶
Analytical VRAM summaries are labeled EvidenceDerived. On a host without a native GPU run, UnmeasuredLatency reports EvidenceUnmeasured and HardwareLatencyStatus wraps cuda.ErrHardwarePending. Only an env-gated GPU execution under gpu-lock produces EvidenceMeasured device timings.
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/quant/calibrate"
)
func main() {
const outFeatures, inFeatures = 16, 64
weights := make([]float32, outFeatures*inFeatures)
for i := range weights {
weights[i] = float32(math.Sin(float64(i)*0.17) * 0.5)
}
stats, err := calibrate.NewActStats(inFeatures)
if err != nil {
panic(err)
}
act := make([]float32, inFeatures)
for i := range act {
act[i] = 1.0
}
act[0] = 50.0 // salient outlier channel
if err := stats.Observe(act); err != nil {
panic(err)
}
layer, err := calibrate.CalibrateLinear(weights, outFeatures, inFeatures, stats, act, calibrate.Config{
Method: calibrate.MethodAWQ,
Format: calibrate.FormatNVFP4,
RequireMMAAlign: true,
})
if err != nil {
panic(err)
}
fmt.Printf("format=%s shape=%dx%d compression>3x=%v\n",
layer.Format, layer.OutFeatures, layer.InFeatures, layer.CompressionRatio > 3.0)
}
Output: format=nvfp4 shape=16x64 compression>3x=true
Index ¶
- Constants
- func HardwareLatencyStatus(b LatencyBench) error
- func WriteModelOptNVFP4(dir string, layers map[string]*CalibratedLinear) error
- func WriteQualityPairFiles(baseW, candW io.Writer, scores []ItemScore, metric string) error
- func WriteQualityPairJSONL(w io.Writer, scores []ItemScore, metric string) error
- type ActStats
- type CalibratedLinear
- type Config
- type EvalResult
- type Format
- type INT4Weight
- type ItemScore
- type LatencyBench
- type LogitStepper
- type Method
- type MethodComparison
- type PipelineReport
- type VRAMSummary
Examples ¶
Constants ¶
const ( EvidenceMeasured = "MEASURED" EvidenceDerived = "DERIVED" EvidenceGenerated = "GENERATED" EvidenceUnmeasured = "UNMEASURED" )
Provenance labels separating measured hardware data from analytical or synthetic figures.
Variables ¶
This section is empty.
Functions ¶
func HardwareLatencyStatus ¶
func HardwareLatencyStatus(b LatencyBench) error
HardwareLatencyStatus reports whether b holds a measured hardware benchmark. When b is unmeasured it returns an error wrapping cuda.ErrHardwarePending.
func WriteModelOptNVFP4 ¶
func WriteModelOptNVFP4(dir string, layers map[string]*CalibratedLinear) error
WriteModelOptNVFP4 exports calibrated NVFP4 linear layers to dir in the NVIDIA ModelOpt checkpoint layout: model.safetensors plus hf_quant_config.json. Every exported layer satisfies ckpt.ReadNVFP4Linear and hf_quant_config.json satisfies ckpt.ParseQuantConfig.
Each layer prefix emits:
- <prefix>.weight U8 [OutFeatures, InFeatures/2]
- <prefix>.weight_scale F8_E4M3 [OutFeatures, InFeatures/16]
- <prefix>.weight_scale_2 F32 []
- <prefix>.input_scale F32 []
When a layer carries per-channel AWQ or SmoothQuant scaling (InputScale), WriteModelOptNVFP4 also writes <prefix>.pre_quant_scale (F32, [InFeatures]).
func WriteQualityPairFiles ¶
WriteQualityPairFiles writes paired baseline and candidate score JSONL files for metric ("mean_logprob" or "kl_mean") directly consumable by `ais qualitypair` and [receipt.ScoreFiles].
func WriteQualityPairJSONL ¶
WriteQualityPairJSONL emits score rows compatible with github.com/tmc/lib/nvidia/x/host/receipt ([receipt.ScoreFiles]) and `ais qualitypair` (one {"item": ID, "score": X, "n_tokens": N} JSON object per line).
Supported metric names:
- "mean_logprob": candidate mean natural-log probability per token.
- "base_mean_logprob": baseline mean natural-log probability per token.
- "kl_mean": candidate mean per-token KL(base || quant) in nats.
- "base_kl_mean": baseline reference KL(base || base) = 0.0.
Types ¶
type ActStats ¶
type ActStats struct {
// contains filtered or unexported fields
}
ActStats collects streaming per-channel input activation statistics (maximum absolute value, mean square, and root mean square) for calibration. The zero value is not usable; construct one with NewActStats.
func NewActStats ¶
NewActStats returns an empty activation statistics collector for vectors of width inFeatures.
func (*ActStats) InFeatures ¶
InFeatures returns the input channel width configured for s.
func (*ActStats) MaxAbs ¶
MaxAbs returns a copy of the per-channel maximum absolute activation value.
func (*ActStats) MeanSq ¶
MeanSq returns the per-channel mean squared activation value, or zeros when no samples have been observed.
func (*ActStats) Observe ¶
Observe incorporates a flat row-major batch of activations with shape [rows, InFeatures]. Observe validates the entire batch for length and finiteness before updating s, so a rejected batch leaves s unchanged.
type CalibratedLinear ¶
type CalibratedLinear struct {
Method Method
Format Format
OutFeatures int
InFeatures int
InputScale []float32 // optional per-channel s_j (len == InFeatures) for AWQ/SmoothQuant
ActGlobalScale float32 // static global activation scale (> 0) for ModelOpt export
NVFP4 *quant.NVFP4Weight // non-nil when Format == FormatNVFP4
INT4 *INT4Weight // non-nil when Format == FormatINT4
Alpha float64 // chosen alpha for AWQ or SmoothQuant
QuantizeActs bool // whether Forward quantizes activations (W4A4)
ReconstructionRMSE float64 // RMSE(W, W_eff) in original weight space
WeightedOutputRMSE float64 // RMSE(W X, Q(W) X) over sampleActivations or stats surrogate
BaseBF16Bytes int64 // OutFeatures * InFeatures * 2
QuantPayloadBytes int64 // packed 4-bit weight bytes
QuantScaleBytes int64 // scale storage bytes (block/group + tensor scales)
CompressionRatio float64 // BaseBF16Bytes / (QuantPayloadBytes + QuantScaleBytes)
}
CalibratedLinear holds a calibrated quantized linear layer together with its channel scaling, accuracy diagnostics, and byte accounting.
func CalibrateLinear ¶
func CalibrateLinear(weights []float32, outFeatures, inFeatures int, stats *ActStats, sampleActivations []float32, cfg Config) (*CalibratedLinear, error)
CalibrateLinear calibrates a row-major [outFeatures, inFeatures] float32 weight matrix into NVFP4 or INT4 using the configured method.
inFeatures must be a positive multiple of 16 (and a multiple of 64 when cfg.RequireMMAAlign is set). MethodAWQ and MethodSmoothQuant require non-nil stats with at least one observed sample. sampleActivations is an optional row-major [batch, inFeatures] activation matrix used by MethodAWQ for exact output-error grid search and to measure WeightedOutputRMSE.
func (*CalibratedLinear) EffectiveWeights ¶
func (cl *CalibratedLinear) EffectiveWeights() ([]float32, error)
EffectiveWeights returns the dequantized [OutFeatures, InFeatures] weight matrix folded back into the original (unscaled) input coordinate system.
func (*CalibratedLinear) Forward ¶
func (cl *CalibratedLinear) Forward(x []float32) ([]float32, error)
Forward computes y = Q(W * diag(s)) * Q_act(diag(s^-1) * x) for a single input vector x of length InFeatures, accumulating dot products in float64. When QuantizeActs is false, activations remain in float32 (W4A16).
func (*CalibratedLinear) ForwardBatch ¶
func (cl *CalibratedLinear) ForwardBatch(xs []float32) ([]float32, error)
ForwardBatch evaluates CalibratedLinear.Forward on every row of a flat row-major [batch, InFeatures] slice, returning [batch, OutFeatures].
type Config ¶
type Config struct {
// Method selects the calibration algorithm. Empty defaults to [MethodAbsMax].
Method Method
// Format selects the quantized weight format. Empty defaults to [FormatNVFP4].
Format Format
// GroupSize sets the per-group scale width for [FormatINT4]. When zero,
// CalibrateLinear uses 32 if inFeatures is divisible by 32, otherwise 16.
// Ignored for [FormatNVFP4], which always uses 16-element blocks.
GroupSize int
// RequireMMAAlign requires inFeatures to be a multiple of 64 (the K tile
// of Blackwell m16n8k64 NVFP4 MMA and [ckpt.ReadNVFP4Linear]).
RequireMMAAlign bool
// GridSteps sets the number of grid-search steps for [MethodMSE] clip
// ratios and [MethodAWQ] alpha search. Non-positive defaults to 20.
GridSteps int
// SmoothAlpha sets the migration exponent alpha in [0, 1] for
// [MethodSmoothQuant]. Zero defaults to 0.5.
SmoothAlpha float64
// QuantizeActs makes [CalibratedLinear.Forward] quantize activations after
// applying InputScale (W4A4 simulation).
QuantizeActs bool
}
Config configures CalibrateLinear.
type EvalResult ¶
type EvalResult struct {
TokensScored int64 `json:"tokens_scored"`
BaseNLL float64 `json:"base_nll"`
QuantNLL float64 `json:"quant_nll"`
BasePPL float64 `json:"base_ppl"`
QuantPPL float64 `json:"quant_ppl"`
DeltaPPL float64 `json:"delta_ppl"`
PPLRatio float64 `json:"ppl_ratio"`
MeanKL float64 `json:"mean_kl"`
MaxTokenNLLDelta float64 `json:"max_token_nll_delta"`
Top1Agreement float64 `json:"top1_agreement"`
PerItem []ItemScore `json:"per_item"`
}
EvalResult summarizes teacher-forced perplexity and KL divergence degradation between a baseline model and a quantized candidate across a token corpus.
func EvalPerplexity ¶
func EvalPerplexity(base, quantized LogitStepper, sequences [][]int32) (*EvalResult, error)
EvalPerplexity runs exact float64 teacher-forced evaluation comparing base and quantized across sequences. Every sequence must contain at least two tokens (positions 0..len-2 predict tokens 1..len-1).
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/nn/quant/calibrate"
)
type exampleStepper struct {
shift float32
}
func (s exampleStepper) Logits(tokens []int32) ([][]float32, error) {
out := make([][]float32, len(tokens))
for i, tok := range tokens {
row := []float32{-1.0, -1.0, -1.0, -1.0}
next := int((tok + 1) % 4)
row[next] = 3.0 - s.shift
out[i] = row
}
return out, nil
}
func main() {
seqs := [][]int32{
{0, 1, 2, 3, 0},
{1, 2, 3, 0, 1},
}
res, err := calibrate.EvalPerplexity(exampleStepper{shift: 0}, exampleStepper{shift: 0.25}, seqs)
if err != nil {
panic(err)
}
fmt.Printf("tokens=%d top1=%.2f kl_positive=%v ppl_degraded=%v\n",
res.TokensScored, res.Top1Agreement, res.MeanKL > 0, res.DeltaPPL > 0)
}
Output: tokens=8 top1=1.00 kl_positive=true ppl_degraded=true
type Format ¶
type Format string
Format selects the quantized weight representation.
const ( // FormatNVFP4 encodes weights as two-level NVFP4 (E2M1 nibbles, unsigned // FP8 E4M3 scale per 16 elements, and an FP32 tensor scale). FormatNVFP4 Format = "nvfp4" // FormatINT4 encodes weights as symmetric group-wise signed 4-bit integers // in [-7, +7] with per-group FP32 scales. FormatINT4 Format = "int4" )
func ParseFormat ¶
ParseFormat parses a quantized format name (case-insensitive).
type INT4Weight ¶
INT4Weight holds a linear-layer weight quantized to symmetric group-wise signed 4-bit integers in [-7, +7]. Packed stores two 4-bit two's-complement nibbles per byte, low nibble first (even column in bits 0..3, odd column in bits 4..7). Scales holds one FP32 scale per GroupSize contiguous elements.
func (*INT4Weight) Dequantize ¶
func (q *INT4Weight) Dequantize() ([]float32, error)
Dequantize unpacks q into a row-major [Rows, Cols] float32 weight matrix.
type ItemScore ¶
type ItemScore struct {
ID string `json:"id"`
TokensScored int64 `json:"tokens_scored"`
BaseNLL float64 `json:"base_nll"`
QuantNLL float64 `json:"quant_nll"`
BaseMeanLogprob float64 `json:"base_mean_logprob"`
QuantMeanLogprob float64 `json:"quant_mean_logprob"`
BasePPL float64 `json:"base_ppl"`
QuantPPL float64 `json:"quant_ppl"`
MeanKL float64 `json:"mean_kl"`
MaxTokenNLLDelta float64 `json:"max_token_nll_delta"`
Top1Agreement float64 `json:"top1_agreement"`
}
ItemScore records exact float64 teacher-forced evaluation metrics for one sequence.
type LatencyBench ¶
type LatencyBench struct {
EvidenceLabel string `json:"evidence_label"`
Device string `json:"device,omitempty"`
Arch string `json:"arch,omitempty"`
Driver string `json:"driver,omitempty"`
CUDAVersion string `json:"cuda_version,omitempty"`
Workload string `json:"workload,omitempty"`
BaseMedianUS float64 `json:"base_median_us,omitempty"`
QuantMedianUS float64 `json:"quant_median_us,omitempty"`
Speedup float64 `json:"speedup,omitempty"`
BaseVRAMBytes uint64 `json:"base_vram_bytes,omitempty"`
QuantVRAMBytes uint64 `json:"quant_vram_bytes,omitempty"`
Note string `json:"note,omitempty"`
}
LatencyBench records an optional device-timed latency and VRAM comparison. On hosts without a native GPU measurement, EvidenceLabel must be EvidenceUnmeasured and timing fields stay zero.
func UnmeasuredLatency ¶
func UnmeasuredLatency(workload string) LatencyBench
UnmeasuredLatency constructs a LatencyBench explicitly marking hardware timings as unmeasured on the host.
type LogitStepper ¶
LogitStepper evaluates a causal language model on a token sequence and returns next-token logits of shape [len(tokens)][vocabSize].
type Method ¶
type Method string
Method selects the post-training quantization calibration algorithm.
const ( // MethodAbsMax uses per-block or per-group maximum absolute scaling. MethodAbsMax Method = "absmax" // MethodMSE applies Four-Over-Six (4/6) and clip-ratio grid search to // minimize per-block quantization error. MethodMSE Method = "mse" // MethodAWQ searches per-channel scaling s_j = rms(x_j)^alpha over // alpha in [0, 1] to minimize activation-weighted output error. MethodAWQ Method = "awq" // MethodSmoothQuant migrates activation outliers into weights using // s_j = max(|X_j|)^alpha / max(|W_j|)^(1-alpha). MethodSmoothQuant Method = "smoothquant" )
func ParseMethod ¶
ParseMethod parses a calibration method name (case-insensitive).
type MethodComparison ¶
type MethodComparison struct {
Method Method `json:"method"`
Format Format `json:"format"`
ReconstructionRMSE float64 `json:"reconstruction_rmse"`
WeightedOutputRMSE float64 `json:"weighted_output_rmse"`
VRAM VRAMSummary `json:"vram"`
Eval *EvalResult `json:"eval,omitempty"`
}
MethodComparison summarizes one (Method, Format) configuration in a calibration sweep report.
type PipelineReport ¶
type PipelineReport struct {
Title string `json:"title"`
ModelSource string `json:"model_source,omitempty"`
EvidenceLabel string `json:"evidence_label,omitempty"`
Layers int `json:"layers"`
VRAM VRAMSummary `json:"vram"`
Eval *EvalResult `json:"eval,omitempty"`
Comparisons []MethodComparison `json:"comparisons,omitempty"`
Latency LatencyBench `json:"latency"`
}
PipelineReport captures the end-to-end calibration, perplexity/KL, VRAM, and optional native latency summary.
func (*PipelineReport) WriteJSON ¶
func (r *PipelineReport) WriteJSON(w io.Writer) error
WriteJSON encodes r as indented JSON with a trailing newline.
func (*PipelineReport) WriteMarkdown ¶
func (r *PipelineReport) WriteMarkdown(w io.Writer) error
WriteMarkdown formats r as a GitHub-flavored Markdown report.
type VRAMSummary ¶
type VRAMSummary struct {
BF16Bytes int64 `json:"bf16_bytes"`
QuantBytes int64 `json:"quant_bytes"`
ScaleBytes int64 `json:"scale_bytes"`
TotalQuantBytes int64 `json:"total_quant_bytes"`
CompressionRatio float64 `json:"compression_ratio"`
SavedPct float64 `json:"saved_pct"`
EvidenceLabel string `json:"evidence_label,omitempty"`
}
VRAMSummary reports analytical or measured weight memory footprints against a BF16 baseline.
func SummarizeVRAM ¶
func SummarizeVRAM(layers []*CalibratedLinear) VRAMSummary
SummarizeVRAM aggregates BF16 vs quantized payload and scale byte counts across layers. The returned summary is labeled EvidenceDerived.