Documentation
¶
Overview ¶
Package quant provides block-scaled quantization formats, weight prepacking, and fused normalization/activation quantization CUDA kernels (Q4_0, Q8_0, Q8_1, OCP FP8 E4M3FN, MXFP8, MXFP4, NVFP4 E2M1, UE8M0, Q2_K, IQ2_XXS, U2).
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
SPDX-License-Identifier: Apache-2.0
Example ¶
package main
import (
"encoding/binary"
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
data := make([]byte, 34)
binary.LittleEndian.PutUint16(data, 0x3c00) // scale 1
data[2] = 42
values, err := nnquant.DequantizeQ8_0(data, 32)
if err != nil {
panic(err)
}
fmt.Printf("values=%d first=%.0f\n", len(values), values[0])
}
Output: values=32 first=42
Example (NormQuantCandidates) ¶
package main
import (
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
candidates, err := nnquant.RMSNormQ8_1Candidates(2, 64, true, true)
if err != nil {
fmt.Println(err)
return
}
for _, candidate := range candidates {
fmt.Println(candidate.Name, len(candidate.Launches), candidate.WorkspaceBytes)
}
}
Output: norm_quant_unfused 2 512
Index ¶
- Constants
- Variables
- func AlignedOutputStride(cols int, elemBytes int, alignBytes int) (int, error)
- func AlignedScaleRows(rows int, alignBytes int) (int, error)
- func CheckTileGeometry(rows, rowBytes, span, swizzle, tileRows int) error
- func Compress2to4(dense []float32, rows, cols int) (sparseWeights []float32, metadata []byte, err error)
- func Compress2to4Bytes(dense []byte, rows, cols int) (sparseWeights []byte, metadata []byte, err error)
- func Decompress2to4(sparseWeights []float32, metadata []byte, rows, cols int) ([]float32, error)
- func Decompress2to4Bytes(sparseWeights []byte, metadata []byte, rows, cols int) ([]byte, error)
- func Dequantize(packed []byte, scales []float32, groupSize int, dst []float32) error
- func DequantizeBlockFP8UE8M0CPU(q []uint8, packedScales []uint32, rows, cols, blockSize int) ([]float32, error)
- func DequantizeConformantBlock32(b ConformantBlock32) [32]float32
- func DequantizeFP8(p *PrepackedTensor, dst []float32) error
- func DequantizeIQ2XXS(dst []float32, block []byte) error
- func DequantizeMXFP4(p *PrepackedTensor, groupSize int, dst []float32) error
- func DequantizeMXFP8(dst []float32, q, scales []byte) error
- func DequantizeQ4_0(data []byte, numElements int) ([]float32, error)
- func DequantizeQ8_0(data []byte, numElements int) ([]float32, error)
- func DequantizeScaleUE8M0(exp uint8) float32
- func E4M3ToFloat32(b byte) float32
- func E5M2ToFloat32(b byte) float32
- func EGraphCommonPrelude() string
- func EmitEGraphIQ2XXSMatvec(kernelName, precision string) string
- func EmitEGraphQ2KMatvec(kernelName, precision string) string
- func EmitEGraphQ8_0Matvec(kernelName, precision string) string
- func EmitEGraphRMSQuantQ81(kernelName string) string
- func EmitEGraphSelectedIQ2XXSQ81(kernelName string) string
- func EmitEGraphSelectedQ2KQ81(kernelName string) string
- func EmitEGraphSelectedQ2KQ81RawSIMD(kernelName string) string
- func EmitEGraphSwiGLUQ8_0(kernelName string) string
- func EmitEGraphSwiGLUQ81(kernelName string) string
- func EmitEGraphU2SIMD(kernelName string) string
- func EmitEGraphU2Scalar(kernelName string) string
- func EmitNVFP4GEMV(name string, cfg NVFP4GEMVConfig) (string, error)
- func Float16ToFloat32(h uint16) float32
- func Float32ToE4M3(v float32) byte
- func Float32ToE5M2(v float32) byte
- func Float32ToFloat16(f float32) uint16
- func FusedSwiGLUPerTokenCastSource(cfg SwiGLUQuantConfig) (string, error)
- func GenerateFP8CUDA(kernelName string) string
- func IQ2XXSTablesCUDA() string
- func InverseTransformScaleLayoutColMajor(colMajorScales []uint32, rows, scaleCols int, alignedRows int) ([]uint32, error)
- func NVFP4MMAAccumulate(c float32, a, b *[64]float32, sfa, sfb *[4]float32) float32
- func OwnedActivationArtifact(target string, format ActivationFormat) (*cudakernel.Artifact, error)
- func OwnedActivationKernelSource(format ActivationFormat) (source string, entry string, err error)
- func OwnedActivationSchema() (cudakernel.Schema, error)
- func PackE2M1WithE4M3Scale(src []float32) (packedData []byte, e4m3Scales []uint8, err error)
- func PackOCPBlocks(src []float32) ([]byte, error)
- func PackUE8M0(exponents []uint8) ([]uint32, error)
- func Quantize(src []float32, groupSize int) ([]byte, []float32, error)
- func QuantizeBlockFP8UE8M0CPU(input []float32, rows, cols, blockSize int) (q []uint8, packedScales []uint32, err error)
- func QuantizeMXFP8(q, scales, src []byte, dt cuda.DType) (nonfinite int64, err error)
- func QuantizeScaleUE8M0(amax float32, fp8Max float32) uint8
- func RMSNormQ8_1Artifact(target string) (*kernel.Artifact, error)
- func RMSNormQ8_1Source() string
- func RMSNormQ8_1UnfusedArtifacts(target string) ([2]*kernel.Artifact, error)
- func RMSNormQ8_1UnfusedSource() string
- func SwiGLUPerTokenQuantCPU(gateUp []float32, cfg SwiGLUQuantConfig) (fp8Out []uint8, scales []float32, packedUE8M0ColMajor []uint32, err error)
- func SwizzleRepackCUDA(name string, span, swizzle, tileRows int) (string, error)
- func SwizzleScales(scales []byte, rows, cols int, mode SwizzleMode) ([]byte, error)
- func TransformScaleLayout(rowMajorScales []uint32, rows, scaleCols int, alignedRows int) ([]uint32, error)
- func TransformScaleLayoutColMajor(rowMajorScales []uint32, rows, scaleCols int, alignedRows int) ([]uint32, error)
- func UnpackE2M1WithE4M3Scale(packedData []byte, e4m3Scales []uint8, count int) ([]float32, error)
- func UnpackIQ2_XXS(p *PrepackedTensor) ([]byte, error)
- func UnpackOCPBlocks(data []byte, count int) ([]float32, error)
- func UnpackQ8_0(p *PrepackedTensor) ([]byte, error)
- func UnpackUE8M0(packed []uint32, count int) ([]uint8, error)
- func UnswizzleScales(swizzled []byte, rows, cols int, mode SwizzleMode) ([]byte, error)
- type ActivationFormat
- type ActivationLayout
- type BlockQ4_0
- type BlockQ8_0
- type BlockQ8_1
- type BlockScaleMMAConfig
- type BlockScaleMMAPlan
- type BoxDescriptor
- type CUDALowerBroadcast
- type CUDALowerDType
- type CUDALowerOperand
- type CUDALowerRMSNormDynQuantOpts
- type CUDALowerScaleLayout
- type CUDALowerStore
- type CUDALowerSwiGLUDynQuantOpts
- type CUDALowerTileEpilogue
- type CUDALowerWeight
- type ConformantBlock32
- type DataType
- type DeviceActivation
- type Engine
- func (e *Engine) Close() error
- func (e *Engine) Dequantize(packed cuda.Slice[uint8], scales cuda.Slice[float32], out cuda.Slice[float32], ...) error
- func (e *Engine) LinearGEMV(x cuda.Slice[float32], packed cuda.Slice[uint8], scales cuda.Slice[float32], ...) error
- func (e *Engine) LinearGEMVOn(s *cuda.Stream, x cuda.Slice[float32], packed cuda.Slice[uint8], ...) error
- type FP8Format
- type InterleaveMode
- type LayoutTransformer
- type NVFP4GEMVConfig
- type NVFP4Weight
- type NormQuantCandidate
- type NormQuantLaunch
- type Option
- type OwnedActivation
- type PrepackedTensor
- func PackMXFP4(src []float32, rows, cols int, groupSize int) (*PrepackedTensor, error)
- func ParseZeroCopy(data []byte) (*PrepackedTensor, error)
- func QuantizeFP8(src []float32, rows, cols int, dt DataType) (*PrepackedTensor, error)
- func Read(r io.Reader) (*PrepackedTensor, error)
- func RepackIQ2_XXS(rawBlocks []byte, rows, cols int) (*PrepackedTensor, error)
- func RepackQ8_0(rawBlocks []byte, rows, cols int) (*PrepackedTensor, error)
- type Q8CopyFixture
- type Q8Storage
- type QuantFormat
- type QuantizedMatrix
- type RoundingContract
- type ScaleRecipe
- type SwiGLUQuantConfig
- type SwizzleMode
- type TensorMapOperation
- type UE8M0
Examples ¶
- Package
- Package (NormQuantCandidates)
- BoxDescriptor.ValidateTensorMap
- Compress2to4
- DequantizeFP8
- DequantizeMXFP4
- DescribeQ8
- EmitNVFP4GEMV
- NewActivationLayout
- NewBlockScaleMMAPlan
- NewLayoutTransformer
- PackMXFP4
- PackNVFP4Weight
- PackOCPBlocks
- PrepackedTensor (Iq2Blocks)
- QuantizeActivation
- QuantizeMXFP8
- QuantizeScaleUE8M0
- StagedQ8CopyFixture
- UE8M0
Constants ¶
const ( // NVFP4BlockElements is the micro-block size (16 E2M1 elements) used by // Blackwell NVFP4 and DeepInfer's V41_FP4_FORMAT KV cache. NVFP4BlockElements = 16 // NVFP4PackedBytes is the packed E2M1 byte count per 16-element micro-block. NVFP4PackedBytes = 8 // NVFP4ScaleBytes is the FP8 E4M3 scale byte count per 16-element micro-block. NVFP4ScaleBytes = 1 )
const ( ArchSM121a = "sm_121a" ArchSM100a = "sm_100a" )
Target names accepted by the host layout transformers.
const ( MinAddressAlignment = 16 MinBoxWidthBytes = 16 MaxBoxWidthBytesSM121a = 128 MaxBoxWidthBytesSM100a = 128 BoxBoundaryBytesSM121a = 128 )
Alignment and default box sizes used by the host layout transformers. The box-size defaults are not general tensor-map hardware limits.
const CUDALowerDynQuantDeviceHelpers = dynQuantDeviceHelpers
CUDALowerDynQuantDeviceHelpers exposes the dynamic NVFP4 quantization device C++ helpers.
const DefaultGroupSize = 32
DefaultGroupSize is the standard OCP MXFP4 block size.
const IQ2XXSBlockBytes = 66
IQ2XXSBlockBytes is the byte length of a packed IQ2_XXS block. Format: 2-byte float16 scale + 64 bytes (grid indices, signs, sub-block scales).
const IQ2XXSBlockSize = 256
IQ2XXSBlockSize is the number of quantized weights in an IQ2_XXS super-block.
const MXFP8BlockSize = 32
MXFP8BlockSize is the number of elements that share one MXFP8 scale.
const NVFP4MMAAsm = NVFP4MMAInstr + " {%0, %1, %2, %3}, {%4, %5, %6, %7}, {%8, %9}, {%0, %1, %2, %3}, %10, {0, 0}, %11, {0, 0};"
NVFP4MMAAsm is the CUDA inline-asm template for NVFP4MMAInstr, for use in a C string literal. D is %0..%3 ("+f"), A is %4..%7, B is %8 and %9, and the SF_A and SF_B words are %10 and %11 ("r"). The byte-id and thread-id scale selectors are 0: scale_vec::4X reads all four bytes of each word, SF_A comes from lanes 4g (row g) and 4g+1 (row g+8), and SF_B from lane 4g (column g).
const NVFP4MMAInstr = "mma.sync.aligned.m16n8k64.row.col.kind::mxf4nvf4.block_scale.scale_vec::4X.f32.e2m1.e2m1.f32.ue4m3"
NVFP4MMAInstr is the warp-level block-scaled NVFP4 Tensor Core instruction EmitNVFP4GEMV lowers to: E2M1 operands with one UE4M3 scale per 16 elements of K (four per operand row or column in each K=64 step).
const OCPBlockBytes = 17
OCPBlockBytes is the byte width of one conformant 32-element OCP MXFP4 block: 16 bytes of packed E2M1 nibbles followed by 1 byte of UE8M0 scale.
const RecipeMXFP8 = "mxfp8-e4m3fn-e8m0-k32-rceil-from-bf16-rne"
RecipeMXFP8 names the arithmetic of QuantizeMXFP8: OCP MX FP8 with float8_e4m3fn elements and one E8M0 scale per 32 elements, the scale rounded up from the float32 quotient amax/448 (see QuantizeScaleUE8M0), from inputs first rounded to bfloat16, nearest even. A change to the bytes the recipe produces must change the name.
The scale rule matches the ROUND_UP mode of downcast_to_mxfp in the Triton project's triton_kernels package (MIT license) except for quotients below 2^-126, where that code takes 2^-126 and this recipe takes the smallest power of two not below the quotient, as cvt.rp.satfinite.ue8m0x2.f32 does. The code here is written from the OCP Microscaling Formats (MX) v1.0 specification, not from that implementation.
const ScaledFP8GEMVTemplate = `` /* 1957-byte string literal not displayed */
ScaledFP8GEMVTemplate is the embedded CUDA C++ kernel for in-register E4M3/E5M2 dequantization and GEMV.
Variables ¶
var ( // ErrPartialBlock reports a length that is not a whole number of // blocks. The quantizers and decoders do not pad a final block. ErrPartialBlock = errors.New("partial block") // ErrNonFinite reports a NaN or infinite input value or block scale. ErrNonFinite = errors.New("non-finite value") )
Errors the block quantizers and decoders wrap, so that callers and conformance vectors can tell the edge cases apart.
var E2M1Table = [16]float32{
0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0,
-0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0,
}
E2M1Table maps each 4-bit nibble (0..15) to its exact floating-point value. Format: 1 sign bit, 2 exponent bits, 1 mantissa bit.
Functions ¶
func AlignedOutputStride ¶
AlignedOutputStride returns the smallest element row stride >= cols whose byte width (stride * elemBytes) is a multiple of alignBytes (defaulting to 32 bytes when alignBytes == 0, matching DeepInfer's _OUTPUT_ALIGNMENT_BYTES).
func AlignedScaleRows ¶
AlignedScaleRows pads rows up to a multiple of alignBytes (defaulting to 16 when alignBytes == 0, matching 16-byte TMA descriptor alignment for packed UE8M0 scale columns).
func CheckTileGeometry ¶
func Compress2to4 ¶
func Compress2to4(dense []float32, rows, cols int) (sparseWeights []float32, metadata []byte, err error)
Compress2to4 compresses a dense float32 matrix into 2:4 structured sparsity format and generates the corresponding metadata for sm_100a tcgen05.mma.ws.sp. For every 4 consecutive elements along cols, the 2 elements with the largest absolute values are preserved and the other 2 are zeroed out.
Example ¶
package main
import (
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
// Compress a matrix row with 2:4 structured sparsity for sm_100a tcgen05
dense := []float32{1.0, 0.0, 3.0, 0.0, 0.0, 4.0, 0.0, 2.0}
sparse, meta, err := nnquant.Compress2to4(dense, 1, 8)
if err != nil {
panic(err)
}
fmt.Printf("Sparse elements: %d\n", len(sparse))
fmt.Printf("Metadata bytes: %d\n", len(meta))
fmt.Printf("Metadata byte 0: 0x%02X\n", meta[0])
}
Output: Sparse elements: 4 Metadata bytes: 1 Metadata byte 0: 0xD8
func Compress2to4Bytes ¶
func Compress2to4Bytes(dense []byte, rows, cols int) (sparseWeights []byte, metadata []byte, err error)
Compress2to4Bytes compresses a dense byte slice (e.g. FP8 or INT8) into 2:4 structured sparsity.
func Decompress2to4 ¶
Decompress2to4 reconstructs the dense float32 matrix from 2:4 sparse weights and metadata.
func Decompress2to4Bytes ¶
Decompress2to4Bytes reconstructs a dense byte slice from 2:4 sparse bytes and metadata.
func Dequantize ¶
Dequantize unpacks MXFP4 bytes and scales into float32 destination slice.
func DequantizeBlockFP8UE8M0CPU ¶
func DequantizeBlockFP8UE8M0CPU(q []uint8, packedScales []uint32, rows, cols, blockSize int) ([]float32, error)
DequantizeBlockFP8UE8M0CPU dequantizes a [rows, cols] FP8 E4M3 matrix and its packed UE8M0 block scales back to float32.
func DequantizeConformantBlock32 ¶
func DequantizeConformantBlock32(b ConformantBlock32) [32]float32
DequantizeConformantBlock32 unpacks a 17-byte ConformantBlock32 back to 32 float32 values.
func DequantizeFP8 ¶
func DequantizeFP8(p *PrepackedTensor, dst []float32) error
DequantizeFP8 converts a row-major FP8 matrix back to float32. Swizzled, interleaved and sparse host layouts are unsupported. Invalid input leaves dst unchanged.
Example ¶
package main
import (
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
p, err := nnquant.QuantizeFP8([]float32{1, -2}, 1, 2, nnquant.TypeFP8_E4M3)
if err != nil {
fmt.Println(err)
return
}
dst := make([]float32, 2)
if err := nnquant.DequantizeFP8(p, dst); err != nil {
fmt.Println(err)
return
}
fmt.Println(dst)
}
Output: [1 -2]
func DequantizeIQ2XXS ¶
DequantizeIQ2XXS unpacks packed IQ2_XXS blocks into dst in float32. It unpacks len(block)/IQ2XXSBlockBytes blocks (each 256 weights).
This is a zero-allocation fast path matching the standard GGML / DeepSeek-V4 IQ2_XXS codebook specification.
func DequantizeMXFP4 ¶
func DequantizeMXFP4(p *PrepackedTensor, groupSize int, dst []float32) error
DequantizeMXFP4 unpacks row-major MXFP4 payload and contiguous scales into dst. groupSize must match the encoding and be a positive multiple of 32. Swizzled, interleaved and sparse host layouts are unsupported. Invalid input leaves dst unchanged.
Example ¶
package main
import (
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
src := make([]float32, 32)
src[0] = 6
p, err := nnquant.PackMXFP4(src, 1, 32, 32)
if err != nil {
fmt.Println(err)
return
}
dst := make([]float32, 32)
if err := nnquant.DequantizeMXFP4(p, 32, dst); err != nil {
fmt.Println(err)
return
}
fmt.Println(dst[0], len(dst))
}
Output: 6 32
func DequantizeMXFP8 ¶
DequantizeMXFP8 decodes MXFP8 codes q and their E8M0 scales, one per 32 codes, into dst. Each value is the code's float8_e4m3fn value times 2^(scale-127), rounded once to float32; a product beyond float32's range becomes an infinity. A NaN scale or code is an error wrapping ErrNonFinite.
func DequantizeQ4_0 ¶
DequantizeQ4_0 unpacks Q4_0 blocks into a float32 slice.
func DequantizeQ8_0 ¶
DequantizeQ8_0 unpacks Q8_0 blocks into a float32 slice.
func DequantizeScaleUE8M0 ¶
DequantizeScaleUE8M0 returns the scale 2^(int(exp)-127) that the UE8M0 (OCP E8M0) exponent exp encodes via cuda.E8M0frombits. Exponent 0 is 2^-127, a float32 subnormal; exponent 255 is NaN.
func E4M3ToFloat32 ¶
E4M3ToFloat32 converts an FP8 E4M3FN byte to float32 via cuda.E4M3frombits.
func E5M2ToFloat32 ¶
E5M2ToFloat32 converts an FP8 E5M2 byte to float32 via cuda.E5M2frombits.
func EGraphCommonPrelude ¶
func EGraphCommonPrelude() string
EGraphCommonPrelude returns the shared device header emitted ahead of e-graph lowered CUDA C++ kernels.
func EmitEGraphIQ2XXSMatvec ¶
func EmitEGraphQ2KMatvec ¶
func EmitEGraphQ8_0Matvec ¶
func EmitEGraphRMSQuantQ81 ¶
func EmitEGraphSelectedQ2KQ81RawSIMD ¶
EmitEGraphSelectedQ2KQ81RawSIMD emits the raw DS4 SIMD down projection. Its lane windows and fused operations are part of the numeric contract.
func EmitEGraphSwiGLUQ8_0 ¶
func EmitEGraphSwiGLUQ81 ¶
func EmitEGraphU2SIMD ¶
func EmitEGraphU2Scalar ¶
func EmitNVFP4GEMV ¶
func EmitNVFP4GEMV(name string, cfg NVFP4GEMVConfig) (string, error)
EmitNVFP4GEMV emits NVRTC-clean CUDA C++ for a decode GEMV
y[b, n] = alpha * sum_k W[n, k] * x[b, k], b < batch <= 8
over an NVFP4Weight and NVFP4 activations, using NVFP4MMAInstr. The weight is the row-major A operand (16 output features per warp) and the activations are the column-major B operand (one batch row per column), so a decode step of up to 8 rows uses one m16n8k64 MMA per 64 elements of K.
The kernel is
__global__ void name(const uint8_t* w_packed, const uint8_t* w_scales,
const uint8_t* x_packed, const uint8_t* x_scales,
float alpha, float* y, int batch)
with w_packed and w_scales laid out as NVFP4Weight.Packed and NVFP4Weight.Scales, x_packed as [batch, K/2] bytes and x_scales as [batch, K/16] UE4M3 bytes (the row-major layout of cudalower.RMSNormDynamicNVFP4Quant), and y as [batch, N] float32. alpha is the weight's TensorScale times the activation tensor scale (1 for activations quantized without one). Launch with grid N/16 and one warp per block. All pointers must be 4-byte aligned.
Under the cudahostemu host emulator (EG_HOST_EMU), the MMA runs as the emulator's model of the same instruction, so the kernel's addressing can be checked without a GPU.
Targets outside the sm_120 family return an error wrapping [cudaerrors.ErrUnsupported].
Example ¶
package main
import (
"fmt"
"strings"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
src, err := nnquant.EmitNVFP4GEMV("q_proj_nvfp4", nnquant.NVFP4GEMVConfig{N: 2048, K: 2048, TargetArch: "sm_121a"})
if err != nil {
panic(err)
}
fmt.Println(strings.Contains(src, nnquant.NVFP4MMAInstr))
_, err = nnquant.EmitNVFP4GEMV("q_proj_nvfp4", nnquant.NVFP4GEMVConfig{N: 2048, K: 2048, TargetArch: "sm_89"})
fmt.Println(err)
}
Output: true mxfp4: target "sm_89" does not support mma.sync kind::mxf4nvf4.block_scale: target does not support the requested capability
func Float16ToFloat32 ¶
Float16ToFloat32 converts IEEE 754 half-precision bits to float32.
func Float32ToE4M3 ¶
Float32ToE4M3 converts v to FP8 E4M3FN (1 sign, 4 exp bias 7, 3 mantissa) via cuda.E4M3bits, rounding to nearest even, saturating finite values and ±Inf to ±448 (0x7e/0xfe), and mapping every NaN to canonical 0x7f.
func Float32ToE5M2 ¶
Float32ToE5M2 converts v to FP8 E5M2 (1 sign, 5 exp bias 15, 2 mantissa) via cuda.E5M2bits, rounding to nearest even, saturating |v| >= 61440 and ±Inf to ±57344 (0x7b/0xfb), and mapping every NaN to canonical 0x7f.
func Float32ToFloat16 ¶
Float32ToFloat16 converts float32 to IEEE 754 half-precision bits, rounding to nearest with ties to even. Overflow produces signed infinity. NaNs keep their sign and high payload bits and are quieted.
func FusedSwiGLUPerTokenCastSource ¶
func FusedSwiGLUPerTokenCastSource(cfg SwiGLUQuantConfig) (string, error)
FusedSwiGLUPerTokenCastSource generates a self-contained NVRTC-compilable CUDA C++ kernel implementing fused SwiGLU activation, warp-level amax reduction, power-of-two UE8M0 or float32 scale computation, 32B-aligned output row stride, and TMA-aligned column-major packed scale output.
func GenerateFP8CUDA ¶
GenerateFP8CUDA produces a specialized FP8 dequantizing GEMV kernel.
func IQ2XXSTablesCUDA ¶
func IQ2XXSTablesCUDA() string
iq2xxsTablesCUDA renders the IQ2_XXS codebook and sign tables as CUDA C++ declarations. The Go tables are the single source of truth: the device code is emitted from them rather than transcribed a second time, so the two cannot drift apart. IQ2XXSTablesCUDA renders the IQ2_XXS codebook and sign tables as CUDA C++.
func InverseTransformScaleLayoutColMajor ¶
func InverseTransformScaleLayoutColMajor(colMajorScales []uint32, rows, scaleCols int, alignedRows int) ([]uint32, error)
InverseTransformScaleLayoutColMajor converts a [scaleCols, alignedRows] column-major packed scale tensor back to a [rows, scaleCols] row-major slice, discarding any trailing padding rows in [rows, alignedRows).
func NVFP4MMAAccumulate ¶
NVFP4MMAAccumulate returns one output element of one NVFP4MMAInstr step as sm_121a computes it: c plus the 64 products a[k]·b[k]·sfa[k/16]·sfb[k/16]. a and b hold E2M1 values and sfa and sfb UE4M3 values.
The device aligns each product by its unnormalised exponent ilogb(a)+ilogb(b)+ilogb(sfa)+ilogb(sfb), and c by ilogb(c)+4. It drops the bits of each term more than 39 places below the largest of these, toward zero, and sums the rest exactly. Then it truncates the sum to float32 (round toward zero). Three rounds of probes on a GB10 established this model; they are in this package's accumulate_*_test.go files. NaN inputs are not modeled.
func OwnedActivationArtifact ¶
func OwnedActivationArtifact(target string, format ActivationFormat) (*cudakernel.Artifact, error)
OwnedActivationArtifact compiles the OwnedActivation quantization kernel for format targeting a supported physical SM architecture ("sm_90", "sm_90a", "sm_100a", or "sm_121a").
func OwnedActivationKernelSource ¶
func OwnedActivationKernelSource(format ActivationFormat) (source string, entry string, err error)
OwnedActivationKernelSource returns the self-contained NVRTC C++17 kernel source and entry point symbol for quantizing a row-major float32 activation tensor into OwnedActivation device buffers for format.
The kernel quantizes row blockIdx.x of the input. Launch it with one block per row and blockDim.x a positive multiple of 32, and pass a values_out buffer that is at least 4-byte aligned.
func OwnedActivationSchema ¶
func OwnedActivationSchema() (cudakernel.Schema, error)
OwnedActivationSchema returns the 7-parameter kernel ABI schema shared by all OwnedActivation quantization kernels: (input ptr, values_out ptr, scales_out ptr, rows u32, cols u32, row_stride_bytes u32, scale_row_stride u32).
func PackE2M1WithE4M3Scale ¶
PackE2M1WithE4M3Scale quantizes src (whose length must be a positive multiple of 16) into 8 packed E2M1 bytes and 1 unsigned FP8 E4M3 scale byte per 16-element micro-block (scale = amax / 6.0 encoded in FP8 E4M3).
func PackOCPBlocks ¶
PackOCPBlocks quantizes src (whose length must be a positive multiple of 32) into conformant 17-byte OCP MXFP4 blocks: 16 bytes of 32 packed E2M1 nibbles followed by 1 byte of UE8M0 scale (ceil(log2(amax / 6.0))).
Example ¶
package main
import (
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
src := make([]float32, 32)
src[0], src[1] = 6.0, -3.0
packed, err := nnquant.PackOCPBlocks(src)
if err != nil {
panic(err)
}
unpacked, err := nnquant.UnpackOCPBlocks(packed, 32)
if err != nil {
panic(err)
}
fmt.Printf("bytes=%d scaleExp=%d firstTwo=[%.1f %.1f]\n",
len(packed), packed[16], unpacked[0], unpacked[1])
}
Output: bytes=17 scaleExp=127 firstTwo=[6.0 -3.0]
func PackUE8M0 ¶
PackUE8M0 packs unsigned 8-bit UE8M0 biased exponents into uint32 words in little-endian byte order (e0 | e1<<8 | e2<<16 | e3<<24), padding trailing bytes with zero when len(exponents) is not a multiple of 4.
func QuantizeBlockFP8UE8M0CPU ¶
func QuantizeBlockFP8UE8M0CPU(input []float32, rows, cols, blockSize int) (q []uint8, packedScales []uint32, err error)
QuantizeBlockFP8UE8M0CPU quantizes a [rows, cols] row-major float32 matrix into FP8 E4M3 values using per-block UE8M0 power-of-two scales over contiguous horizontal blocks of blockSize elements.
func QuantizeMXFP8 ¶
QuantizeMXFP8 quantizes src, little-endian elements of type dt, which must be cuda.F32 or cuda.BF16, by RecipeMXFP8. It writes one float8_e4m3fn byte per element to q and one E8M0 byte per 32 elements to scales; for a row-major matrix whose row length is a multiple of 32, that is one scale per 32 columns, in row order.
F32 elements are rounded to BF16, nearest even, before anything else. An all-zero block gets scale 0 (2^-127), and its zeros keep their signs. A block holding a NaN or infinity, after that rounding, gets scale 0xff, the E8M0 NaN, and code 0x7f with each element's sign; QuantizeMXFP8 counts those elements in nonfinite rather than failing.
The element count must be a multiple of 32: QuantizeMXFP8 pads no block and returns an error wrapping ErrPartialBlock otherwise.
Example ¶
This example quantizes two blocks of float32 values to MXFP8: one whose largest magnitude is 3, and one of zeros, which gets scale 0 and keeps the sign of its negative zero.
package main
import (
"encoding/binary"
"fmt"
"math"
"github.com/tmc/lib/nvidia/x/cuda"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
src := make([]byte, 4*64)
for i, v := range map[int]float32{0: 3, 1: -0.75, 2: 0.1, 33: float32(math.Copysign(0, -1))} {
binary.LittleEndian.PutUint32(src[4*i:], math.Float32bits(v))
}
q, scales := make([]byte, 64), make([]byte, 2)
if _, err := nnquant.QuantizeMXFP8(q, scales, src, cuda.F32); err != nil {
fmt.Println(err)
return
}
out := make([]float32, 64)
if err := nnquant.DequantizeMXFP8(out, q, scales); err != nil {
fmt.Println(err)
return
}
fmt.Printf("scales %v\n", scales)
fmt.Printf("codes %x %x\n", q[:3], q[32:34])
fmt.Println(out[:3], out[32:34])
}
Output: scales [120 0] codes 7cec55 0080 [3 -0.75 0.1015625] [0 -0]
func QuantizeScaleUE8M0 ¶
QuantizeScaleUE8M0 returns the UE8M0 (OCP E8M0) biased exponent of the smallest power of two not below q = |amax| / fp8Max, where q is the float32 quotient rounded to nearest even. This is the scale rule of RecipeMXFP8, and the result of cvt.rp.satfinite.ue8m0x2.f32 on q.
An all-zero block (amax 0) gets exponent 0, the scale 2^-127, so its elements quantize to zeros that keep their signs. A quotient at or below 2^-127 also gets 0. A quotient above 2^127, including an infinite amax, saturates to 254, and a NaN amax gives 255, the E8M0 NaN. When fp8Max is non-positive or non-finite, 448 (FP8 E4M3) is used.
Example ¶
package main
import (
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
exp := nnquant.QuantizeScaleUE8M0(448.0, 448.0)
scale := nnquant.DequantizeScaleUE8M0(exp)
packed, err := nnquant.PackUE8M0([]uint8{exp, exp + 1})
if err != nil {
panic(err)
}
unpacked, err := nnquant.UnpackUE8M0(packed, 2)
if err != nil {
panic(err)
}
fmt.Printf("exp=%d scale=%.1f unpacked=%v\n", exp, scale, unpacked)
}
Output: exp=127 scale=1.0 unpacked=[127 128]
func RMSNormQ8_1Artifact ¶
RMSNormQ8_1Artifact compiles the generated kernel for a physical CUDA target (for example, sm_121a), preserving its fixed ABI and compiled resources. It requires NVRTC and CUDA headers; it does not load or launch the kernel.
func RMSNormQ8_1Source ¶
func RMSNormQ8_1Source() string
RMSNormQ8_1Source emits the fused CUDA kernel for the declared fixture. It includes cuda_fp16.h; NVRTC supplies size_t and the math functions. The kernel rms_quant_q8_1 stores s as d*sum(q), after quantizing, as BlockQ8_1 documents; ggml, the egraph root package and ds4-min store sum(v) before quantizing, so their blocks cannot be mixed with these.
func RMSNormQ8_1UnfusedArtifacts ¶
RMSNormQ8_1UnfusedArtifacts compiles the normalization and quantization entries, in launch order, for a physical target. Compilation preserves each entry's resource requirements. This does not allocate, load or launch kernels.
func RMSNormQ8_1UnfusedSource ¶
func RMSNormQ8_1UnfusedSource() string
RMSNormQ8_1UnfusedSource emits a two-kernel alternative to RMSNormQ8_1Source. rms_f32 writes rows*cols float32 values to a distinct intermediate buffer; quant_q8_1 reads that buffer and writes rows*(cols/32) Q8_1 blocks. Launch them in order on the same stream, with one one-dimensional block per row. Only thread zero computes. Inputs obey the fused kernel's numerical contract. The intermediate remains available to secondary consumers after both launches. Both entries use the fused seven-parameter ABI. The quantizer ignores weight, eps and weighted; its in argument is the normalization output. Header and builtin requirements match RMSNormQ8_1Source.
func SwiGLUPerTokenQuantCPU ¶
func SwiGLUPerTokenQuantCPU(gateUp []float32, cfg SwiGLUQuantConfig) (fp8Out []uint8, scales []float32, packedUE8M0ColMajor []uint32, err error)
SwiGLUPerTokenQuantCPU computes silu(gate) * up on a [Tokens, 2*IntermediateDim] row-major tensor (where each token row stores [gate[0..D-1], up[0..D-1]]) and quantizes each BlockSize tile into FP8 E4M3 with either float32 scales or TMA-aligned column-major packed UE8M0 scales.
func SwizzleRepackCUDA ¶
SwizzleRepackCUDA returns CUDA C++ for a kernel name(src, dst, rows, row_bytes) that performs [RepackSwizzled] on the device: each thread moves one 16-byte chunk from row-major src to its tile-major swizzled position in dst. row_bytes must be a multiple of span and rows of tileRows; both pointers must be 16-byte aligned. It is plain CUDA and runs on any sm_70 or later device.
func SwizzleScales ¶
func SwizzleScales(scales []byte, rows, cols int, mode SwizzleMode) ([]byte, error)
SwizzleScales swizzles a 2D scale factor buffer for sm_100a tcgen05 shared memory bank alignment.
func TransformScaleLayout ¶
func TransformScaleLayout(rowMajorScales []uint32, rows, scaleCols int, alignedRows int) ([]uint32, error)
TransformScaleLayout transposes a [rows, scaleCols] row-major packed scale matrix into a [scaleCols, alignedRows] TMA-aligned column-major layout.
func TransformScaleLayoutColMajor ¶
func TransformScaleLayoutColMajor(rowMajorScales []uint32, rows, scaleCols int, alignedRows int) ([]uint32, error)
TransformScaleLayoutColMajor transposes a [rows, scaleCols] row-major packed scale matrix into a [scaleCols, alignedRows] TMA-aligned column-major layout, zero-filling padding rows in [rows, alignedRows).
func UnpackE2M1WithE4M3Scale ¶
UnpackE2M1WithE4M3Scale unpacks count float32 elements (a positive multiple of 16) from packed E2M1 nibbles and per-16 FP8 E4M3 scale factors.
func UnpackIQ2_XXS ¶
func UnpackIQ2_XXS(p *PrepackedTensor) ([]byte, error)
UnpackIQ2_XXS unpacks row-major IQ2_XXS payload and contiguous scales back to standard 66-byte blocks. Swizzled, interleaved and sparse host layouts are unsupported.
func UnpackOCPBlocks ¶
UnpackOCPBlocks unpacks count float32 elements (a positive multiple of 32) from 17-byte OCP MXFP4 blocks.
func UnpackQ8_0 ¶
func UnpackQ8_0(p *PrepackedTensor) ([]byte, error)
UnpackQ8_0 converts pre-packed Q8_0 tiles back into standard 34-byte interleaved Q8_0 blocks.
func UnpackUE8M0 ¶
UnpackUE8M0 unpacks count unsigned 8-bit UE8M0 biased exponents from little-endian packed uint32 words.
func UnswizzleScales ¶
func UnswizzleScales(swizzled []byte, rows, cols int, mode SwizzleMode) ([]byte, error)
UnswizzleScales restores the natural layout of a swizzled scale factor buffer. Because XOR swizzling is an involution (f(f(x)) = x), unswizzling applies the same mapping.
Types ¶
type ActivationFormat ¶
type ActivationFormat string
ActivationFormat identifies an activation tensor quantization and storage format.
const ( // ActFormatBF16 stores each activation element as a 16-bit bfloat16 value // in little-endian byte order without auxiliary scale factors. ActFormatBF16 ActivationFormat = "bf16" // ActFormatFP8PerToken quantizes each activation row into FP8 E4M3 elements // accompanied by one IEEE-754 binary32 scale per token row. ActFormatFP8PerToken ActivationFormat = "fp8_e4m3_pertoken" // ActFormatMXFP8Block32 quantizes each 32-element horizontal activation block // into OCP MXFP8 E4M3 elements accompanied by one UE8M0 power-of-two scale per block. ActFormatMXFP8Block32 ActivationFormat = "mxfp8_e4m3_ue8m0_b32" )
type ActivationLayout ¶
type ActivationLayout struct {
Format ActivationFormat
Rows int
Cols int
RowStrideBytes int
ScaleBlockSize int
ScaleStride int
Rounding RoundingContract
}
ActivationLayout describes the format, logical dimensions, 32-byte aligned row stride, scale granularity, scale row stride, and rounding contract of an OwnedActivation.
func NewActivationLayout ¶
func NewActivationLayout(format ActivationFormat, rows, cols int, rounding RoundingContract) (ActivationLayout, error)
NewActivationLayout constructs and validates an ActivationLayout with a 32-byte aligned RowStrideBytes computed via AlignedOutputStride.
Example ¶
package main
import (
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
layout, err := nnquant.NewActivationLayout(nnquant.ActFormatMXFP8Block32, 2, 64, nnquant.RoundNearestEven)
if err != nil {
panic(err)
}
fmt.Printf("format=%s stride=%d block=%d scaleStride=%d rounding=%s\n",
layout.Format, layout.RowStrideBytes, layout.ScaleBlockSize, layout.ScaleStride, layout.Rounding)
}
Output: format=mxfp8_e4m3_ue8m0_b32 stride=64 block=32 scaleStride=2 rounding=round_nearest_even
func (ActivationLayout) Validate ¶
func (l ActivationLayout) Validate() error
Validate checks that l satisfies all dimension, 32-byte row stride alignment, block divisibility, scale stride, and rounding invariants.
type BlockQ4_0 ¶
type BlockQ4_0 struct {
Scale uint16 // float16 scale factor
Quants [16]byte // 32 4-bit nibbles (low/high)
}
BlockQ4_0 represents a 32-element Q4_0 quantized block (18 bytes total).
type BlockQ8_1 ¶
BlockQ8_1 stores a normalized 32-element row block with fp16 d and s.
S is d*sum(q), computed after quantizing. ggml, the egraph root package and ds4-min store sum(v) before quantizing in the same field, so blocks from those producers and from this package cannot be mixed.
func RMSNormQ8_1 ¶
func RMSNormQ8_1(input, weight []float32, rows, cols int, epsilon float32, weighted bool) ([]BlockQ8_1, error)
RMSNormQ8_1 computes row-wise RMS normalization and Q8_1 quantization. When weighted is true, weight must contain one value per column and is applied after normalization. Quantization rounds to nearest integer and saturates to [-127,127].
type BlockScaleMMAConfig ¶
BlockScaleMMAConfig configures a Blackwell block-scaled Tensor Core MXFP4 matrix multiplication plan (m16n8k64 with 32-element UE8M0 scale blocks).
type BlockScaleMMAPlan ¶
type BlockScaleMMAPlan struct {
// contains filtered or unexported fields
}
BlockScaleMMAPlan holds a validated MXFP4 block-scaled GEMM lowering plan.
func NewBlockScaleMMAPlan ¶
func NewBlockScaleMMAPlan(cfg BlockScaleMMAConfig) (*BlockScaleMMAPlan, error)
NewBlockScaleMMAPlan validates cfg and constructs a BlockScaleMMAPlan.
Targets "sm_120a", "sm_120f", "sm_121a", and "sm_121f" lower to the Blackwell mma.sync.aligned.m16n8k64.row.col.kind::mxf4.block_scale.scale_vec::2X.f32.e2m1.e2m1.f32.ue8m0 instruction. Other targets, including the sm_100 family, return an error wrapping [cudaerrors.ErrUnsupported] when RequireHardwareMMA is true, or select the LUT fallback path when false.
Example ¶
package main
import (
"fmt"
"strings"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
plan, err := nnquant.NewBlockScaleMMAPlan(nnquant.BlockScaleMMAConfig{
M: 16,
N: 8,
K: 64,
TargetArch: "sm_121a",
RequireHardwareMMA: true,
})
if err != nil {
panic(err)
}
src, err := plan.EmitCUDA("mxfp4_gemm_tile")
if err != nil {
panic(err)
}
fmt.Printf("hw_mma=%t has_ptx=%t\n",
plan.UsesHardwareBlockScaleMMA(),
strings.Contains(src, "mma.sync.aligned.m16n8k64.row.col.kind::mxf4.block_scale.scale_vec::2X.f32.e2m1.e2m1.f32.ue8m0"))
}
Output: hw_mma=true has_ptx=true
func (*BlockScaleMMAPlan) Config ¶
func (p *BlockScaleMMAPlan) Config() BlockScaleMMAConfig
Config returns the validated configuration used to create p.
func (*BlockScaleMMAPlan) EmitCUDA ¶
func (p *BlockScaleMMAPlan) EmitCUDA(funcName string) (string, error)
EmitCUDA emits standalone NVRTC-clean CUDA C++ device code (without #include <stdint.h>) defining funcName and its warp-level m16n8k64 MXFP4 block-scaled Tensor Core helper alongside a software LUT fallback for targets outside the sm_120 family.
func (*BlockScaleMMAPlan) SimulateGEMM ¶
func (p *BlockScaleMMAPlan) SimulateGEMM(a [][32]float32, b [][32]float32) ([]float32, float64, error)
SimulateGEMM quantizes the M*(K/32) 32-element blocks of A (row-major [M x K]) and the N*(K/32) 32-element blocks of B (column-major / row-major B^T [N x K]) into 17-byte ConformantBlock32 records, evaluates the block-scaled dot products across K, and returns the M*N float32 output matrix along with its cosine similarity against an exact float64 reference GEMM.
func (*BlockScaleMMAPlan) UsesHardwareBlockScaleMMA ¶
func (p *BlockScaleMMAPlan) UsesHardwareBlockScaleMMA() bool
UsesHardwareBlockScaleMMA reports whether p uses the hardware Blackwell kind::mxf4.block_scale Tensor Core instruction rather than software fallback.
type BoxDescriptor ¶
type BoxDescriptor struct {
Rank int // 2 or 3
DataType DataType // Element data type
GlobalAddress uint64 // Base memory address (must be 16-byte aligned)
GlobalDims [3]uint64 // [dim0, dim1, dim2] in elements
GlobalStrides [3]int64 // Stride in bytes along dim1 and dim2 (multiples of 16)
BoxDims [3]uint32 // [box0, box1, box2] tile shape in elements
ElementStrides [3]uint32 // Positive traversal strides
Swizzle SwizzleMode // Shared memory bank swizzle
Interleave InterleaveMode // Byte interleaving layout
}
BoxDescriptor describes host tensor storage and a traversal box. A valid host descriptor is not necessarily a CUDA tensor-map descriptor. Unused dimension, box and element-stride entries may be zero or one; unused global-stride entries must be zero.
func (*BoxDescriptor) BoxSizeBytes ¶
func (b *BoxDescriptor) BoxSizeBytes() int
BoxSizeBytes returns the host box size, or zero for malformed or unrepresentable storage. Validate returns the corresponding error.
func (*BoxDescriptor) EncodeTensorMap ¶
func (b *BoxDescriptor) EncodeTensorMap() ([16]uint64, error)
EncodeTensorMap returns an error because tensor maps require opaque descriptor construction through the CUDA Driver API.
func (*BoxDescriptor) TotalSizeBytes ¶
func (b *BoxDescriptor) TotalSizeBytes() int64
TotalSizeBytes returns the padded host storage size, or zero for malformed or unrepresentable storage. Validate returns the corresponding error.
func (*BoxDescriptor) Validate ¶
func (b *BoxDescriptor) Validate(arch string) error
Validate checks the host storage contract for a named transformer target. It checks shape, known formats and modes, aligned nonoverlapping strides, representable storage and address extents. It does not verify payload bytes, encode a tensor map, or establish eligibility for a device operation.
func (*BoxDescriptor) ValidateTensorMap ¶
func (b *BoxDescriptor) ValidateTensorMap(arch string, operation TensorMapOperation) error
ValidateTensorMap checks descriptor fields for a tiled load or store under CUDA Driver API 13.4 cuTensorMapEncodeTiled and PTX ISA 9.4 tensor-copy rules. It supports Float16 and Float32, rank 2 or 3, the three interleave modes, and no swizzle or the standard 32-, 64- and 128-byte swizzles on the two named targets. Other packed formats and atom swizzles are explicitly unsupported. Stores are restricted to boxes contained in the logical tensor at the origin.
Success does not encode an opaque tensor map or validate payload contents, allocation, transfer coordinates, shared addresses or completion protocols. Descriptor construction through the driver and native execution remain separate. See https://docs.nvidia.com/cuda/cuda-driver-api/cuda_driver_api/group__CUDA__TENSOR__MEMORY.html.
Example ¶
package main
import (
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
b := nnquant.BoxDescriptor{
Rank: 2, DataType: nnquant.TypeFloat32, GlobalAddress: 4096,
GlobalDims: [3]uint64{256, 8, 1}, GlobalStrides: [3]int64{1024, 0, 0},
BoxDims: [3]uint32{256, 4, 1}, ElementStrides: [3]uint32{1, 1, 1},
}
fmt.Println(b.ValidateTensorMap(nnquant.ArchSM121a, nnquant.TensorMapTiledLoad))
fmt.Println(b.ValidateTensorMap(nnquant.ArchSM121a, nnquant.TensorMapTiledStore))
}
Output: <nil> <nil>
type CUDALowerBroadcast ¶
type CUDALowerBroadcast uint8
CUDALowerBroadcast mirrors the cudalower Broadcast enum.
type CUDALowerDType ¶
type CUDALowerDType uint8
CUDALowerDType mirrors the cudalower DType enum for extracted kernel emitters.
func (CUDALowerDType) String ¶
func (d CUDALowerDType) String() string
type CUDALowerOperand ¶
type CUDALowerOperand struct {
Name string
DType CUDALowerDType
Broadcast CUDALowerBroadcast
}
CUDALowerOperand mirrors the cudalower epilogue extra Operand.
type CUDALowerRMSNormDynQuantOpts ¶
type CUDALowerRMSNormDynQuantOpts struct {
Name string
Cols int
Eps float32
In CUDALowerDType
Residual bool
ScaleLayout CUDALowerScaleLayout
Params []string
}
CUDALowerRMSNormDynQuantOpts configures CUDALowerRMSNormDynQuantOpts.CUDA.
func (CUDALowerRMSNormDynQuantOpts) CUDA ¶
func (k CUDALowerRMSNormDynQuantOpts) CUDA() (string, error)
CUDA returns the device kernel source (without [Prelude]).
type CUDALowerScaleLayout ¶
type CUDALowerScaleLayout uint8
CUDALowerScaleLayout mirrors the cudalower ScaleLayout enum.
func (CUDALowerScaleLayout) String ¶
func (l CUDALowerScaleLayout) String() string
type CUDALowerStore ¶
type CUDALowerStore uint8
CUDALowerStore mirrors the cudalower GEMMStore enum.
type CUDALowerSwiGLUDynQuantOpts ¶
type CUDALowerSwiGLUDynQuantOpts struct {
Name string
Cols int
In CUDALowerDType
ScaleLayout CUDALowerScaleLayout
Params []string
}
CUDALowerSwiGLUDynQuantOpts configures CUDALowerSwiGLUDynQuantOpts.CUDA.
func (CUDALowerSwiGLUDynQuantOpts) CUDA ¶
func (k CUDALowerSwiGLUDynQuantOpts) CUDA() (string, error)
CUDA returns the device kernel source (without [Prelude]).
type CUDALowerTileEpilogue ¶
type CUDALowerTileEpilogue uint8
CUDALowerTileEpilogue mirrors the cudalower TileEpilogue enum.
func (CUDALowerTileEpilogue) String ¶
func (e CUDALowerTileEpilogue) String() string
type CUDALowerWeight ¶
type CUDALowerWeight uint8
CUDALowerWeight mirrors the cudalower WeightFormat enum.
func (CUDALowerWeight) String ¶
func (f CUDALowerWeight) String() string
type ConformantBlock32 ¶
ConformantBlock32 is a conformant 17-byte OCP Microscaling MXFP4 block encoding 32 E2M1 elements in 16 bytes (two 4-bit nibbles per byte, low nibble first) followed by a 1-byte unsigned E8M0 power-of-two scale.
func QuantizeConformantBlock32 ¶
func QuantizeConformantBlock32(vals [32]float32) ConformantBlock32
QuantizeConformantBlock32 quantizes 32 float32 values into a 17-byte ConformantBlock32 using an OCP UE8M0 power-of-two scale.
func (ConformantBlock32) MarshalBinary ¶
func (b ConformantBlock32) MarshalBinary() ([]byte, error)
MarshalBinary encodes b into its 17-byte OCP MXFP4 wire representation: 16 bytes of packed E2M1 nibbles followed by 1 byte of UE8M0 scale.
func (*ConformantBlock32) UnmarshalBinary ¶
func (b *ConformantBlock32) UnmarshalBinary(data []byte) error
UnmarshalBinary decodes a 17-byte OCP MXFP4 block into b.
type DataType ¶
type DataType string
DataType identifies tensor element precision and packing format.
const ( TypeIQ2_XXS DataType = "IQ2_XXS" // 2-bit codebook quantized super-blocks (256 elem/block) TypeQ8_0 DataType = "Q8_0" // 8-bit symmetric with float16 scale (32 elem/block) TypeFP8_E4M3 DataType = "FP8_E4M3" // 8-bit float: 1s, 4e, 3m (max 448.0) TypeFP8_E5M2 DataType = "FP8_E5M2" // 8-bit float: 1s, 5e, 2m (IEEE-like) TypeMXFP4 DataType = "MXFP4" // OCP Microscaling FP4 (E2M1) with per-block scale TypeFloat16 DataType = "Float16" // IEEE 754 binary16 TypeFloat32 DataType = "Float32" // IEEE 754 binary32 )
func (DataType) BitsPerElement ¶
BitsPerElement returns the nominal number of bits per element.
type DeviceActivation ¶
type DeviceActivation struct {
Values cuda.Slice[byte]
FP32Scales cuda.Slice[float32]
UE8M0Scales cuda.Slice[uint8]
Layout ActivationLayout
// contains filtered or unexported fields
}
DeviceActivation owns quantized activation buffers resident in GPU memory so downstream consumers can chain kernels without intermediate host copies.
func LaunchDeviceActivationQuant ¶
func LaunchDeviceActivationQuant( ctx context.Context, dev *cuda.Device, stream *cuda.Stream, target string, inDev cuda.Slice[float32], layout ActivationLayout, ) (act *DeviceActivation, retErr error)
LaunchDeviceActivationQuant compiles and launches OwnedActivationArtifact on dev and stream reading directly from inDev (length layout.Rows*layout.Cols) and returning a device-resident DeviceActivation without copying quantized outputs back to the host.
func (*DeviceActivation) CopyToHost ¶
func (a *DeviceActivation) CopyToHost() (*OwnedActivation, error)
CopyToHost allocates an OwnedActivation and copies Values and the active scale slice (FP32Scales or UE8M0Scales) from device to host memory.
func (*DeviceActivation) Release ¶
func (a *DeviceActivation) Release() error
Release frees the device buffers owned by a and marks a as released. Subsequent calls to Release are no-ops returning nil.
func (*DeviceActivation) Released ¶
func (a *DeviceActivation) Released() bool
Released reports whether a is nil or has been released via DeviceActivation.Release.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine manages compiled GPU functions for MXFP4 operations.
func NewEngine ¶
NewEngine compiles and loads MXFP4 GPU kernels on dev.
On error NewEngine usually returns a nil engine. It returns a non-nil, partially initialized engine with the error only when it still owns a module it could not release: Load reported an error after loading the module or attached a cleanup io.Closer to its error, or a kernel lookup failed and unloading the module also failed. The partial engine refuses launches; call Close, before closing dev, to release what it holds.
func (*Engine) Close ¶
Close releases the loaded CUDA module. Complete outstanding work before closing the engine, and close the engine before its device. Repeated calls are harmless.
func (*Engine) Dequantize ¶
func (e *Engine) Dequantize( packed cuda.Slice[uint8], scales cuda.Slice[float32], out cuda.Slice[float32], totalElements, groupSize int, ) error
Dequantize launches GPU-side dequantization from packed uint8 + scales into float32 destination.
func (*Engine) LinearGEMV ¶
func (e *Engine) LinearGEMV( x cuda.Slice[float32], packed cuda.Slice[uint8], scales cuda.Slice[float32], outY cuda.Slice[float32], inDim, outDim, groupSize int, ) error
LinearGEMV launches fused MXFP4 matrix-vector multiplication on the GPU's null stream. Use Engine.LinearGEMVOn to order it with other stream work.
func (*Engine) LinearGEMVOn ¶
func (e *Engine) LinearGEMVOn( s *cuda.Stream, x cuda.Slice[float32], packed cuda.Slice[uint8], scales cuda.Slice[float32], outY cuda.Slice[float32], inDim, outDim, groupSize int, ) error
LinearGEMVOn is Engine.LinearGEMV on stream s. A nil s is the null stream. packed holds outDim rows of inDim/2 bytes and scales one float per group of groupSize weights, in row-major order, as QuantizeMatrix produces them.
type InterleaveMode ¶
type InterleaveMode uint32
InterleaveMode describes tensor byte interleaving.
const ( InterleaveNone InterleaveMode = 0 Interleave16B InterleaveMode = 1 Interleave32B InterleaveMode = 2 )
type LayoutTransformer ¶
type LayoutTransformer struct {
// contains filtered or unexported fields
}
LayoutTransformer prepares tensor layouts into hardware-aligned TMA 2D/3D boxes.
func NewLayoutTransformer ¶
func NewLayoutTransformer(arch string, dt DataType, opts ...Option) (*LayoutTransformer, error)
NewLayoutTransformer creates a transformer for the target architecture and data type.
Example ¶
package main
import (
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
// Pre-pack a 2D weight matrix for Blackwell sm_121a TMA transfer
transformer, err := nnquant.NewLayoutTransformer(
nnquant.ArchSM121a,
nnquant.TypeFP8_E4M3,
nnquant.WithAlignment(16),
)
if err != nil {
panic(err)
}
rawWeights := make([]byte, 64*100) // 64 rows, 100 columns (1 byte per FP8)
tensor, err := transformer.Transform2D(rawWeights, 64, 100)
if err != nil {
panic(err)
}
fmt.Printf("Arch: %s\n", tensor.Arch)
fmt.Printf("Rank: %d\n", tensor.BoxDesc.Rank)
fmt.Printf("RowStride: %d bytes\n", tensor.BoxDesc.GlobalStrides[0])
fmt.Printf("BoxDims: [%d, %d]\n", tensor.BoxDesc.BoxDims[0], tensor.BoxDesc.BoxDims[1])
}
Output: Arch: sm_121a Rank: 2 RowStride: 112 bytes BoxDims: [112, 32]
func (*LayoutTransformer) Transform2D ¶
func (lt *LayoutTransformer) Transform2D(src []byte, rows, cols int) (*PrepackedTensor, error)
Transform2D transforms a 2D matrix into hardware-aligned TMA 2D tensor boxes. It pads row strides to satisfy 16-byte address alignment and 128-byte box boundary constraints.
func (*LayoutTransformer) Transform3D ¶
func (lt *LayoutTransformer) Transform3D(src []byte, depth, rows, cols int) (*PrepackedTensor, error)
Transform3D transforms a 3D volume into hardware-aligned TMA 3D tensor boxes.
type NVFP4GEMVConfig ¶
type NVFP4GEMVConfig struct {
N int // output features (weight rows), a positive multiple of 16
K int // input features, a positive multiple of 64
TargetArch string // sm_120a, sm_120f, sm_121a, or sm_121f
}
NVFP4GEMVConfig configures EmitNVFP4GEMV.
type NVFP4Weight ¶
type NVFP4Weight struct {
Rows int // output features
Cols int // input features, a multiple of 64
Packed []byte
Scales []uint8
TensorScale float32
}
NVFP4Weight is a linear-layer weight quantized to two-level NVFP4: E2M1 elements, one unsigned E4M3 scale per 16-element block along a row, and one float32 scale for the whole tensor. Element (r, c) dequantizes to
E2M1(nibble) * E4M3(Scales[r*Cols/16 + c/16]) * TensorScale
Packed holds Rows*Cols/2 bytes, row-major, low nibble first. Scales holds Rows*Cols/16 bytes, row-major. Both are the layouts the m16n8k64 kind::mxf4nvf4 scale_vec::4X fragments read directly: with the weight as the row-major A operand, each lane loads its A registers and its scale-a word with single aligned 32-bit loads (see EmitNVFP4GEMV).
TensorScale is amax/(6*448), so the largest block scale lands at the top of the E4M3 range; it is zero for an all-zero tensor.
func PackNVFP4Weight ¶
func PackNVFP4Weight(w []float32, rows, cols int) (*NVFP4Weight, error)
PackNVFP4Weight quantizes the row-major [rows, cols] weight w (the layout of a Hugging Face nn.Linear weight: one row per output feature) into NVFP4. cols must be a positive multiple of 64, the K of one m16n8k64 step.
Elements round as cvt.rn.satfinite.e2m1x2.f32 does; block scales round to nearest E4M3, so a block whose maximum rounds its scale down saturates at ±6.
Example ¶
package main
import (
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
// A 1x64 weight: one 16-element block of 3, the rest 0.75.
w := make([]float32, 64)
for i := range w {
w[i] = 0.75
}
for i := range 16 {
w[i] = 3
}
q, err := nnquant.PackNVFP4Weight(w, 1, 64)
if err != nil {
panic(err)
}
x := make([]float32, 64)
for i := range x {
x[i] = 1
}
y, err := q.GEMV(x)
if err != nil {
panic(err)
}
fmt.Printf("packed=%dB scales=%dB tensor_scale=%.6g y=%.4g\n", len(q.Packed), len(q.Scales), q.TensorScale, y[0])
}
Output: packed=32B scales=4B tensor_scale=0.00111607 y=84
func (*NVFP4Weight) Dequantize ¶
func (q *NVFP4Weight) Dequantize() ([]float32, error)
Dequantize returns the row-major [Rows, Cols] float32 weight q encodes.
func (*NVFP4Weight) GEMV ¶
func (q *NVFP4Weight) GEMV(x []float32) ([]float32, error)
GEMV returns y = W x for the dequantized weight W, accumulating in float64. It is the host oracle for NVFP4 GEMV kernels: pass x through PackE2M1WithE4M3Scale and UnpackE2M1WithE4M3Scale first to model a kernel that also quantizes its activations (W4A4).
type NormQuantCandidate ¶
type NormQuantCandidate struct {
Name string
Buffers map[string]layout.Tile
Launches []NormQuantLaunch
WorkspaceBytes int
}
NormQuantCandidate describes a legal implementation before compilation. Buffers are distinct allocations: input and optional weight contain float32, norm contains float32, and output contains packed 36-byte Q8_1 blocks. The output layout is expressed in bytes, including both scale fields. Workspace is the norm buffer size; it remains required until secondary consumers finish. Resource registers and shared memory come from compiled artifacts, not this description. Descriptions are detached and may be modified by their owner.
func RMSNormQ8_1Candidates ¶
func RMSNormQ8_1Candidates(rows, cols int, weighted, materializeNorm bool) ([]NormQuantCandidate, error)
RMSNormQ8_1Candidates returns unfused and, when legal, fused alternatives. materializeNorm means an external consumer needs the normalized float32 values; the fused kernel has no such output and is then excluded. weighted requires one float32 weight per column. Epsilon and actual input values must separately satisfy RMSNormQ8_1's numerical contract before native execution. This checks dimensions, CUDA grid limits, layouts and complete buffer sizes without allocating tensor storage or calling CUDA. No performance ranking is implied by result order. Compile using RMSNormQ8_1UnfusedArtifacts or RMSNormQ8_1Artifact according to the candidate name.
type NormQuantLaunch ¶
NormQuantLaunch describes one entry and its buffer bindings. Input and Output name entries in NormQuantCandidate.Buffers. All launches use the seven-parameter ABI described by RMSNormQ8_1UnfusedSource. Preserve slice order on one stream.
type Option ¶
type Option func(*LayoutTransformer)
Option configures a LayoutTransformer.
func WithAlignment ¶
WithAlignment sets the byte alignment for tensor strides (default: 16).
func WithBaseAddress ¶
WithBaseAddress sets the mock or actual GPU global base address (must be 16-byte aligned).
func WithBoxDims ¶
WithBoxDims sets the desired TMA box tile dimensions [box0, box1, box2].
func WithInterleave ¶
func WithInterleave(mode InterleaveMode) Option
WithInterleave configures the tensor byte interleaving mode.
func WithSwizzle ¶
func WithSwizzle(mode SwizzleMode) Option
WithSwizzle configures the shared memory bank swizzle mode.
type OwnedActivation ¶
type OwnedActivation struct {
Values []byte
UE8M0Scales []uint8
FP32Scales []float32
Layout ActivationLayout
// contains filtered or unexported fields
}
OwnedActivation holds quantized activation values, companion scale factors, layout metadata, and explicit lifetime state. Callers must not use an OwnedActivation after calling OwnedActivation.Release.
func LaunchOwnedActivationQuant ¶
func LaunchOwnedActivationQuant(ctx context.Context, dev *cuda.Device, stream *cuda.Stream, target string, input []float32, layout ActivationLayout) (act *OwnedActivation, retErr error)
LaunchOwnedActivationQuant compiles and loads OwnedActivationArtifact for target and layout.Format on dev, allocates device buffers for input, values_out, and scales_out, launches the quantization kernel on stream, synchronizes stream, copies the quantized output back into a newly allocated OwnedActivation, and releases the temporary device buffers and module.
func QuantizeActivation ¶
func QuantizeActivation(input []float32, layout ActivationLayout) (*OwnedActivation, error)
QuantizeActivation quantizes a contiguous [layout.Rows, layout.Cols] float32 activation tensor into a newly allocated OwnedActivation honoring layout.Format, layout.Rounding, and layout.RowStrideBytes.
Example ¶
package main
import (
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
layout, err := nnquant.NewActivationLayout(nnquant.ActFormatMXFP8Block32, 1, 32, nnquant.RoundNearestEven)
if err != nil {
panic(err)
}
input := make([]float32, 32)
for i := range input {
input[i] = float32((i%4)+1) * 16.0
}
act, err := nnquant.QuantizeActivation(input, layout)
if err != nil {
panic(err)
}
deq, err := act.DequantizeFloat32()
if err != nil {
panic(err)
}
if err := act.Release(); err != nil {
panic(err)
}
fmt.Printf("deq0=%.1f deq1=%.1f scales=%d released=%v\n",
deq[0], deq[1], len(act.UE8M0Scales), act.Released())
}
Output: deq0=16.0 deq1=32.0 scales=1 released=true
func (*OwnedActivation) DequantizeFloat32 ¶
func (a *OwnedActivation) DequantizeFloat32() ([]float32, error)
DequantizeFloat32 reconstructs the contiguous [Rows * Cols] float32 activation tensor from a's quantized values and scales. It returns an error if a is nil, has been released via OwnedActivation.Release, or contains malformed data.
func (*OwnedActivation) Release ¶
func (a *OwnedActivation) Release() error
Release zeros the backing storage of Values, UE8M0Scales, and FP32Scales and marks a as released. Subsequent calls to Release are no-ops returning nil.
func (*OwnedActivation) Released ¶
func (a *OwnedActivation) Released() bool
Released reports whether a is nil or has been released via OwnedActivation.Release.
type PrepackedTensor ¶
type PrepackedTensor struct {
Arch string
Type DataType
BoxDesc BoxDescriptor
Payload []byte // Host tensor storage
Scales []byte // Contiguous or swizzled scale factors
Metadata []byte // 2:4 structured sparsity metadata (if sparse)
// contains filtered or unexported fields
}
PrepackedTensor contains host payload bytes, optional scales and sparsity metadata, and their layout description. It does not own device allocations.
Example (Iq2Blocks) ¶
package main
import (
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
raw := make([]byte, 66)
raw[2] = 7
p, err := nnquant.RepackIQ2_XXS(raw, 1, 256)
if err != nil {
fmt.Println(err)
return
}
decoded, err := nnquant.UnpackIQ2_XXS(p)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(decoded), decoded[2])
}
Output: 66 7
func PackMXFP4 ¶
func PackMXFP4(src []float32, rows, cols int, groupSize int) (*PrepackedTensor, error)
PackMXFP4 quantizes float32 values into 16-byte-aligned row-major MXFP4 payload bytes, float16 group scales, and up to 128-byte box metadata. Elements round as cvt.rn.satfinite.e2m1x2.f32 does (cuda.E2M1bits): to nearest, ties to even, saturating to ±6, with NaN encoding as +6.
Example ¶
package main
import (
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
// Quantize float32 weights into 128-byte hardware-aligned MXFP4 tiles
src := make([]float32, 32*64)
for i := range src {
src[i] = float32((i % 7) - 3)
}
tensor, err := nnquant.PackMXFP4(src, 32, 64, 32)
if err != nil {
panic(err)
}
fmt.Printf("Type: %s\n", tensor.Type)
fmt.Printf("Payload bytes: %d\n", len(tensor.Payload))
fmt.Printf("Scale factors: %d\n", len(tensor.Scales)/2)
}
Output: Type: MXFP4 Payload bytes: 1024 Scale factors: 64
func ParseZeroCopy ¶
func ParseZeroCopy(data []byte) (*PrepackedTensor, error)
ParseZeroCopy parses a prepacked buffer directly without copying payload data. It slices directly into data, confirming 128-byte hardware alignment for zero-copy mmap.
func QuantizeFP8 ¶
func QuantizeFP8(src []float32, rows, cols int, dt DataType) (*PrepackedTensor, error)
QuantizeFP8 converts a float32 matrix into 16-byte-aligned row-major FP8 E4M3 or E5M2 payload bytes with up to 128-byte box metadata, rounding to nearest even and saturating overflows and infinities via Float32ToE4M3 and Float32ToE5M2.
func Read ¶
func Read(r io.Reader) (*PrepackedTensor, error)
Read deserializes a pre-packed tensor from an io.Reader.
func RepackIQ2_XXS ¶
func RepackIQ2_XXS(rawBlocks []byte, rows, cols int) (*PrepackedTensor, error)
RepackIQ2_XXS separates 66-byte IQ2_XXS super-blocks into 16-byte-aligned row-major 64-byte payload rows, 2-byte scales, and up to 128-byte box metadata.
func RepackQ8_0 ¶
func RepackQ8_0(rawBlocks []byte, rows, cols int) (*PrepackedTensor, error)
RepackQ8_0 separates standard 34-byte Q8_0 blocks into row-major quantization bytes and two-byte scale entries. Device alignment and tensor-map construction are caller responsibilities.
func (*PrepackedTensor) MarshalBinary ¶
func (p *PrepackedTensor) MarshalBinary() ([]byte, error)
MarshalBinary serializes the pre-packed tensor into an in-memory byte buffer.
func (*PrepackedTensor) Write ¶
func (p *PrepackedTensor) Write(w io.Writer) error
Write serializes the pre-packed tensor into an aligned binary format suitable for mmap.
func (*PrepackedTensor) ZeroCopy ¶
func (p *PrepackedTensor) ZeroCopy() bool
ZeroCopy reports whether the payload was sliced directly from an input buffer without copy.
type Q8CopyFixture ¶
type Q8CopyFixture struct {
Source string
GridBlocks, BlockThreads int
DynamicBytes int64
RawBytes int
PrepackReadBytes, PrepackWriteBytes int
WorkspaceBytes int
}
Q8CopyFixture is a synchronous Q8_0 payload-and-scale consumer. Launch Source's staged_q8_copy entry with one-dimensional grid and blocks using GridBlocks, BlockThreads and DynamicBytes. Arguments are payload, scales, and output device pointers, in that order. Output holds standard 34-byte Q8_0 blocks; no scale conversion or arithmetic is performed.
PrepackReadBytes and PrepackWriteBytes charge the preceding block repack; WorkspaceBytes includes its payload and scale storage. The kernel reads and writes RawBytes each. These are byte counts, not timing evidence. The caller owns nonaliasing device buffers through completion and configures any required dynamic-shared opt-in. Source is not native qualification.
func StagedQ8CopyFixture ¶
func StagedQ8CopyFixture(plan *tilelayout.Plan, tensor *PrepackedTensor) (Q8CopyFixture, error)
StagedQ8CopyFixture consumes stage0 of plan and the checked host layout of tensor. It uses ordinary byte loads and a CTA barrier, not a tensor map or TMA swizzle. Target limits must exist as probed device records. Only dynamic alignments up to 128 bytes are supported by this source fixture.
Example ¶
tensor, err := RepackQ8_0(make([]byte, 34), 1, 32)
if err != nil {
panic(err)
}
limits, err := tilelayout.LimitsFromDevice("sm_121a")
if err != nil {
panic(err)
}
plan, err := tilelayout.NewPlan(limits)
if err != nil {
panic(err)
}
if _, err := plan.Add(tilelayout.Request{Name: "stage0", Size: 34, Alignment: 16, Dynamic: true}); err != nil {
panic(err)
}
f, err := StagedQ8CopyFixture(plan, tensor)
if err != nil {
panic(err)
}
fmt.Println(f.GridBlocks, f.BlockThreads, f.DynamicBytes, f.WorkspaceBytes)
Output: 1 34 34 34
type Q8Storage ¶
type Q8Storage struct {
Rows, Cols, RowStride int
Blocks int
RawBytes int
PayloadBytes int
ScaleBytes int
WorkspaceBytes int
}
Q8Storage describes the host byte layout of Q8_0 blocks. Each block has 32 signed quantization bytes and a separate, unchanged two-byte scale. Byte counts describe conversion work and storage, not measured time.
func DescribeQ8 ¶
func DescribeQ8(p *PrepackedTensor) (Q8Storage, error)
DescribeQ8 validates the row-major, separately scaled Q8_0 storage consumed by UnpackQ8_0. It does not validate a CUDA tensor map or own device memory. Swizzled, interleaved and sparse host payloads are unsupported.
Example ¶
p, err := RepackQ8_0(make([]byte, 34), 1, 32)
if err != nil {
panic(err)
}
s, err := DescribeQ8(p)
if err != nil {
panic(err)
}
fmt.Println(s.RawBytes, s.PayloadBytes, s.ScaleBytes, s.WorkspaceBytes)
Output: 34 32 2 34
type QuantFormat ¶
type QuantFormat string
QuantFormat identifies a weight quantization format.
const ( FormatQ4_0 QuantFormat = "Q4_0" // 4-bit symmetric with float16 scale per 32 elements FormatQ8_0 QuantFormat = "Q8_0" // 8-bit symmetric with float16 scale per 32 elements )
type QuantizedMatrix ¶
QuantizedMatrix holds packed 4-bit weights and per-group scale factors.
func QuantizeMatrix ¶
func QuantizeMatrix(rows, cols int, src []float32, groupSize int) (*QuantizedMatrix, error)
QuantizeMatrix quantizes a 2D row-major float32 matrix.
type RoundingContract ¶
type RoundingContract uint8
RoundingContract specifies the mantissa rounding rule used when quantizing float32 activations into ActFormatBF16, ActFormatFP8PerToken, or ActFormatMXFP8Block32.
const ( // RoundNearestEven rounds ties to the nearest representable value with an // even least-significant mantissa bit. RoundNearestEven RoundingContract = iota + 1 // RoundTowardZero truncates magnitudes toward zero. RoundTowardZero )
func (RoundingContract) String ¶
func (r RoundingContract) String() string
String returns the canonical name of r.
type ScaleRecipe ¶
type ScaleRecipe uint8
ScaleRecipe selects the block scale representation used by per-token FP8 quantization kernels.
const ( // ScaleRecipeFloat32 stores one IEEE-754 binary32 scale per quantization block. ScaleRecipeFloat32 ScaleRecipe = iota // ScaleRecipeUE8M0 stores one unsigned 8-bit biased power-of-two exponent // (2^(exp-127)) per quantization block, packed four per uint32 word. ScaleRecipeUE8M0 )
func (ScaleRecipe) String ¶
func (r ScaleRecipe) String() string
String returns the canonical name of r.
type SwiGLUQuantConfig ¶
type SwiGLUQuantConfig struct {
Tokens int
IntermediateDim int
BlockSize int
Recipe ScaleRecipe
OutputRowAlignBytes int
ScaleColAlignBytes int
}
SwiGLUQuantConfig configures fused SwiGLU activation and per-token block FP8 E4M3 quantization.
type SwizzleMode ¶
type SwizzleMode uint32
SwizzleMode names a descriptor's requested swizzle, not a bank-conflict result.
const ( SwizzleNone SwizzleMode = 0 Swizzle32B SwizzleMode = 1 Swizzle64B SwizzleMode = 2 Swizzle128B SwizzleMode = 3 Swizzle128BAtom32B SwizzleMode = 4 )
func (SwizzleMode) String ¶
func (s SwizzleMode) String() string
String returns the human-readable swizzle mode name.
type TensorMapOperation ¶
type TensorMapOperation string
TensorMapOperation names the bounded tiled copy operations checked here.
const ( TensorMapTiledLoad TensorMapOperation = "tiled-load" TensorMapTiledStore TensorMapOperation = "tiled-store" )
type UE8M0 ¶
type UE8M0 uint8
UE8M0 represents an OCP Microscaling unsigned 8-bit biased power-of-two scale exponent (2^(int(u)-127)). Code 0xFF (255) encodes NaN.
Example ¶
package main
import (
"fmt"
nnquant "github.com/tmc/lib/nvidia/x/nn/quant"
)
func main() {
// Original float32 activations
weights := []float32{
0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0,
-0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0, 0.0,
0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 0.0,
-0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0, 0.0,
}
packed, scales, err := nnquant.Quantize(weights, 32)
if err != nil {
fmt.Printf("quantize error: %v\n", err)
return
}
dst := make([]float32, len(weights))
if err := nnquant.Dequantize(packed, scales, 32, dst); err != nil {
fmt.Printf("dequantize error: %v\n", err)
return
}
fmt.Printf("Original len: %d, Packed bytes: %d, Scales: %d\n", len(weights), len(packed), len(scales))
fmt.Printf("Dequantized first 4: [%.1f, %.1f, %.1f, %.1f]\n", dst[0], dst[1], dst[2], dst[3])
}
Output: Original len: 32, Packed bytes: 16, Scales: 1 Dequantized first 4: [0.0, 0.5, 1.0, 1.5]
func Float32ToUE8M0 ¶
Float32ToUE8M0 converts a positive float32 scale factor v into a UE8M0 power-of-two exponent via cuda.E8M0bits (ceil(log2(v))+127, saturating v <= 2^-127 to 0, subnormals in (2^-127, 2^-126) to 1, and v >= 2^127 including +Inf to 0xFE). Non-positive values (including -0 and -Inf) clamp to 0; NaN maps to 0xFF.
func (UE8M0) Float32 ¶
Float32 returns the float32 power-of-two value 2^(int(u)-127) represented by u, or NaN when u is 0xFF, via cuda.E8M0frombits.
Source Files
¶
- binary.go
- block_scale_mma.go
- cuda.go
- cudalower_dynquant.go
- cudalower_types.go
- doc.go
- egraph_codegen.go
- fp8_gemv.go
- iq2_xxs.go
- layout.go
- mxfp4.go
- mxfp4_ue8m0.go
- mxfp8.go
- norm_candidates.go
- norm_unfused.go
- nvfp4_e4m3.go
- nvfp4_mma.go
- nvfp4_mma_accumulate.go
- nvfp4_weight.go
- owned_activation.go
- owned_activation_kernel.go
- prepack_quant.go
- q8.go
- q8_fixture.go
- quant.go
- sparsity.go
- specs.go
- swiglu_quant.go
- swizzle_repack.go
- testdata_generate.go
- tma_sf.go
- types.go
- ue8m0.go
Directories
¶
| Path | Synopsis |
|---|---|
|
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.
|
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. |