Documentation
¶
Overview ¶
Package tcgen05 implements Blackwell (sm_100a, sm_103a, sm_100f, sm_103f) and Vera Rubin (sm_107a, sm_107f) Tensor Memory (TMEM) Fifth- and Sixth-Generation Tensor Core (tcgen05 / PTX ISA 9.4), FlashAttention-4 paged and absorbed Multi-head Latent Attention (MLA), 2:4 structured sparsity and spcompress, and Cluster Launch Control (CLC) kernel emitters, hardware descriptors, and GB200/GB300/VR200 residency planners.
Kernels emitted by this package route every PTX instruction through a self-contained device prelude so the same CUDA C++ source compiles for sm_100a, sm_103a, and sm_107a with nvcc and executes on the host CPU via cudahostemu:
- TCGen05GEMM and TCGen05SparseGEMM emit dense and 2:4 structured sparse `.cta_group::2` block-scaled NVFP4/MXFP4/MXFP8 UMMA pipelines with TMEM lifecycle tracking (`tcgen05.alloc` through `tcgen05.dealloc`).
- TCGen05PagedAttention and TCGen05MLAPagedAttention emit FlashAttention-4 and DeepSeek MLA absorbed-KV 5-role warp-specialized ping-pong TMEM pipelines with `scale_vec::4X` and 2x SFU exponential emulation on sm_103a and sm_107a.
- [RubinBlockScaledUMMA] emits Vera Rubin sm_107a / sm_107f PTX ISA 9.4 dual-CTA `.cta_group::2` block-scaled NVFP4/MXFP4/MXFP6/MXFP8 kernels with TMA L2 multicast (`cp.async.bulk.tensor.2d.multicast::cluster`), hardware `ld.global.red` / `st.global.spcompress` activation compression, and 256 KB per-SM TMEM budgeting.
Each tcgen05 kernel also produces a formal TraceEvent sequence verified by github.com/tmc/lib/nvidia/x/tile/layout.VerifyTrace.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia.
Index ¶
- Constants
- Variables
- func ApplyMRoPEReference(x [][]float32, posTHW [][3]int32, spec MRoPESpec) ([][]float32, error)
- func ApplyRoPEReference(x [][]float32, pos []int32, spec MRoPESpec) ([][]float32, error)
- func BuildTubeletTMADescriptor(spec TubeletPatchSpec, baseAddr uint64) (layout.Descriptor, error)
- func CLCHelpers() string
- func CUDALowerNVFP4WGMMAHelpers(dequant1w, dequant2w string) string
- func CUDALowerWGMMARSFunc(name string, n int) string
- func DecodeFP6E2M3(code uint8) float32
- func DecodeFP6E3M2(code uint8) float32
- func DecodeUE8M0(code uint8) float32
- func DecompressReference(cdata []float32, mdata []uint32, M, N int) ([]float32, error)
- func DequantNVFP4(dst []float32, packed, scales []uint8, global float32) error
- func DequantizeMXFP4E2M1(packed []uint8, scales []uint8) []float32
- func DequantizeMXFP8E4M3(codes []uint8, scales []uint8) []float32
- func EncodeE2M1(v float32) uint8
- func EncodeFP6E2M3(v float32) uint8
- func EncodeFP6E3M2(v float32) uint8
- func EncodeUE8M0(scale float32) uint8
- func FlashLogitsGumbel(seed uint64, row, token int) float64
- func FromE2M1(code uint8) float32
- func FromUE8M0Bits(code uint8) float32
- func GQAAttention(q, k, v []float32, tokens, numQHeads, numKVHeads, headDim int) (scores, out []float32, err error)
- func LayerNormL2VJP(z, v []float64, eps float64) (loss float64, g []float64)
- func LoRAKernelArgs(plan LoRAGatherPlan) (order, start, end, rank, aoff, boff []int32, scale []float32)
- func OrthonormalityError(u []float32, dim, rank int) float64
- func PackFP6x4(c0, c1, c2, c3 uint8) [3]uint8
- func Philox4x32_10(ctr [4]uint32, key [2]uint32) [4]uint32
- func Prune2To4F32(a []float32, M, K int) (compressed []float32, meta []uint32, prunedDense []float32, err error)
- func Prune2To4NVFP4(aPacked []uint8, aScales []uint8, M, K int) (compPacked []uint8, compScales []uint8, meta []uint32, err error)
- func Quantize3BitLUTB(b []float32, K, N int) (indices []uint8, lutE4M3 []uint8, bScales []uint8, dequantized []float32, ...)
- func QuantizeLearnedLUTB(b, hessianDiag []float32, K, N, maxIters int) (indices, lutE4M3, bScales []uint8, dequantized []float32, err error)
- func QuantizeMXFP4E2M1(src []float32) (packed []uint8, scales []uint8)
- func QuantizeMXFP8E4M3(src []float32) (codes []uint8, scales []uint8)
- func ReferenceFusedLoRA(x, w [][]float32, tokenAdapterIDs []int, aPool, bPool [][]float32, ...) ([][]float32, error)
- func SpCompress2to4F32(in []float32, op SpCompressOp) (cdata []float32, mdata []uint32, err error)
- func SpDecompress2to4F32(cdata []float32, mdata []uint32, totalElems int) ([]float32, error)
- func SparseMMAActivationDenseWeight(act DynSparseTile, w []float32, n int) ([]float32, error)
- func SplitBF16(f float32) (hi, lo uint16)
- func SwiGLU(gate, up []float32) []float32
- func TMEMColumns(arch string) uint16
- func Unpack2To4F32(compressed []float32, meta []uint32, M, K int) ([]float32, error)
- func UnpackFP6x4(b [3]uint8) [4]uint8
- func UnpackIndices3Bit(p [12]byte) [32]uint8
- func ValidateLUTColumn(col uint32) error
- func VerifyDeadlockFreedom(s Schedule, numTiles int) error
- func WGMMAE4M3Func(name string, n int) string
- func WGMMAFunc(name string, n int) string
- type BlockFP8GEMM
- type BlockNVFP4GEMM
- type CLCPersistentTileGEMM
- func (g CLCPersistentTileGEMM) CUDA() (string, error)
- func (g CLCPersistentTileGEMM) Launcher() (string, error)
- func (g CLCPersistentTileGEMM) Reference(m int, x []uint16, w GEMMWeights) ([]float32, error)
- func (g CLCPersistentTileGEMM) SharedBytes() int
- func (g CLCPersistentTileGEMM) Source() (string, error)
- func (g CLCPersistentTileGEMM) TotalTiles(m int) int
- type CUDALowerBroadcast
- type CUDALowerDType
- type CUDALowerNVFP4QuantOpts
- type CUDALowerOperand
- type CUDALowerRubinF32x2NormOpts
- type CUDALowerRubinUE5M3Opts
- type CUDALowerSM120AttnOpts
- type CUDALowerSM120GEMMOpts
- type CUDALowerScaleLayout
- type CUDALowerSkinnyGEMMOpts
- type CUDALowerSkinnyMMAOpts
- type CUDALowerStore
- type CUDALowerTileEpilogue
- type CUDALowerTileGEMMOpts
- type CUDALowerUMMAGEMMOpts
- type CUDALowerWeight
- type CollectorOp
- type CompressedKVPage
- type DynSparseSwiGLUResult
- type DynSparseTarget
- type DynSparseTile
- type ElemType
- type FlashLogitsOutput
- type FlashLogitsSchedule
- func (s FlashLogitsSchedule) CUDA() (string, error)
- func (s FlashLogitsSchedule) CUDAFile() (string, error)
- func (s FlashLogitsSchedule) ExecuteReference(h, wVocab []float32, draftTokens []int32) (FlashLogitsOutput, error)
- func (s FlashLogitsSchedule) Tiles() int
- func (s FlashLogitsSchedule) TraceEvents() []layout.TraceEvent
- func (s FlashLogitsSchedule) Validate() error
- type GB300ResidencyPlan
- type GB300Spec
- type GEMMWeights
- type InstDesc
- type JaggedAttention
- func (a JaggedAttention) CUDA() (string, error)
- func (a JaggedAttention) Grid(sched JaggedBatchSchedule, heads int) (grid, block [3]int)
- func (a JaggedAttention) Reference(sched JaggedBatchSchedule, q, k, v [][]float32, posTHW [][3]int32) ([][]float32, error)
- func (a JaggedAttention) SharedBytes() int
- func (a JaggedAttention) TMEMColumns() uint32
- func (a JaggedAttention) TraceEvents(kvTiles int) []layout.TraceEvent
- func (a JaggedAttention) Validate() error
- type JaggedBatchSchedule
- type KVCompressSchedule
- type KVCompressTask
- type KVCompressorPartition
- type Kind
- type Lambda
- type LdRedOp
- type LearnedLUTBlock
- type LoRAAdapterSlot
- type LoRAGatherPlan
- type LoRASegment
- type MRoPESpec
- type Problem
- type ProtocolError
- type ProtocolErrorKind
- type RoleAssignment
- type RoleDemand
- type RubinSpCompressDecompressKernel
- func (k RubinSpCompressDecompressKernel) CUDA() (string, error)
- func (k RubinSpCompressDecompressKernel) CUDAFile() (string, error)
- func (k RubinSpCompressDecompressKernel) Grid() (grid, block [3]int)
- func (k RubinSpCompressDecompressKernel) Reference(in []float32) (cdata []float32, mdata []uint32, reconstructed []float32, err error)
- func (k RubinSpCompressDecompressKernel) Validate() error
- type SSMChunkSchedule
- func (s SSMChunkSchedule) CUDA() (string, error)
- func (s SSMChunkSchedule) CUDAFile() (string, error)
- func (s SSMChunkSchedule) Grid(heads, ctas int) (grid, block [3]int)
- func (s SSMChunkSchedule) Reference(in SSMInput) (out, state [][]float32, err error)
- func (s SSMChunkSchedule) ReferenceChunked(in SSMInput) (out, state [][]float32, err error)
- func (s SSMChunkSchedule) SeqLen() int
- func (s SSMChunkSchedule) SharedBytes() int
- func (s SSMChunkSchedule) TMEMColumns() uint32
- func (s SSMChunkSchedule) TraceEvents() []layout.TraceEvent
- func (s SSMChunkSchedule) Validate() error
- type SSMInput
- type SSMVariant
- type ScaleType
- type Schedule
- type SegmentedLoRASchedule
- func (s SegmentedLoRASchedule) CUDA() (string, error)
- func (s SegmentedLoRASchedule) CUDAFile() (string, error)
- func (s SegmentedLoRASchedule) Grid(tokens int) (grid, block [3]int)
- func (s SegmentedLoRASchedule) SharedBytes() int
- func (s SegmentedLoRASchedule) TMEMColumns() uint32
- func (s SegmentedLoRASchedule) TraceEvents(segments int) []layout.TraceEvent
- func (s SegmentedLoRASchedule) Validate() error
- type SharedDesc
- type SpCompressDesc
- type SpCompressOp
- type SpElemType
- type SubspaceKVProjector
- func (p SubspaceKVProjector) AbsorbedLatentAttention(q []float32, numQHeads int, c CompressedKVPage) (scores, out []float32, err error)
- func (p SubspaceKVProjector) CompressKVPage(k, v []float32, tokens, pageID int, use3BitLUT bool) (CompressedKVPage, error)
- func (p SubspaceKVProjector) CompressionRatio(c CompressedKVPage) float64
- func (p SubspaceKVProjector) DecompressKVPage(c CompressedKVPage) (k, v []float32)
- func (p SubspaceKVProjector) Dim() int
- func (p SubspaceKVProjector) Validate() error
- type Swizzle
- type TCGen05BlockScaledGEMM
- type TCGen05Cluster2GEMM
- type TCGen05DynSparseSwiGLU
- func (k TCGen05DynSparseSwiGLU) CUDA() (string, error)
- func (k TCGen05DynSparseSwiGLU) CUDAFile() (string, error)
- func (k TCGen05DynSparseSwiGLU) Grid() (grid, block [3]int)
- func (k TCGen05DynSparseSwiGLU) InstDescriptor() (uint32, error)
- func (k TCGen05DynSparseSwiGLU) Reference(gate, up, wDown []float32) (DynSparseSwiGLUResult, error)
- func (k TCGen05DynSparseSwiGLU) TraceEvents() []layout.TraceEvent
- func (k TCGen05DynSparseSwiGLU) Validate() error
- type TCGen05EarlyReleasePipelineGEMM
- type TCGen05GEMM
- func (g TCGen05GEMM) CUDA() (string, error)
- func (g TCGen05GEMM) Grid(m int) (grid, block [3]int)
- func (g TCGen05GEMM) Launcher() (string, error)
- func (g TCGen05GEMM) Reference(m int, x []uint16, w GEMMWeights) ([]float32, error)
- func (g TCGen05GEMM) ReferenceNVFP4(m int, aFP4, aScale, bFP4, bScale []uint8) ([]float32, error)
- func (g TCGen05GEMM) SharedBytes() int
- func (g TCGen05GEMM) Source() (string, error)
- type TCGen05KVSubspaceProject
- func (k TCGen05KVSubspaceProject) CUDA() (string, error)
- func (k TCGen05KVSubspaceProject) CUDAFile() (string, error)
- func (k TCGen05KVSubspaceProject) Grid() (grid, block [3]int)
- func (k TCGen05KVSubspaceProject) Reference(x, basis []float32) ([]float32, error)
- func (k TCGen05KVSubspaceProject) TraceEvents() []layout.TraceEvent
- func (k TCGen05KVSubspaceProject) Validate() error
- type TCGen05LUTDecompressGEMM
- func (k TCGen05LUTDecompressGEMM) CUDA() (string, error)
- func (k TCGen05LUTDecompressGEMM) CUDAFile() (string, error)
- func (k TCGen05LUTDecompressGEMM) Grid() (grid, block [3]int)
- func (k TCGen05LUTDecompressGEMM) InstDescriptor() (uint32, error)
- func (k TCGen05LUTDecompressGEMM) Reference(aE4M3, aScales, bIndices, bLUTE4M3, bScales []uint8) ([]float32, error)
- type TCGen05LdRed
- type TCGen05LdRedConfig
- func (k TCGen05LdRedConfig) CUDA() (string, error)
- func (k TCGen05LdRedConfig) CUDAFile() (string, error)
- func (k TCGen05LdRedConfig) Grid() (grid, block [3]int)
- func (k TCGen05LdRedConfig) Reference(in []float32) (data []float32, rowRed []float32, err error)
- func (k TCGen05LdRedConfig) Validate() error
- type TCGen05LdSpCompress
- func (k TCGen05LdSpCompress) CUDA() (string, error)
- func (k TCGen05LdSpCompress) CUDAFile() (string, error)
- func (k TCGen05LdSpCompress) DecompressReference(cdata []float32, mdata []uint32, M, N int) ([]float32, error)
- func (k TCGen05LdSpCompress) Grid() (grid, block [3]int)
- func (k TCGen05LdSpCompress) MetadataWordsPerRow() int
- func (k TCGen05LdSpCompress) Reference(in []float32) (cdata []float32, mdata []uint32, rowRed []float32, err error)
- func (k TCGen05LdSpCompress) Validate() error
- type TCGen05MLAPagedAttention
- func (k TCGen05MLAPagedAttention) Block() [3]int
- func (k TCGen05MLAPagedAttention) CUDA() string
- func (k TCGen05MLAPagedAttention) Check() error
- func (k TCGen05MLAPagedAttention) Grid() [3]int
- func (k TCGen05MLAPagedAttention) Launcher() string
- func (k TCGen05MLAPagedAttention) Reference(qAbsorbed, qRope, cKVPages, kRopePages []float32, pageTable []int32, ...) []float32
- func (k TCGen05MLAPagedAttention) SharedBytes() int
- func (k TCGen05MLAPagedAttention) Source() string
- func (k TCGen05MLAPagedAttention) TMEMTrace() []layout.TraceEvent
- func (k TCGen05MLAPagedAttention) TraceEvents() []layout.TraceEvent
- type TCGen05MXFP8GEMM
- func (k TCGen05MXFP8GEMM) CUDA() (string, error)
- func (k TCGen05MXFP8GEMM) CUDAFile() (string, error)
- func (k TCGen05MXFP8GEMM) Grid() (grid, block [3]int)
- func (k TCGen05MXFP8GEMM) InstDescriptor() (uint32, error)
- func (k TCGen05MXFP8GEMM) Reference(aData, aScales, bData, bScales []uint8) ([]float32, error)
- func (k TCGen05MXFP8GEMM) TraceEvents() []layout.TraceEvent
- type TCGen05PagedAttention
- func (k TCGen05PagedAttention) Block() [3]int
- func (k TCGen05PagedAttention) CUDA() string
- func (k TCGen05PagedAttention) Check() error
- func (k TCGen05PagedAttention) Grid() [3]int
- func (k TCGen05PagedAttention) Launcher() string
- func (k TCGen05PagedAttention) Reference(q []float32, kPages, vPages []float32, pageTable []int32, seqLen int) []float32
- func (k TCGen05PagedAttention) SharedBytes() int
- func (k TCGen05PagedAttention) Source() string
- func (k TCGen05PagedAttention) TMEMTrace() []layout.TraceEvent
- func (k TCGen05PagedAttention) TraceEvents() []layout.TraceEvent
- type TCGen05ScaleVec4XGEMM
- type TCGen05SparseGEMM
- func (k TCGen05SparseGEMM) CUDA() (string, error)
- func (k TCGen05SparseGEMM) CUDAFile() (string, error)
- func (k TCGen05SparseGEMM) Grid() (grid, block [3]int)
- func (k TCGen05SparseGEMM) InstDescriptor() (uint32, error)
- func (k TCGen05SparseGEMM) Launcher() (string, error)
- func (k TCGen05SparseGEMM) Reference(aCompressed []float32, aMeta []uint32, b []float32) ([]float32, error)
- func (k TCGen05SparseGEMM) SharedBytes() int
- func (k TCGen05SparseGEMM) TraceEvents() []layout.TraceEvent
- type TCGen05TMAMulticastGatherGEMM
- func (k TCGen05TMAMulticastGatherGEMM) CUDA() (string, error)
- func (k TCGen05TMAMulticastGatherGEMM) CUDAFile() (string, error)
- func (k TCGen05TMAMulticastGatherGEMM) Grid() (grid, block [3]int)
- func (k TCGen05TMAMulticastGatherGEMM) Reference(aGlobal []float32, totalGlobalRows int, gatherRows []int32, b []float32) ([]float32, error)
- func (k TCGen05TMAMulticastGatherGEMM) TraceEvents() []layout.TraceEvent
- type TCGen05TMEMFlashAttention
- func (k TCGen05TMEMFlashAttention) CUDA() (string, error)
- func (k TCGen05TMEMFlashAttention) Grid() (grid, block [3]int)
- func (k TCGen05TMEMFlashAttention) Launcher() (string, error)
- func (k TCGen05TMEMFlashAttention) SharedBytes() int
- func (k TCGen05TMEMFlashAttention) TraceEvents() []layout.TraceEvent
- type TCGen05WeightsStationaryGEMM
- func (k TCGen05WeightsStationaryGEMM) CUDA() (string, error)
- func (k TCGen05WeightsStationaryGEMM) CUDAFile() (string, error)
- func (k TCGen05WeightsStationaryGEMM) Grid() (grid, block [3]int)
- func (k TCGen05WeightsStationaryGEMM) InstDescriptor() (uint32, error)
- func (k TCGen05WeightsStationaryGEMM) Reference(a, b []float32) ([]float32, error)
- func (k TCGen05WeightsStationaryGEMM) Validate() error
- type TMEMAddr
- type TMEMBufferReq
- type TMEMCrossLayerSpec
- type TMEMMegakernelPlan
- type TMEMPlacement
- type TMEMStage
- type TMEMStageOp
- type TTTSchedule
- func (s TTTSchedule) CUDA() (string, error)
- func (s TTTSchedule) CUDAFile() (string, error)
- func (s TTTSchedule) Grid(heads, ctas int) (grid, block [3]int)
- func (s TTTSchedule) Reference(w0, q, k, v [][]float32) (out, w [][]float32, chunkLoss []float64, err error)
- func (s TTTSchedule) SeqLen() int
- func (s TTTSchedule) SharedBytes() int
- func (s TTTSchedule) TMEMColumns() uint32
- func (s TTTSchedule) TraceEvents() []layout.TraceEvent
- func (s TTTSchedule) Validate() error
- type TTTVariant
- type TileEpilogue
- type TubeletPatchSpec
- func (s TubeletPatchSpec) CUDA() (string, error)
- func (s TubeletPatchSpec) Grid() (grid, block [3]int)
- func (s TubeletPatchSpec) GridTHW() (t, h, w int)
- func (s TubeletPatchSpec) PatchLen() int
- func (s TubeletPatchSpec) Patches() int
- func (s TubeletPatchSpec) Reference(video []float32, w [][]float32) ([][]float32, error)
- func (s TubeletPatchSpec) SharedBytes() int
- func (s TubeletPatchSpec) TraceEvents() []layout.TraceEvent
- func (s TubeletPatchSpec) Validate() error
- type WSCollectorAction
- type WSCollectorBuffer
- type WarpRoleKind
- type WeightFormat
- type ZeroColumnMaskDesc
Examples ¶
- BlockFP8GEMM
- BlockNVFP4GEMM
- BuildJaggedBatchSchedule
- DynamicPrune2To4
- FitBlock32LearnedLUT
- FlashLogitsSchedule.ExecuteReference
- KVCompressSchedule.Plan
- RubinSpCompressDecompressKernel
- Synthesize
- TCGen05LUTDecompressGEMM
- TCGen05LdSpCompress
- TCGen05MLAPagedAttention
- TCGen05MXFP8GEMM
- TCGen05PagedAttention
- TCGen05SparseGEMM
- TCGen05TMAMulticastGatherGEMM
- TCGen05WeightsStationaryGEMM
Constants ¶
const ( // MaxTMEMColumnsPerSM is the maximum number of 32-bit TMEM columns per SM // on Blackwell (sm_100a / sm_103a): 512 columns x 128 lanes x 4B = 256 KB. MaxTMEMColumnsPerSM = 512 // TMEMLanesPerSM is the number of vertical lanes (rows) in TMEM per SM. TMEMLanesPerSM = 128 // MaxTMEMBytesPerSM is the 256 KB Tensor Memory capacity per SM. MaxTMEMBytesPerSM = MaxTMEMColumnsPerSM * TMEMLanesPerSM * 4 )
Blackwell Tensor Memory (TMEM) hardware capacity constants per SM.
const ( SpRatio1to2 = "1:2" SpRatio2to4 = "2:4" SpRatio4to8 = "4:8" SpRatio1to4 = "1:4" SpRatio2to8 = "2:8" SpRatio4to16 = "4:16" )
Structured sparsity ratio qualifiers (.sp::<ratio>) for PTX ISA 9.4 §9.7.10.30 spcompress and §9.7.10.31 spdecompress.
const BlackwellFP4Helpers = `` /* 2767-byte string literal not displayed */
const CUDALowerMMACfg6HandPrefix = `` /* 24979-byte string literal not displayed */
mmaCfg6HandPrefix is the hand-written G1 helpers and template, with no Torch binding or G2 launcher. It compiles for sm_90a; its numerics are unmeasured on device.
const CUDALowerNVFP4TMADevice = `` /* 33113-byte string literal not displayed */
nvfp4TMADevice is a direct port of the retained v27 device implementation. Origin SHA256: 570ec10423625b76fa891b2ef02a7cc9b56a3b8e529b125c98ae3d4989883989 Device-prefix SHA256 before comment backticks become apostrophes: fc7b155374f29c9d6271a5e08f3c6ec4f5343ef3dc2c1c47d4cf5998b70352ef Only the namespace is substituted when emitted. No CUDA compiler or GPU qualification is implied by the host tests of this port.
const CUDALowerWarpSpecHelpers = warpSpecHelpers
CUDALowerWarpSpecHelpers exposes the warp-specialized mbarrier, bulk-copy, and register-budget device C++ helpers.
const HostEmuElems = 32
HostEmuElems is the number of floats per tile in Schedule.EmitHostEmuCUDA.
const MXBlock = 32
MXBlock is the standard 32-element block size for OCP microscaling formats (MXFP8, MXFP6, and MXFP4) scaled by a shared UE8M0 exponent.
const NVFP4Block = 16
NVFP4Block is the number of values sharing one E4M3 block scale.
const Prelude = `` /* 11516-byte string literal not displayed */
Prelude is the self-contained device prelude every emitted tcgen05 or CLC kernel begins with.
const SM120Prelude = `#ifndef EG_SM120_PRELUDE
#define EG_SM120_PRELUDE
// EG_SM120_FAMILY is true when compiling device code for the sm_120 family
// (sm_120a, sm_120f, sm_121a, sm_121f), where the PTX ISA provides
// mma.sync .block_scale and cvt.rn.f16x2.e2m1x2.
#if (defined(__CUDA_ARCH_FEAT_SM120_ALL) || defined(__CUDA_ARCH_FEAT_SM121_ALL) || \
(defined(__CUDA_ARCH_FAMILY_SPECIFIC__) && __CUDA_ARCH__ >= 1200 && __CUDA_ARCH__ < 1300)) && \
!defined(EG_HOST_EMU) && !defined(EG_EMU)
#define EG_SM120_FAMILY 1
#else
#define EG_SM120_FAMILY 0
#endif
EG_DEV float eg_sm120_decode_e2m1(uint32_t code) {
uint32_t h[2];
eg_e2m1x4_to_bf16x4(code & 0xfu, h);
return eg_bf16_to_f32(h[0]);
}
// eg_sm120_dequant_nvfp4_pair widens the two E2M1 nibbles in packed_byte and
// scales them by the UE4M3 block scale byte scale_e4m3.
EG_DEV void eg_sm120_dequant_nvfp4_pair(uint32_t packed_byte, uint32_t scale_e4m3, float out[2]) {
const float sf = eg_e4m3_to_f32(scale_e4m3 & 0xffu);
#if EG_SM120_FAMILY
uint32_t f16x2;
asm("{\n\t"
".reg .b8 q;\n\t"
"cvt.u8.u32 q, %1;\n\t"
"cvt.rn.f16x2.e2m1x2 %0, q;\n\t"
"}" : "=r"(f16x2) : "r"(packed_byte));
const uint32_t lo = f16x2 & 0xffffu;
const uint32_t hi = f16x2 >> 16;
const uint32_t blo = (lo & 0x7fffu) ? (((lo & 0x7fffu) >> 3) + 0x3800u) | (lo & 0x8000u) : (lo & 0x8000u);
const uint32_t bhi = (hi & 0x7fffu) ? (((hi & 0x7fffu) >> 3) + 0x3800u) | (hi & 0x8000u) : (hi & 0x8000u);
out[0] = eg_bf16_to_f32(blo) * sf;
out[1] = eg_bf16_to_f32(bhi) * sf;
#else
uint32_t h[2];
eg_e2m1x4_to_bf16x4(packed_byte & 0xffu, h);
out[0] = eg_bf16_to_f32(h[0]) * sf;
out[1] = eg_bf16_hi_to_f32(h[0]) * sf;
#endif
}
// eg_sm120_mma_nvfp4_16864 executes workstation/edge Blackwell (sm_120a / sm_121a)
// warp-synchronous m16n8k64 NVFP4 block-scaled tensor-core accumulation into
// warp registers d[0..3]. sfa and sfb each carry four UE4M3 scales, one per
// 16 elements of K (scale_vec::4X, the only vector size .ue4m3 allows).
EG_DEV void eg_sm120_mma_nvfp4_16864(
float d[4], const uint32_t a[4], const uint32_t b[2], uint32_t sfa, uint32_t sfb) {
#if EG_SM120_FAMILY
asm volatile("` + sm120NVFP4MMAAsm + `"
: "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3])
: "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]),
"r"(b[0]), "r"(b[1]), "r"(sfa), "r"(sfb));
#elif defined(EG_HOST_EMU)
eg_emu_mma_nvfp4_16864(d, a, b, sfa, sfb);
#else
const int lane = (int)(threadIdx.x & 31u);
const int g = lane / 4, t = lane % 4;
float out[4] = {d[0], d[1], d[2], d[3]};
for (int i = 0; i < 4; ++i) {
const int row = g + 8 * (i / 2);
const int col = 2 * t + (i & 1);
const int a_slane = (row % 8) * 4 + (row / 8);
const int b_slane = col * 4;
const uint32_t row_sfa = __shfl_sync(0xffffffffu, sfa, a_slane);
const uint32_t col_sfb = __shfl_sync(0xffffffffu, sfb, b_slane);
float acc = out[i];
for (int k = 0; k < 64; ++k) {
const int alane = (row % 8) * 4 + (k % 32) / 8;
const int areg = (row / 8) + 2 * (k / 32);
const uint32_t aword = (areg == 0) ? a[0] : (areg == 1) ? a[1] : (areg == 2) ? a[2] : a[3];
const uint32_t got_a = __shfl_sync(0xffffffffu, aword, alane);
const float av = eg_sm120_decode_e2m1((got_a >> (4 * (k % 8))) & 0xfu) *
eg_e4m3_to_f32((row_sfa >> (8 * (k / 16))) & 0xffu);
const int blane = col * 4 + (k % 32) / 8;
const uint32_t bword = (k < 32) ? b[0] : b[1];
const uint32_t got_b = __shfl_sync(0xffffffffu, bword, blane);
const float bv = eg_sm120_decode_e2m1((got_b >> (4 * (k % 8))) & 0xfu) *
eg_e4m3_to_f32((col_sfb >> (8 * (k / 16))) & 0xffu);
acc += av * bv;
}
out[i] = acc;
}
for (int i = 0; i < 4; ++i) d[i] = out[i];
#endif
}
EG_DEV void eg_sm120_clc_mbar_init(uint64_t* mbar, uint32_t count) {
#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 1200) && !defined(EG_HOST_EMU) && !defined(EG_EMU)
const uint32_t addr = (uint32_t)__cvta_generic_to_shared(mbar);
asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" :: "r"(addr), "r"(count) : "memory");
#elif defined(EG_HOST_EMU) || defined(EG_EMU)
eg_emu_mbar_init(mbar, (int)count);
#else
(void)mbar;
(void)count;
#endif
}
// eg_clc_try_cancel issues a Blackwell clusterlaunchcontrol.try_cancel request
// to steal an unlaunched CTA tile into 16-byte shared-memory response_smem.
EG_DEV void eg_clc_try_cancel(uint4* response_smem, uint64_t* mbar) {
#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 1200) && !defined(EG_HOST_EMU) && !defined(EG_EMU)
const uint32_t resp_addr = (uint32_t)__cvta_generic_to_shared(response_smem);
const uint32_t mbar_addr = (uint32_t)__cvta_generic_to_shared(mbar);
asm volatile(
"mbarrier.arrive.expect_tx.shared::cta.b64 _, [%1], 16;\n\t"
"clusterlaunchcontrol.try_cancel.async.shared::cta.mbarrier::complete_tx::bytes.b128 [%0], [%1];"
:: "r"(resp_addr), "r"(mbar_addr) : "memory");
#elif defined(EG_EMU)
eg_emu_clc_try_cancel_async(response_smem, mbar);
#else
if (response_smem) *response_smem = {0u, 0u, 0u, 0u};
(void)mbar;
#endif
}
EG_DEV void eg_sm120_clc_wait(uint64_t* mbar, uint32_t phase) {
#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 1200) && !defined(EG_HOST_EMU) && !defined(EG_EMU)
const uint32_t mbar_addr = (uint32_t)__cvta_generic_to_shared(mbar);
asm volatile(
"{\n\t"
".reg .pred p;\n\t"
"EG_SM120_CLC_WAIT_%=:\n\t"
"mbarrier.try_wait.parity.shared::cta.b64 p, [%0], %1;\n\t"
"@!p bra EG_SM120_CLC_WAIT_%=;\n\t"
"}"
:: "r"(mbar_addr), "r"(phase) : "memory");
#elif defined(EG_EMU)
eg_emu_clc_wait(mbar, (int)phase);
#else
(void)mbar;
(void)phase;
#endif
}
EG_DEV bool eg_sm120_clc_query_is_canceled(uint4 resp) {
#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 1200) && !defined(EG_HOST_EMU) && !defined(EG_EMU)
uint32_t pred;
asm volatile(
"{\n\t"
".reg .pred p;\n\t"
".reg .b128 r128;\n\t"
"mov.b128 r128, {%1, %2, %3, %4};\n\t"
"clusterlaunchcontrol.query_cancel.is_canceled.pred.b128 p, r128;\n\t"
"selp.u32 %0, 1, 0, p;\n\t"
"}"
: "=r"(pred)
: "r"(resp.x), "r"(resp.y), "r"(resp.z), "r"(resp.w));
return pred != 0;
#elif defined(EG_EMU)
return eg_emu_clc_query_is_canceled(resp);
#else
return resp.w != 0u;
#endif
}
EG_DEV uint32_t eg_sm120_clc_query_first_ctaid_x(uint4 resp) {
#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 1200) && !defined(EG_HOST_EMU) && !defined(EG_EMU)
uint32_t ctaid_x;
asm volatile(
"{\n\t"
".reg .b128 r128;\n\t"
"mov.b128 r128, {%1, %2, %3, %4};\n\t"
"clusterlaunchcontrol.query_cancel.get_first_ctaid::x.b32.b128 %0, r128;\n\t"
"}"
: "=r"(ctaid_x)
: "r"(resp.x), "r"(resp.y), "r"(resp.z), "r"(resp.w));
return ctaid_x;
#elif defined(EG_EMU)
return eg_emu_clc_query_first_ctaid_x(resp);
#else
return resp.x;
#endif
}
#endif // EG_SM120_PRELUDE
`
const TCGen05AdvancedPrelude = `` /* 23243-byte string literal not displayed */
TCGen05AdvancedPrelude is the self-contained device preamble emitted for advanced sm_100a/sm_103a tcgen05 kernels (2-CTA cta_group::2 cooperative MMA, tcgen05.cp scale staging, TMEM-sourced operand A FlashAttention, and 4-warp 32-row epilogue datapath access).
In eg_tcgen05_commit_cta2, the .multicast::cluster CTA mask is hard-coded to 0x3, which assumes a 2-CTA cluster (__cluster_dims__(2, 1, 1)). Kernels launched with larger clusters must derive the pair mask from %cluster_ctarank (0x3u << (rank & ~1u)).
const TCGen05BlackwellTMAPrelude = `` /* 7014-byte string literal not displayed */
TCGen05BlackwellTMAPrelude provides device helpers for Blackwell sm_100a/sm_103a L2 cache eviction policy descriptors (createpolicy.fractional.L2::evict_last / L2::evict_first), 2D TMA 4-row non-contiguous gather/scatter (.gather4 / .scatter4), and 2D TMA cluster multicast (.multicast::cluster).
const TensorMapEncode = `` /* 2235-byte string literal not displayed */
TensorMapEncode is the host function with which a launcher encodes a tensor map on a device. It needs cuda.h and the CUDA runtime, so NVRTC and the host emulation do not take it.
The driver's encoder comes from the runtime's driver entry point, which an older driver does not have, and it refuses a map it cannot encode. eg_tmap_encode_2d reports both: a launcher that went on would call a null function or launch a kernel on a map that is not one.
const UE8M0Bias = 127
UE8M0Bias is the unsigned exponent bias (127) for 8-bit OCP UE8M0 scales.
const UE8M0NaN uint8 = 0xFF
UE8M0NaN is the reserved NaN code (0xFF) in the OCP UE8M0 scale encoding.
const WGMMASwizzleHelpers = `` /* 723-byte string literal not displayed */
const WeightFP8E4M3 = WeightE4M3
WeightFP8E4M3 aliases WeightE4M3 for FP8 E4M3 paged KV caches.
Variables ¶
var ErrInfeasible = errors.New("no feasible warp-specialization schedule")
ErrInfeasible is returned when no configuration satisfies the constraints.
var Identity = MustLambda("$0")
Identity is the lambda $0.
Functions ¶
func ApplyMRoPEReference ¶
ApplyMRoPEReference rotates each row x[t] [HeadDim] by its (temporal, height, width) position posTHW[t] in FP32, as the emitted kernels do.
func ApplyRoPEReference ¶
ApplyRoPEReference is 1D rotary embedding over the same rotary pairs as spec: every pair turns by pos[t]. With equal (t, h, w) positions ApplyMRoPEReference gives the same bits.
func BuildTubeletTMADescriptor ¶
func BuildTubeletTMADescriptor(spec TubeletPatchSpec, baseAddr uint64) (layout.Descriptor, error)
BuildTubeletTMADescriptor returns the rank-4 tensor map that loads one (PatchT, PatchH, PatchW, Channels) tubelet of the FP32 video at baseAddr per TMA box. Dimensions are listed innermost first: channels, width, height, frames. Out-of-bounds boxes at the far edges are zero filled.
func CLCHelpers ¶
func CLCHelpers() string
CLCHelpers returns the device C++ wrappers for Blackwell sm_100a/sm_103a clusterlaunchcontrol.try_cancel and clusterlaunchcontrol.query_cancel.
func CUDALowerNVFP4WGMMAHelpers ¶
CUDALowerNVFP4WGMMAHelpers returns the header-free NVFP4 WGMMA device helper block.
func CUDALowerWGMMARSFunc ¶
CUDALowerWGMMARSFunc emits a register-shared WGMMA device function.
func DecodeFP6E2M3 ¶
DecodeFP6E2M3 decodes a 6-bit OCP FP6 E2M3 code in [0..63] (1 sign bit, 2 exponent bits with bias 1, 3 mantissa bits, max magnitude 7.5) to float32.
func DecodeFP6E3M2 ¶
DecodeFP6E3M2 decodes a 6-bit OCP FP6 E3M2 code in [0..63] (1 sign bit, 3 exponent bits with bias 3, 2 mantissa bits, max magnitude 28.0) to float32.
func DecodeUE8M0 ¶
DecodeUE8M0 decodes an 8-bit OCP UE8M0 scale code to float32 (2^(code-127) for code in [0..254], or NaN for 0xFF) via cuda.E8M0frombits.
func DecompressReference ¶
DecompressReference reconstructs the dense [M, N] float32 tensor (with unselected positions zeroed) from compressed values cdata [M * (N/2)] and packed 2-bit-per-selected-element metadata mdata [M * ceil(N/32)].
func DequantNVFP4 ¶
DequantNVFP4 decodes one NVFP4 row of k values.
func DequantizeMXFP4E2M1 ¶
DequantizeMXFP4E2M1 reconstructs float32 values from packed E2M1 bytes and 32-element UE8M0 block scales.
func DequantizeMXFP8E4M3 ¶
DequantizeMXFP8E4M3 reconstructs float32 values from E4M3 codes and 32-element UE8M0 block scales.
func EncodeE2M1 ¶
EncodeE2M1 encodes v into a 4-bit OCP E2M1 code in [0..15] (bit 3 is sign, bits 2..0 select from {0, 0.5, 1, 1.5, 2, 3, 4, 6} by round-to-nearest-even). Like cvt.rn.satfinite.e2m1x2.f32, it saturates magnitudes above 6, infinities included, to ±6 and encodes NaN as +6. See cuda.E2M1bits.
func EncodeFP6E2M3 ¶
EncodeFP6E2M3 encodes v into a 6-bit OCP FP6 E2M3 code in [0..63] using round-to-nearest-even and saturating outside [-7.5, 7.5].
func EncodeFP6E3M2 ¶
EncodeFP6E3M2 encodes v into a 6-bit OCP FP6 E3M2 code in [0..63] using round-to-nearest-even and saturating outside [-28.0, 28.0].
func EncodeUE8M0 ¶
EncodeUE8M0 encodes a positive scale factor into an 8-bit OCP UE8M0 biased exponent (bias = 127), returning the smallest power-of-two 2^(code-127) >= scale (or 127 for 1.0, 0 for scale <= 2^-127, 254 for overflow, and 0xFF for NaN).
func FlashLogitsGumbel ¶
FlashLogitsGumbel returns the Gumbel(0, 1) variate that the flash-logits kernel adds to the scaled logit of (row, token): -log(-log(u)) with u = (x + 0.5) / 2^32 and x the first word of Philox4x32_10({token, row, 0, 0}, {seed, seed >> 32}).
func FromUE8M0Bits ¶
FromUE8M0Bits decodes an 8-bit OCP UE8M0 biased exponent scale code to float32.
func GQAAttention ¶
func GQAAttention(q, k, v []float32, tokens, numQHeads, numKVHeads, headDim int) (scores, out []float32, err error)
GQAAttention is the uncompressed reference for SubspaceKVProjector.AbsorbedLatentAttention: single-position grouped-query attention of q [numQHeads, headDim] over k, v [tokens, numKVHeads*headDim], accumulated in float64.
func LayerNormL2VJP ¶
LayerNormL2VJP returns ℓ = ½‖LN(z) - v‖² and g = ∂ℓ/∂z for LN without affine parameters: with ẑ = (z - μ)/σ, σ = √(var(z) + eps) and r = ẑ - v,
g = (r - mean(r) - ẑ mean(r ⊙ ẑ)) / σ.
func LoRAKernelArgs ¶
func LoRAKernelArgs(plan LoRAGatherPlan) (order, start, end, rank, aoff, boff []int32, scale []float32)
LoRAKernelArgs returns the order and seg_ arrays of the kernel signature for plan.
func OrthonormalityError ¶
OrthonormalityError returns ||U^T U - I||_F for the row-major [dim, rank] matrix u.
func PackFP6x4 ¶
PackFP6x4 packs four 6-bit FP6 codes (c0, c1, c2, c3 in [0..63]) into 3 contiguous bytes (24 bits):
b[0] = c0 | (c1 << 6) b[1] = (c1 >> 2) | (c2 << 4) b[2] = (c2 >> 4) | (c3 << 2)
func Philox4x32_10 ¶
Philox4x32_10 returns the Philox4x32 counter-based random block for counter ctr and key key after 10 rounds (Salmon et al., SC 2011; the Random123 philox4x32_10 function).
func Prune2To4F32 ¶
func Prune2To4F32(a []float32, M, K int) (compressed []float32, meta []uint32, prunedDense []float32, err error)
Prune2To4F32 prunes a dense [M, K] float32 matrix along the reduction dimension K to NVIDIA 2:4 structured sparsity. In each contiguous 4-element group a[r, 4g..4g+3], it selects the 2 elements with largest |v| (breaking ties deterministically by lower index 0 < 1 < 2 < 3) and orders the kept indices as 0 <= idx0 < idx1 <= 3.
It returns:
- compressed: [M, K/2] non-zero values (2 per 4-element group),
- meta: [M, K/32] uint32 metadata words (8 groups x 4-bit nibble per word),
- prunedDense:[M, K] dense matrix with the pruned elements zeroed.
func Prune2To4NVFP4 ¶
func Prune2To4NVFP4(aPacked []uint8, aScales []uint8, M, K int) (compPacked []uint8, compScales []uint8, meta []uint32, err error)
Prune2To4NVFP4 prunes a packed NVFP4 tensor aPacked [M, K/2] with E4M3 block scales aScales [M, K/16] along K to 2:4 structured sparsity:
- compPacked: [M, K/4] bytes (one byte holding the 2 kept 4-bit E2M1 nibbles per 4-element group),
- compScales: [M, K/16] E4M3 block scales,
- meta: [M, K/32] uint32 metadata words (8 groups x 4-bit nibble per word).
func Quantize3BitLUTB ¶
func Quantize3BitLUTB(b []float32, K, N int) (indices []uint8, lutE4M3 []uint8, bScales []uint8, dequantized []float32, err error)
Quantize3BitLUTB compresses a weight matrix B [K, N] (where K is a positive multiple of 32 and N is a positive multiple of 8) for PTX ISA 9.4 (§9.7.18.10.10.1 decompress::lut::b) 3-bit look-up-table weight decompression:
- bScales [N * (K/32)] holds one UE8M0 per-32-element block scale for each column n and 32-row block kb (indexed at n*(K/32) + kb),
- lutE4M3 [(N/8) * 8] holds an 8-entry E4M3 lookup table of centroids for each 8-column slice n0..n0+7 (indexed at (n/8)*8 + idx),
- indices [K * N] holds the 3-bit centroid index in [0..7] for each B[k, n], and
- dequantized [K * N] holds the reconstructed float32 weights cuda.E4M3frombits(lut[idx]) * FromUE8M0Bits(scale).
func QuantizeLearnedLUTB ¶
func QuantizeLearnedLUTB(b, hessianDiag []float32, K, N, maxIters int) (indices, lutE4M3, bScales []uint8, dequantized []float32, err error)
QuantizeLearnedLUTB quantizes B [K, N] into the operand layout that Quantize3BitLUTB produces and TCGen05LUTDecompressGEMM consumes (one UE8M0 scale per column and 32-row block, one 8-entry E4M3 LUT per 8-column slice, a 3-bit index per element), but fits each slice's LUT by Hessian-weighted Lloyd-Max (FitBlock32LearnedLUT's algorithm) instead of four unweighted refinement steps. hessianDiag [K] weights input channel k; nil means all ones.
func QuantizeMXFP4E2M1 ¶
QuantizeMXFP4E2M1 quantizes a slice of float32 values (length a multiple of 32) into 32-element OCP MXFP4 blocks (2 E2M1 nibbles per byte, 1 UE8M0 scale per 32 elements).
func QuantizeMXFP8E4M3 ¶
QuantizeMXFP8E4M3 quantizes a slice of float32 values (length a multiple of 32) into 32-element OCP MXFP8 blocks using E4M3 elements and UE8M0 block scales.
func ReferenceFusedLoRA ¶
func ReferenceFusedLoRA(x, w [][]float32, tokenAdapterIDs []int, aPool, bPool [][]float32, adapters map[int]LoRAAdapterSlot) ([][]float32, error)
ReferenceFusedLoRA computes in float64, for each token i,
y_i = W x_i + scale_a (B_a (A_a x_i)) with a = tokenAdapterIDs[i]
and y_i = W x_i when a is -1. x is [tokens][DimIn], w [DimOut][DimIn], and the pools are laid out as LoRAAdapterSlot describes.
func SpCompress2to4F32 ¶
func SpCompress2to4F32(in []float32, op SpCompressOp) (cdata []float32, mdata []uint32, err error)
SpCompress2to4F32 compresses a dense slice in (whose length must be a positive multiple of 32) using 2:4 structured sparsity according to op (MAX, MAXABS, MIN, or MINABS).
For each contiguous 4-element group in[4*g .. 4*g+3], it selects the 2 elements ordered by op (breaking ties deterministically by lower index 0 < 1 < 2 < 3), places their values into cdata[2*g .. 2*g+1] in ascending index order (idx0 < idx1), and packs the 4-bit metadata nibble (idx0 | (idx1 << 2)) into bits 4*(g%8)..4*(g%8)+3 of mdata[g/8].
func SpDecompress2to4F32 ¶
SpDecompress2to4F32 reconstructs a dense slice of totalElems float32 values from 2:4 compressed data cdata (length totalElems/2) and packed 2-bit index metadata mdata (length totalElems/32), scattering each compressed pair back to (idx0, idx1) and zero-filling the remaining 2 slots per 4-element group.
func SparseMMAActivationDenseWeight ¶
func SparseMMAActivationDenseWeight(act DynSparseTile, w []float32, n int) ([]float32, error)
SparseMMAActivationDenseWeight returns D = A * W^T for the 2:4 sparse activation A = act [Rows, DenseCols] and the dense weight w [n, DenseCols] (row-major, one output feature per row, the layout of a down_proj weight). It is the host reference of tcgen05.mma.sp with a runtime-pruned operand A and an unmodified dense operand B. Accumulation is float32 in group order.
func SplitBF16 ¶
SplitBF16 splits f into hi + lo, both bfloat16, with hi = bf16(f) and lo = bf16(f - hi).
func SwiGLU ¶
SwiGLU returns SiLU(gate) * up elementwise in float32, the activation pruned by TCGen05DynSparseSwiGLU.
func TMEMColumns ¶
TMEMColumns returns the TMEM column limit the package assumes for arch: 512 on sm_100 and sm_103, 576 on sm_107 (exclusive allocation, PTX ISA 9.4 Table 58, as [cudatmem.MaxColumnsExclusive] records), and 0 on targets without tcgen05 TMEM, including sm_90a and sm_121a.
func Unpack2To4F32 ¶
Unpack2To4F32 reconstructs the dense [M, K] float32 matrix from a 2:4 compressed value matrix compressed [M, K/2] and packed metadata meta [M, K/32].
func UnpackFP6x4 ¶
UnpackFP6x4 unpacks 3 contiguous bytes (24 bits) into four 6-bit FP6 codes in [0..63].
func UnpackIndices3Bit ¶
UnpackIndices3Bit is the inverse of LearnedLUTBlock.PackIndices.
func ValidateLUTColumn ¶
ValidateLUTColumn reports whether col can hold a 2-column TMEM LUT for .decompress::lut::b: it must be even and leave room for both columns.
func VerifyDeadlockFreedom ¶
VerifyDeadlockFreedom checks the ring protocol s implies over numTiles tiles, as the package documentation describes, and returns a *ProtocolError for the first failure.
func WGMMAE4M3Func ¶
wgmmaE4M3Func returns a device function name(float* d, uint64_t da, uint64_t db) issuing wgmma.mma_async m64n<n>k32 E4M3 → FP32 with D += A·B, both operands K-major in shared memory.
Types ¶
type BlockFP8GEMM ¶
type BlockFP8GEMM struct {
Name string
N, K int
// Multimem reduces each partial output element atomically into a
// multicast address with multimem.red.relaxed.sys.global.add.f32
// instead of writing a unicast store. Under host emulation it
// accumulates into out for multi-rank TP/EP equivalence checks.
Multimem bool
}
BlockFP8GEMM emits an SM100a GEMM for E4M3 operands and FP32 block scales. A uses one scale per row and 128 K values. B shares a scale across 128 output columns and 128 K values. Both operands are row-major, with K contiguous. The result is row-major FP32.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/tcgen05"
)
func main() {
g := tcgen05.BlockFP8GEMM{Name: "project_fp8", N: 128, K: 256}
src, err := g.CUDA()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(strings.Contains(src, "kind::mxf8f6f4.block_scale"), g.SharedBytes())
}
Output: true 26624
func (BlockFP8GEMM) CUDA ¶
func (g BlockFP8GEMM) CUDA() (string, error)
CUDA returns CUDA source without Prelude. Launch with 128 threads per block and grid dimensions (N/64, ceil(M/128), 1). Each block computes a 128-by-64 output tile. Its m argument gives the number of A rows.
func (BlockFP8GEMM) SharedBytes ¶
func (g BlockFP8GEMM) SharedBytes() int
SharedBytes returns the dynamic shared memory required by CUDA.
type BlockNVFP4GEMM ¶
type BlockNVFP4GEMM struct {
Name string
N, K int
// UE8M0 selects unsigned exponent-only scales. The default is UE4M3.
UE8M0 bool
// Multimem reduces each partial output element atomically into a
// multicast address with multimem.red.relaxed.sys.global.add.f32
// instead of writing a unicast store. Under host emulation it
// accumulates into out for multi-rank TP/EP equivalence checks.
Multimem bool
}
BlockNVFP4GEMM emits an SM100a GEMM for row-major packed E2M1 operands, unsigned E4M3 or E8M0 scales per 16 K elements, and row-major FP32 output. The E2M1 low nibble is the even K element.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/tcgen05"
)
func main() {
g := tcgen05.BlockNVFP4GEMM{Name: "project_nvfp4", N: 128, K: 256}
src, err := g.CUDA()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(strings.Contains(src, "kind::mxf4nvf4.block_scale"), g.SharedBytes())
}
Output: true 83968
func (BlockNVFP4GEMM) CUDA ¶
func (g BlockNVFP4GEMM) CUDA() (string, error)
CUDA returns CUDA source without Prelude. Launch with 128 threads per block and grid dimensions (N/128, ceil(M/128), 1). Use 128-row TMA boxes of 128 bytes for the swizzled operands and 16 bytes for the unswizzled scales. The first float at w_gs multiplies each output.
func (BlockNVFP4GEMM) SharedBytes ¶
func (g BlockNVFP4GEMM) SharedBytes() int
SharedBytes returns the dynamic shared memory required by CUDA.
type CLCPersistentTileGEMM ¶
type CLCPersistentTileGEMM struct {
Name string
Target string
N, K int
BM, BN, BK int
ActiveCTAs int // host-emulation residency hint
Weight WeightFormat // WeightBF16, WeightE4M3, WeightNVFP4
Out cuda.DType
Epilogue Lambda
}
CLCPersistentTileGEMM configures a Blackwell sm_100a/sm_103a persistent GEMM kernel that steals output tiles dynamically using clusterlaunchcontrol.try_cancel instead of global atomicAdd counters.
func (CLCPersistentTileGEMM) CUDA ¶
func (g CLCPersistentTileGEMM) CUDA() (string, error)
CUDA returns the device kernel source (without Prelude or CLCHelpers).
func (CLCPersistentTileGEMM) Launcher ¶
func (g CLCPersistentTileGEMM) Launcher() (string, error)
Launcher returns a host launcher function for g.
func (CLCPersistentTileGEMM) Reference ¶
func (g CLCPersistentTileGEMM) Reference(m int, x []uint16, w GEMMWeights) ([]float32, error)
Reference computes the [m, N] output in float64 with the epilogue evaluated in FP32 and rounded to g.Out.
func (CLCPersistentTileGEMM) SharedBytes ¶
func (g CLCPersistentTileGEMM) SharedBytes() int
SharedBytes returns the shared memory bytes used by one CTA.
func (CLCPersistentTileGEMM) Source ¶
func (g CLCPersistentTileGEMM) Source() (string, error)
Source returns the complete CUDA translation unit for g, including Prelude, CLCHelpers, the persistent kernel, and its host launcher.
func (CLCPersistentTileGEMM) TotalTiles ¶
func (g CLCPersistentTileGEMM) TotalTiles(m int) int
TotalTiles returns the total number of BM x BN output tiles for m rows.
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 CUDALowerNVFP4QuantOpts ¶
CUDALowerNVFP4QuantOpts configures CUDALowerNVFP4QuantOpts.CUDA.
type CUDALowerOperand ¶
type CUDALowerOperand struct {
Name string
DType CUDALowerDType
Broadcast CUDALowerBroadcast
}
CUDALowerOperand mirrors the cudalower epilogue extra Operand.
type CUDALowerRubinF32x2NormOpts ¶
type CUDALowerRubinF32x2NormOpts struct {
Name string
Rows, Cols int
Eps float32
Target string
Params []string
}
CUDALowerRubinF32x2NormOpts configures CUDALowerRubinF32x2NormOpts.CUDA.
type CUDALowerRubinUE5M3Opts ¶
type CUDALowerRubinUE5M3Opts struct {
Name string
Rows, Cols int
Eps float32
UsePZO bool
Target string
Params []string
}
CUDALowerRubinUE5M3Opts configures CUDALowerRubinUE5M3Opts.CUDA.
type CUDALowerSM120AttnOpts ¶
type CUDALowerSM120AttnOpts struct {
Name string
NumQHeads, NumKVHeads int
HeadDim int
PageSize, MaxPages int
SeqLen int
Scale float32
Target string
KVFormat CUDALowerWeight
Splits int
MinSplitKeys int
Q CUDALowerDType
Params []string
}
CUDALowerSM120AttnOpts configures CUDALowerSM120AttnOpts.CUDA.
func (CUDALowerSM120AttnOpts) CUDA ¶
func (a CUDALowerSM120AttnOpts) CUDA() (string, error)
CUDA returns the self-contained CUDA C++ kernel source for a.
type CUDALowerSM120GEMMOpts ¶
type CUDALowerSM120GEMMOpts struct {
Name string
M, N, K int
BM, BN, BK int
Target string
UseCLC bool
Epilogue CUDALowerTileEpilogue
Out CUDALowerDType
Params []string
}
CUDALowerSM120GEMMOpts configures CUDALowerSM120GEMMOpts.CUDA.
func (CUDALowerSM120GEMMOpts) CUDA ¶
func (g CUDALowerSM120GEMMOpts) CUDA() (string, error)
CUDA returns the self-contained CUDA C++ kernel source for g.
type CUDALowerScaleLayout ¶
type CUDALowerScaleLayout uint8
CUDALowerScaleLayout mirrors the cudalower ScaleLayout enum.
func (CUDALowerScaleLayout) String ¶
func (l CUDALowerScaleLayout) String() string
type CUDALowerSkinnyGEMMOpts ¶
type CUDALowerSkinnyGEMMOpts struct {
Name string
N, K, MaxM int
Weight CUDALowerWeight
Out, X CUDALowerDType
Epilogue string
EpilogueCUDA func(...string) (string, error)
Extras []CUDALowerOperand
GLU bool
HasTail bool
TailName, TailIn, TailCUDA string
TailParams []string
TailThreads int
RowsPerBlock, SMs, Warps, SplitK int
Unroll, Prefetch int
BlackwellFP4 bool
Store CUDALowerStore
FaultSkip bool
Params []string
}
CUDALowerSkinnyGEMMOpts configures CUDALowerSkinnyGEMMOpts.CUDA.
type CUDALowerSkinnyMMAOpts ¶
type CUDALowerSkinnyMMAOpts struct {
Name string
N, K, MaxM int
Out CUDALowerDType
Epilogue string
EpilogueCUDA func(...string) (string, error)
Extras []CUDALowerOperand
GLU bool
Warps, Tiles, Chunks, Steps int
KChunk int
StageWeights bool
SplitK, SMs int
Params []string
}
CUDALowerSkinnyMMAOpts configures CUDALowerSkinnyMMAOpts.CUDA.
type CUDALowerStore ¶
type CUDALowerStore uint8
CUDALowerStore mirrors the cudalower GEMMStore enum.
type CUDALowerTileEpilogue ¶
type CUDALowerTileEpilogue uint8
CUDALowerTileEpilogue mirrors the cudalower TileEpilogue enum.
func (CUDALowerTileEpilogue) String ¶
func (e CUDALowerTileEpilogue) String() string
type CUDALowerTileGEMMOpts ¶
type CUDALowerTileGEMMOpts struct {
Name string
N, K int
Weight CUDALowerWeight
Out CUDALowerDType
Epilogue string
EpilogueCUDA func(...string) (string, error)
Extras []CUDALowerOperand
Grouped bool
GLU bool
WGMMA bool
Gather bool
SumSq bool
Repacked bool
CompactScales bool
DequantWords int
Swizzle128B bool
GroupM int
StreamK int
WarpSpecialized bool
VectorActivationLoads bool
BlackwellFP4 bool
BM, BN int
Stages int
Params []string
Dequant1W, Dequant2W string
}
CUDALowerTileGEMMOpts configures CUDALowerTileGEMMOpts.CUDA.
type CUDALowerUMMAGEMMOpts ¶
type CUDALowerUMMAGEMMOpts struct {
Name string
N, K int
Weight CUDALowerWeight
Out CUDALowerDType
EpilogueCUDA func(...string) (string, error)
Extras []CUDALowerOperand
MaxM, BN, Stages int
Params []string
}
CUDALowerUMMAGEMMOpts configures CUDALowerUMMAGEMMOpts.CUDA.
type CUDALowerWeight ¶
type CUDALowerWeight uint8
CUDALowerWeight mirrors the cudalower WeightFormat enum.
func (CUDALowerWeight) String ¶
func (f CUDALowerWeight) String() string
type CollectorOp ¶
type CollectorOp string
CollectorOp specifies the operand collector reuse-buffer operation for .collector::a::<op> and .collector::b::<op> on Rubin sm_107a/sm_107f tcgen05.mma instructions (PTX ISA 9.4 section 9.7.18.10.10.1).
const ( CollectorNone CollectorOp = "" CollectorFill CollectorOp = "fill" CollectorUse CollectorOp = "use" CollectorLastUse CollectorOp = "lastuse" CollectorDiscard CollectorOp = "discard" )
type CompressedKVPage ¶
type CompressedKVPage struct {
PageID int
Tokens int
Rank int
LatentK []float32 // [Tokens, Rank]; dequantized values when Use3BitLUT
LatentV []float32
// Use3BitLUT reports that the latents are stored as 32-element
// LearnedLUTBlocks. Each block runs along the reduction dimension of
// the MMA that reads it: BlocksK along Rank for S = q~ C_K^T, in
// row-major order; BlocksV along Tokens for o~ = P C_V, ordered by
// (32-token group, latent column).
Use3BitLUT bool
BlocksK []LearnedLUTBlock
BlocksV []LearnedLUTBlock
}
CompressedKVPage is a page of KV rows stored in the projector's latent subspace.
func (CompressedKVPage) Bytes ¶
func (c CompressedKVPage) Bytes() int64
Bytes returns the storage size of the page: 2 bytes per latent value in BF16, or 21 bytes per 32-value LUT block (12 bytes of 3-bit indices, an 8-byte E4M3 codebook and a UE8M0 scale).
type DynSparseSwiGLUResult ¶
type DynSparseSwiGLUResult struct {
H DynSparseTile // pruned h [M, I]
RowAbsMax []float32 // [M] max |h| per row (pre-pruning)
Out []float32 // [M, N] = prune(h) * w_down^T
}
DynSparseSwiGLUResult holds the outputs of TCGen05DynSparseSwiGLU.Reference.
type DynSparseTarget ¶
type DynSparseTarget uint8
DynSparseTarget names the runtime tensor that is pruned to 2:4 structured sparsity just before it is consumed as operand A of a tcgen05.mma.sp.
const ( // DynSparsePostSwiGLU prunes h = SiLU(gate) * up before the dense down_proj. DynSparsePostSwiGLU DynSparseTarget = iota // DynSparseKVCachePages prunes K or V pages along the MMA reduction // dimension (head dim for K in S^T = K Q^T, tokens for V in O^T = V^T P^T). DynSparseKVCachePages // DynSparseAttnProbP prunes the post-softmax probabilities P before P V. DynSparseAttnProbP )
func (DynSparseTarget) String ¶
func (t DynSparseTarget) String() string
String returns the name of t.
type DynSparseTile ¶
type DynSparseTile struct {
Target DynSparseTarget
Rows int
DenseCols int
Values []float32 // [Rows, DenseCols/2] kept values (dequantized when quantized)
Meta []uint32 // [Rows, DenseCols/32] 2:4 index metadata
// PackedE2M1 and ScalesUE8M0 are set only when the kept values were
// quantized to MXFP4: two E2M1 codes per byte, one UE8M0 scale per 32
// kept values ([Rows, DenseCols/4] and [Rows, DenseCols/64]).
PackedE2M1 []uint8
ScalesUE8M0 []uint8
// RetainedL2Energy is ||prune(x)||^2 / ||x||^2 of the pruning step alone
// (1 when x is all zeros).
RetainedL2Energy float64
}
DynSparseTile is a [Rows, DenseCols] tensor pruned at runtime to 2:4 structured sparsity along its columns.
Values and Meta use the layout of SpCompress2to4F32 applied row by row: Values holds the two kept elements of each 4-element group in ascending column order and Meta packs one 4-bit (idx0 | idx1<<2) nibble per group, eight groups per uint32 word.
func DynamicPrune2To4 ¶
func DynamicPrune2To4(target DynSparseTarget, x []float32, rows, cols int, quantize bool) (DynSparseTile, error)
DynamicPrune2To4 prunes the row-major [rows, cols] matrix x to 2:4 structured sparsity along its columns, keeping in every 4-element group the two elements of largest magnitude. Ties go to the lower column index, the MAXABS rule of PTX ISA 9.4 spcompress and tcgen05.ld.spcompress, so for any x the result retains the largest l2 energy of any 2:4 pattern.
cols must be a positive multiple of 32. When quantize is true, cols must be a multiple of 64 and the kept values are further quantized to MXFP4 (E2M1 with one UE8M0 scale per 32 kept values).
Example ¶
x := []float32{
0.1, -3, 2, 0.5, 1, 1, -1, 0, 4, 0, 0, -4, 0.2, 0.3, 0.1, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}
tile, err := DynamicPrune2To4(DynSparsePostSwiGLU, x, 1, 32, false)
if err != nil {
panic(err)
}
fmt.Println(tile.Values[:8])
fmt.Printf("meta %#08x\n", tile.Meta[0])
fmt.Printf("energy %.3f\n", tile.RetainedL2Energy)
Output: [-3 2 1 1 4 -4 0.2 0.3] meta 0x44444c49 energy 0.974
func (DynSparseTile) Dense ¶
func (t DynSparseTile) Dense() ([]float32, error)
Dense returns the [Rows, DenseCols] dense matrix that t represents, with pruned positions set to zero.
func (DynSparseTile) StorageBytes ¶
func (t DynSparseTile) StorageBytes(valueBits int) int64
StorageBytes returns the bytes needed to hold t: the kept values at valueBits each (4 when t is quantized, ignoring valueBits), the 2:4 metadata at 4 bits per 4-element group, and one byte per UE8M0 scale. A dense tensor of the same shape needs Rows*DenseCols*valueBits/8 bytes, so for BF16 the ratio is 9/16 and for 8-bit formats 5/8.
type ElemType ¶
type ElemType uint8
An ElemType is a matrix element type as named by the tcgen05.mma instruction descriptor tables.
type FlashLogitsOutput ¶
type FlashLogitsOutput struct {
SampledTokenID []int32 // Gumbel-max winner argmax_v z_v/T + G_v
SampledLogProb []float32 // z_winner/T - LSE
LSE []float32 // log sum_v exp(z_v/T)
DraftTokenProb []float32 // exp(z_draft/T - LSE), 0 when the draft token is out of range
}
FlashLogitsOutput holds the per-row results of the vocabulary stream.
type FlashLogitsSchedule ¶
type FlashLogitsSchedule struct {
Name string
Target string // "sm_100a", "sm_103a", "sm_107a" or "sm_107f" (default "sm_100a")
TileM int // token rows per CTA; must be 128
TileV int // vocabulary columns per TMEM tile; 32, 64 or 128 (default 64)
VocabSize int // V >= 1
HiddenDim int // D, a positive multiple of 32
Temperature float32 // T > 0
Seed uint64
DoubleBuffer bool
}
FlashLogitsSchedule configures a single-CTA LM head that streams the vocabulary through TMEM in TileV-column tiles and reduces each tile into per-row registers, so no [rows, VocabSize] logit array is ever written: for each of the TileM token rows it keeps the running max m and partition sum l of z/T (rescaling l by exp(m_old - m_new) when a tile raises the max), the Gumbel-max winner of z/T + G (G from FlashLogitsGumbel), and the scaled logit of an optional draft token.
The emitted kernel computes each tile with tcgen05.mma.cta_group::1.kind::tf32 over HiddenDim in 32-wide chunks, waiting on an mbarrier per chunk, into buffer t%2 of two TileV-column TMEM buffers when DoubleBuffer is set (one otherwise). It does not overlap the MMA of tile t+1 with the reduction of tile t: that needs a dedicated MMA warp and per-buffer barriers, which this emitter does not produce. The device path is emitted for sm_100a, sm_103a and sm_107a and has not been executed on tcgen05 hardware; under EG_EMU (cudahostemu and sm_12x devices) an exact C++ fallback runs instead. Speculative residual resampling is not implemented.
func (FlashLogitsSchedule) CUDA ¶
func (s FlashLogitsSchedule) CUDA() (string, error)
CUDA returns the kernel source without Prelude. The kernel signature is
NAME(const float* h, const float* w_vocab, const int* draft,
int* out_token, float* out_logprob, float* out_lse, float* out_draft_prob)
with h [TileM, HiddenDim], w_vocab [VocabSize, HiddenDim], draft [TileM] and the four outputs [TileM]. Global memory holds only these arrays.
func (FlashLogitsSchedule) CUDAFile ¶
func (s FlashLogitsSchedule) CUDAFile() (string, error)
CUDAFile returns the self-contained translation unit (Prelude plus CUDA).
func (FlashLogitsSchedule) ExecuteReference ¶
func (s FlashLogitsSchedule) ExecuteReference(h, wVocab []float32, draftTokens []int32) (FlashLogitsOutput, error)
ExecuteReference runs the tile-streamed algorithm on the host for the hidden states h [rows, HiddenDim] (rows = len(h)/HiddenDim, any count), vocabulary matrix wVocab [VocabSize, HiddenDim] and per-row draft tokens (nil or len rows; -1 for none). It holds one TileV-wide tile of logits at a time, never a [rows, VocabSize] array.
Example ¶
s := FlashLogitsSchedule{TileV: 32, VocabSize: 100, HiddenDim: 32, Temperature: 1, Seed: 42}
h := make([]float32, 32)
w := make([]float32, 100*32)
h[0] = 1
w[17*32] = 20 // token 17 has logit 20, all others 0
out, err := s.ExecuteReference(h, w, []int32{17})
if err != nil {
panic(err)
}
fmt.Printf("token %d, log p %.4f, draft p %.6f\n", out.SampledTokenID[0], out.SampledLogProb[0], out.DraftTokenProb[0])
Output: token 17, log p 0.0000, draft p 1.000000
func (FlashLogitsSchedule) Tiles ¶
func (s FlashLogitsSchedule) Tiles() int
Tiles returns the number of vocabulary tiles, ceil(VocabSize/TileV).
func (FlashLogitsSchedule) TraceEvents ¶
func (s FlashLogitsSchedule) TraceEvents() []layout.TraceEvent
TraceEvents returns the tcgen05 event sequence of the kernel for cudatmem.VerifyTrace.
func (FlashLogitsSchedule) Validate ¶
func (s FlashLogitsSchedule) Validate() error
Validate reports whether s describes a supported kernel.
type GB300ResidencyPlan ¶
type GB300ResidencyPlan struct {
Target string // PTX target ("sm_103a")
NumGPUs int // number of GPUs in the deployment domain
HBMBytesPerGPU int64 // HBM3e capacity per GPU in bytes
AvailableHBMBytes int64 // total HBM3e capacity across NumGPUs in bytes
WeightBytes int64 // total quantized weight + block-scale footprint in bytes
KVCacheBytes int64 // total KV cache footprint at (batchSize, seqLen) in bytes
ActivationBytes int64 // activation and scratch workspace footprint in bytes
TotalRequiredBytes int64 // WeightBytes + KVCacheBytes + ActivationBytes
RemainingHBMBytes int64 // AvailableHBMBytes - TotalRequiredBytes (0 when spilling)
SpilledC2CBytes int64 // bytes spilled to Grace LPDDR5X over NVLink-C2C (0 when FitsInHBM)
C2CColdFraction float64 // fraction of WeightBytes spilled to Grace LPDDR5X in [0, 1]
MaxHBMContextLen int64 // maximum sequence length per request that fits entirely in HBM3e
FitsInHBM bool // true when TotalRequiredBytes <= AvailableHBMBytes
}
GB300ResidencyPlan summarizes the HBM3e memory residency and NVLink-C2C cold spill fraction for a model deployed across numGPUs Blackwell Ultra GB300 GPUs.
func PlanGB300Residency ¶
func PlanGB300Residency(modelParams int64, weightBits int, kvBytesPerToken int64, batchSize, seqLen, numGPUs int) GB300ResidencyPlan
PlanGB300Residency computes the HBM3e residency plan on 288 GiB/GPU Blackwell Ultra GB300 (sm_103a) GPUs for a model with modelParams parameters quantized to weightBits bits per parameter, kvBytesPerToken bytes of KV state per token, and active request shape (batchSize, seqLen) distributed across numGPUs GPUs. For 4-bit block-scaled formats (NVFP4/MXFP4), it includes the 1 UE4M3 byte per 16-element block scale overhead (0.5 bits/param).
func PlanHBMResidencyWithCapacity ¶
func PlanHBMResidencyWithCapacity(target string, hbmBytesPerGPU int64, modelParams int64, weightBits int, kvBytesPerToken int64, batchSize, seqLen, numGPUs int) GB300ResidencyPlan
PlanHBMResidencyWithCapacity computes an HBM3e residency plan for an arbitrary per-GPU HBM capacity (e.g., 288 GiB on GB300 sm_103a vs 192 GiB on GB200 sm_100a).
type GB300Spec ¶
type GB300Spec struct {
// LocalityDomains is the measured per-domain geometry of this product.
LocalityDomains *devicetable.LocalityProfileSet
Target string // PTX architecture-accelerated target ("sm_103a")
FamilyTarget string // PTX family-conditional target ("sm_100f")
HBMBytes int64 // 12-Hi HBM3e capacity per GPU in bytes (288 GiB)
RackHBMBytes int64 // 72-GPU NVL72 rack HBM3e capacity in bytes (~20.7 TiB)
HBMBandwidthGBps float64 // HBM3e bandwidth per GPU in GB/s (8000 GB/s = 8.0 TB/s)
DenseFP4TFLOPS float64 // dense NVFP4/MXFP4 throughput in TFLOPS (15,000 TFLOPS = 15 PFLOPS, 1.5x B200)
DenseFP8TFLOPS float64 // dense FP8/BF16 throughput in TFLOPS (5,000 TFLOPS = 5 PFLOPS)
AttentionSFUMultiplier float64 // MUFU EX2/TANH throughput multiplier vs B200 (2.0x)
ScaleOutBandwidthGBps float64 // ConnectX-8 SuperNIC PCIe Gen6 x16 scale-out bandwidth in GB/s (100 GB/s = 800 Gb/s)
GraceLPDDR5XBytes int64 // Grace CPU LPDDR5X capacity in bytes (512 GiB per Grace CPU)
}
GB300Spec describes the hardware capabilities of an NVIDIA Blackwell Ultra B300 / GB300 GPU (compute capability 10.3, PTX target sm_103a, family target sm_100f) in the Cordelia socketed SXM Puck + ConnectX-8 SuperNIC platform.
func DefaultGB300Spec ¶
func DefaultGB300Spec() GB300Spec
DefaultGB300Spec returns the canonical hardware specification for an NVIDIA Blackwell Ultra GB300 (sm_103a) GPU.
type GEMMWeights ¶
type GEMMWeights struct {
BF16 []uint16
Lo []uint16
Packed []uint8
Scales []uint8
GlobalScal float32
E4M3 []uint8
}
GEMMWeights holds W in one of the formats of WeightFormat.
type InstDesc ¶
type InstDesc struct {
Kind Kind
Sparse bool // tcgen05.mma.sp
SparsitySelector uint8 // Table 51 kinds, sparse only: 0..3
SparsityVersion uint8 // mxf4 and mxf4nvf4, sparse only: 0 (v0) or 1 (v1)
Saturate bool // i8 only
DType ElemType // Table 51 kinds only: f16 or f32 (f16, f8f6f4), f32 (tf32), s32 (i8, ti16)
AType ElemType
BType ElemType
NegateA, NegateB bool
TransposeA, TransposeB bool
// M and N are the MMA shape. K is the MMA reduction extent of a single
// instruction, counting the logical (pre-compression) elements when
// Sparse is set; it must be zero for i8 and ti16, whose layout has no
// K field.
M, N, K int
// MaxShift is the maximum shift while attempting B-matrix reuse in
// tcgen05.mma.ws: 0, 8, 16, or 32. Table 51 kinds only.
MaxShift int
// Block-scaled kinds only.
ScaleType ScaleType
ScaleAID uint8 // matrix A scale factor data ID: 0..3 (mxf8f6f4), 0 or 2 (mxf4, mxf4nvf4)
ScaleBID uint8 // matrix B scale factor data ID: same range as ScaleAID
ScaleA128Lane bool // matrix A scale factor layout: 128 lanes instead of 32
}
InstDesc is the 32-bit instruction descriptor (idesc) operand of tcgen05.mma, laid out per PTX ISA 9.4 section 9.7.18.4.2.
The layout depends on Kind. Fields the layout for Kind does not contain must be zero; InstDesc.Encode rejects them otherwise, so that DecodeInstDesc(d.Kind, w) == d for every encodable d.
func DecodeInstDesc ¶
DecodeInstDesc unpacks a 32-bit tcgen05.mma instruction descriptor word laid out for kind. It returns an error if w sets a reserved bit or holds a code the layout does not define.
func (InstDesc) Encode ¶
Encode packs d into the 32-bit instruction descriptor word. It returns an error if d has a field the layout for d.Kind cannot represent.
func (InstDesc) ValidateForTarget ¶
ValidateForTarget reports whether d is encodable and valid on target, applying the target notes of PTX ISA 9.4 section 9.7.18.4.2.1: the K dimension select bits (29 for f8f6f4, 31 for mxf8f6f4, 3 for mxf4 and mxf4nvf4), the matrix A scale factor layout bit, and the UE5M3 scale type require sm_107a or sm_107f, and the mxf4/mxf4nvf4 sparsity version must be v1 on sm_107a/sm_107f and v0 elsewhere.
type JaggedAttention ¶
type JaggedAttention struct {
Name string
Target string // sm_100a, sm_103a, sm_107a or an f variant (default sm_100a)
MRoPE MRoPESpec
Causal bool
Scale float32 // softmax scale (default 1/sqrt(HeadDim))
}
A JaggedAttention configures single-head-per-CTA attention over a JaggedBatchSchedule: each CTA owns one 128-row query tile, applies the MRoPE rotation to q and k as it stages them, and streams 64-key tiles of its own sequence only: S = Q Kᵀ into TMEM, online softmax one query row per thread, the O correction applied in TMEM with tcgen05.ld/st, and O += P V accumulated in TMEM. Keys stop at kv_end = cu_seqlens[seq+1] (or the query tile end when Causal), so no tile reads another sequence.
The sm_100a/sm_103a/sm_107a path of the emitted source has not been executed; the EG_EMU path runs in the tests.
func (JaggedAttention) CUDA ¶
func (a JaggedAttention) CUDA() (string, error)
CUDA returns the kernel source without Prelude:
name(int tokens, const int* tile_seq, const int* tile_idx,
const int* cu_seqlens, const float* inv_freq, const int* pos,
const float* q, const float* k, const float* v, float* out)
tile_seq and tile_idx are the columns of a JaggedBatchSchedule's TileMap (TileM = 128), inv_freq is MRoPESpec.InvFreq, pos is [tokens][3], and q, k, v, out are [heads][tokens][HeadDim] with the head in blockIdx.y.
func (JaggedAttention) Grid ¶
func (a JaggedAttention) Grid(sched JaggedBatchSchedule, heads int) (grid, block [3]int)
Grid returns the launch shape for sched and heads heads.
func (JaggedAttention) Reference ¶
func (a JaggedAttention) Reference(sched JaggedBatchSchedule, q, k, v [][]float32, posTHW [][3]int32) ([][]float32, error)
Reference computes attention for one head in float64 after rotating q and k with ApplyMRoPEReference. q, k, v and the result are [tokens][HeadDim].
func (JaggedAttention) SharedBytes ¶
func (a JaggedAttention) SharedBytes() int
SharedBytes returns the dynamic shared memory the kernel needs, or 0 if a is invalid.
func (JaggedAttention) TMEMColumns ¶
func (a JaggedAttention) TMEMColumns() uint32
TMEMColumns returns the TMEM allocation width: S then O. It is 0 if the width exceeds MaxTMEMColumnsPerSM.
func (JaggedAttention) TraceEvents ¶
func (a JaggedAttention) TraceEvents(kvTiles int) []layout.TraceEvent
TraceEvents returns the tcgen05 operation sequence of a CTA that streams kvTiles key tiles.
func (JaggedAttention) Validate ¶
func (a JaggedAttention) Validate() error
Validate reports whether a describes a kernel this package can emit.
type JaggedBatchSchedule ¶
type JaggedBatchSchedule struct {
CuSeqlens []int32
TileM int
TileMap [][2]int // per tile: sequence index, tile index within the sequence
}
A JaggedBatchSchedule maps variable-length sequences, given by their prefix offsets CuSeqlens [B+1], to TileM-row query tiles that never cross a sequence boundary.
func BuildJaggedBatchSchedule ¶
func BuildJaggedBatchSchedule(cuSeqlens []int32, tileM int) (JaggedBatchSchedule, error)
BuildJaggedBatchSchedule tiles each sequence separately; empty sequences get no tiles.
Example ¶
// Three images of 73, 300 and 190 patches in one batch.
s, err := BuildJaggedBatchSchedule([]int32{0, 73, 373, 563}, 128)
if err != nil {
panic(err)
}
fmt.Println(s.Tokens(), s.TileMap)
Output: 563 [[0 0] [1 0] [1 1] [1 2] [2 0] [2 1]]
func (JaggedBatchSchedule) Tokens ¶
func (s JaggedBatchSchedule) Tokens() int
Tokens returns the total token count.
type KVCompressSchedule ¶
type KVCompressSchedule struct {
PageTokens int
HotWindowTokens int
Partition KVCompressorPartition
}
KVCompressSchedule decides which KV pages the background compressor handles: the most recent HotWindowTokens tokens stay uncompressed, and each completed page of PageTokens tokens that has left the hot window is compressed once.
func (KVCompressSchedule) Plan ¶
func (s KVCompressSchedule) Plan(seqLen, compressedPages int) ([]KVCompressTask, error)
Plan returns the pages to compress for a sequence of seqLen tokens when pages [0, compressedPages) are already compressed.
Example ¶
s := KVCompressSchedule{
PageTokens: 64,
HotWindowTokens: 256,
Partition: KVCompressorPartition{TotalSMs: 148, BackgroundSMs: 8, SMGranularity: 2},
}
tasks, err := s.Plan(600, 1)
if err != nil {
panic(err)
}
for _, task := range tasks {
fmt.Printf("page %d tokens [%d, %d) on background SM %d\n", task.PageID, task.FirstToken, task.FirstToken+64, task.SM)
}
Output: page 1 tokens [64, 128) on background SM 1 page 2 tokens [128, 192) on background SM 2 page 3 tokens [192, 256) on background SM 3 page 4 tokens [256, 320) on background SM 4
type KVCompressTask ¶
KVCompressTask assigns one page to one background SM (an index in [0, Partition.BackgroundSMs)). Pages map to SMs by PageID modulo the background SM count, so a page keeps its SM across calls.
type KVCompressorPartition ¶
KVCompressorPartition is the SM partition a background KV compressor requests: BackgroundSMs of TotalSMs run the compressor in their own green context while the rest serve decode. SMGranularity is the split unit the driver reports for the device; BackgroundSMs must be a multiple of it. This type only describes the request; creating the green context is left to the caller.
func (KVCompressorPartition) DecodeSMs ¶
func (p KVCompressorPartition) DecodeSMs() int
DecodeSMs returns the SMs left for the decode partition.
func (KVCompressorPartition) Validate ¶
func (p KVCompressorPartition) Validate() error
Validate checks that the partition leaves SMs on both sides and respects the split granularity.
type Kind ¶
type Kind uint8
A Kind is the .kind qualifier of a tcgen05.mma instruction. It selects the layout of the instruction descriptor.
type Lambda ¶
type Lambda struct {
// contains filtered or unexported fields
}
A Lambda is a scalar FP32 function of operands $0, $1, ..., written as an S-expression such as "(mul $0 (sigmoid $1))" or "(add $0 1.5)".
func MustLambda ¶
MustLambda is like ParseLambda but panics on error.
type LdRedOp ¶
type LdRedOp string
LdRedOp specifies the inline reduction operator (.redOp) for tcgen05.ld.red and tcgen05.ld.red.spcompress instructions (PTX ISA 9.4 section 9.7.18.8.3).
type LearnedLUTBlock ¶
type LearnedLUTBlock struct {
ScaleUE8M0 uint8
Codebook [8]uint8 // E4M3 centroid codes
Indices [32]uint8 // each in 0..7
WeightedMSE float64 // sum_i h_i (w_i - wHat_i)^2 / sum_i h_i
Iterations int // Lloyd-Max iterations run
}
LearnedLUTBlock is one 32-element weight block quantized to 3-bit indices into its own 8-entry E4M3 codebook with a UE8M0 block scale, the operand form of PTX ISA 9.4 tcgen05.mma ... .decompress::lut::b.block32. Weight i decodes as cuda.E4M3frombits(Codebook[Indices[i]]) * DecodeUE8M0(ScaleUE8M0).
func FitBlock32LearnedLUT ¶
func FitBlock32LearnedLUT(w, hessianDiag [32]float32, maxIters int) (LearnedLUTBlock, error)
FitBlock32LearnedLUT fits an 8-entry E4M3 codebook to the weight block w by Hessian-weighted Lloyd-Max, minimizing
sum_i h_i (w_i - 2^(s-127) c_{q_i})^2
over codebooks c on the E4M3 grid and indices q. The scale s is the smallest UE8M0 power of two with max|w| / 2^(s-127) <= 448. Centroids start at weighted quantiles with the largest h_i w_i^2 element pinned to an end centroid; each M-step rounds the weighted cluster mean to the nearest E4M3 value, which is the best grid point for that cluster, so the objective never increases. Fitting stops when the assignment is stable or after maxIters iterations. hessianDiag entries must be positive and finite; pass all ones for unweighted MSE.
Example ¶
var w, h [32]float32
for i := range w {
w[i] = float32(i%8) - 3.5 // eight distinct levels
h[i] = 1
}
w[0] = 12 // outlier
b, err := FitBlock32LearnedLUT(w, h, 50)
if err != nil {
panic(err)
}
u := UniformLUTBlock32(w)
fmt.Printf("learned mse %.4f, uniform mse %.4f\n", b.WeightedMSE, u.WeightedMSE)
p := b.PackIndices()
fmt.Printf("scale 2^%d, packed % x\n", int(b.ScaleUE8M0)-UE8M0Bias, p[:3])
Output: learned mse 0.0625, uniform mse 1.0391 scale 2^-5, packed 8f c6 da
func UniformLUTBlock32 ¶
func UniformLUTBlock32(w [32]float32) LearnedLUTBlock
UniformLUTBlock32 quantizes w with a fixed symmetric codebook of 8 uniformly spaced levels spanning [-max|w|, max|w|], rounded to E4M3, using the same scale rule as FitBlock32LearnedLUT. It is the baseline the learned codebook is measured against; WeightedMSE is unweighted.
func (LearnedLUTBlock) CodebookWords ¶
func (b LearnedLUTBlock) CodebookWords() [2]uint32
CodebookWords returns the codebook as the two little-endian 32-bit words copied into a 2-column TMEM LUT slot by tcgen05.cp.
func (LearnedLUTBlock) Dequantize ¶
func (b LearnedLUTBlock) Dequantize() [32]float32
Dequantize returns the 32 weights that b encodes.
func (LearnedLUTBlock) PackIndices ¶
func (b LearnedLUTBlock) PackIndices() [12]byte
PackIndices packs the 32 3-bit indices into a 96-bit little-endian stream: index i occupies bits 3i..3i+2.
type LoRAAdapterSlot ¶
type LoRAAdapterSlot struct {
AdapterID int
Rank int // 8, 16, 32 or 64
Scale float32 // alpha / r
AOffset int
BOffset int
}
A LoRAAdapterSlot locates one rank-r adapter in the unified adapter pools: rows [AOffset, AOffset+Rank) of the A pool [rows][DimIn] hold A_a and rows [BOffset, BOffset+Rank) of the B pool [rows][DimOut] hold B_aᵀ.
type LoRAGatherPlan ¶
type LoRAGatherPlan struct {
// Order lists token indices grouped by ascending adapter ID, in index
// order within a group; base-only tokens (adapter -1) come last.
Order []int32
// Segments covers the adapter tokens of Order; base-only tokens are in
// no segment and get no LoRA work.
Segments []LoRASegment
// TokenQuads and ARowQuads are the row indices of four-row TMA
// .gather4 loads of x and of the A pool. A segment's last quad repeats
// its final row.
TokenQuads [][4]int32
ARowQuads [][4]int32
}
A LoRAGatherPlan groups a batch's tokens by adapter for segmented LoRA.
func PlanLoRAGather ¶
func PlanLoRAGather(tokenAdapterIDs []int, adapters map[int]LoRAAdapterSlot) (LoRAGatherPlan, error)
PlanLoRAGather groups tokens by adapter. tokenAdapterIDs[i] is token i's adapter ID, or -1 for the base model only; every other ID must be in adapters.
func (LoRAGatherPlan) Gather4Specs ¶
func (p LoRAGatherPlan) Gather4Specs(target string, dimIn, elemBytes int) ([]layout.TMAGather4Spec, error)
Gather4Specs returns the TMA .gather4 loads of p's token quads followed by its A-pool quads, for rows of dimIn elements of elemBytes bytes.
type LoRASegment ¶
type LoRASegment struct {
Slot LoRAAdapterSlot
Start, End int // positions [Start, End) in Order
TokenQuads [2]int // range of TokenQuads covering the segment's tokens
ARowQuads [2]int // range of ARowQuads covering the adapter's A rows
}
A LoRASegment is a run of tokens that share one adapter in a LoRAGatherPlan's order.
type MRoPESpec ¶
An MRoPESpec configures multimodal rotary position embedding: the first PairsT rotary pairs of a head turn by the temporal position, the next PairsH by the height position, and the next PairsW by the width position. Pair i rotates channels (i, i+R) with R = PairsT+PairsH+PairsW (rotate-half layout) at frequency BaseTheta^(-i/R); channels [2R, HeadDim) are not rotated.
type Problem ¶
type Problem struct {
Arch string // exact target, such as "sm_100a"
SMEMCapBytes int // shared memory per CTA
TileSMEMBytes int // bytes one ring stage holds
EpilogueSMEMBytes int // shared memory outside the ring
TMALatency uint64 // cycles from TMA issue to data in shared memory
Roles []RoleDemand
TMEM []TMEMBufferReq
Totals []int // allowed total warp counts; nil means 8, 12, 16
}
A Problem is the input to Synthesize.
type ProtocolError ¶
type ProtocolError struct {
Kind ProtocolErrorKind
Search string // "exhaustive", "producer-first", "consumer-first" or "round-robin"
Role WarpRoleKind
Tile int
Ring int
Stage int
Detail string
}
A ProtocolError reports the first failure found and the scheduler or search that found it.
func (*ProtocolError) Error ¶
func (e *ProtocolError) Error() string
type ProtocolErrorKind ¶
type ProtocolErrorKind int
A ProtocolErrorKind classifies a ring-protocol failure.
const ( Deadlock ProtocolErrorKind = iota // no role can step before every tile finishes Race // a stage is written before its previous tile is released StaleRead // a stage is read while it holds another tile ParityAlias // a wait passed on parity while the phase count differs )
func (ProtocolErrorKind) String ¶
func (k ProtocolErrorKind) String() string
type RoleAssignment ¶
type RoleAssignment struct {
Kind WarpRoleKind
FirstWarp int // index of the role's first warp in the CTA
Warps int
Regs int // setmaxnreg target
Cycles uint64 // modelled cycles per tile
}
A RoleAssignment is one role's place in a Schedule.
type RoleDemand ¶
type RoleDemand struct {
Kind WarpRoleKind
MinWarps int // rounded up to a multiple of 4
MinRegs int // registers per thread for zero spills, rounded up to a multiple of 8
WorkCyclesTile uint64 // cycles per tile at MinWarps
ScalesWithWarps bool // work divides across extra warps
}
A RoleDemand is what one role needs: its minimum warps and registers, and its work per tile at the minimum warp count.
type RubinSpCompressDecompressKernel ¶
type RubinSpCompressDecompressKernel struct {
NumElements int // number of elements; defaults to 256 (must be a positive multiple of 32)
Desc SpCompressDesc // 32-bit spdesc configuration; defaults to {Op: SpOpMaxAbs, ElemType: SpTypeE4M3}
Ratio string // sparsity ratio; defaults to "2:4"
Target string // PTX target ("sm_107a" or "sm_107f"; defaults to "sm_107a")
}
RubinSpCompressDecompressKernel configures a Rubin sm_107a/sm_107f register-to-register structured sparsity compression and decompression kernel demonstrating PTX ISA 9.4 §9.7.10.30 (spcompress) and §9.7.10.31 (spdecompress).
Example ¶
desc := SpCompressDesc{Op: SpOpMaxAbs, ElemType: SpTypeE4M3}
k := RubinSpCompressDecompressKernel{
NumElements: 32,
Desc: desc,
Ratio: SpRatio2to4,
Target: "sm_107a",
}
in := make([]float32, 32)
in[0], in[1], in[2], in[3] = -4.0, 1.5, -0.5, 3.0
cdata, mdata, recon, err := k.Reference(in)
src, _ := k.CUDA()
fmt.Printf("err=%v spdesc=0x%02x cdata0=(%.1f, %.1f) nib0=0x%x recon0=(%.1f, %.1f, %.1f, %.1f) ptx=%v\n",
err, desc.Encode(), cdata[0], cdata[1], mdata[0]&0xf,
recon[0], recon[1], recon[2], recon[3],
strings.Contains(src, "spcompress.b8.b2.sp::2:4.x4") && strings.Contains(src, "spdecompress.b8.b2.sp::2:4.x32"))
Output: err=<nil> spdesc=0x0d cdata0=(-4.0, 3.0) nib0=0xc recon0=(-4.0, 0.0, 0.0, 3.0) ptx=true
func (RubinSpCompressDecompressKernel) CUDA ¶
func (k RubinSpCompressDecompressKernel) CUDA() (string, error)
CUDA emits the CUDA C++ kernel source (without Prelude) for eg_rubin_spcompress_roundtrip, containing inline PTX blocks for spcompress.b8.b2.sp::2:4.x4 and spdecompress.b8.b2.sp::2:4.x32 guarded by __CUDA_ARCH__ == 1070 plus exact C++ execution of 2:4 compression and decompression driven by spdesc.
func (RubinSpCompressDecompressKernel) CUDAFile ¶
func (k RubinSpCompressDecompressKernel) CUDAFile() (string, error)
CUDAFile emits the self-contained CUDA C++ translation unit (including Prelude) for k, ready for cudahostemu.Run or nvcc.
func (RubinSpCompressDecompressKernel) Grid ¶
func (k RubinSpCompressDecompressKernel) Grid() (grid, block [3]int)
Grid returns the single-CTA grid and 64-thread block dimensions for k.
func (RubinSpCompressDecompressKernel) Reference ¶
func (k RubinSpCompressDecompressKernel) Reference(in []float32) (cdata []float32, mdata []uint32, reconstructed []float32, err error)
Reference executes the host reference 2:4 compression and decompression round-trip on in (length k.NumElements, or defaulted to 256) using k.Desc.Op.
func (RubinSpCompressDecompressKernel) Validate ¶
func (k RubinSpCompressDecompressKernel) Validate() error
Validate checks that k has valid element count, descriptor, sparsity ratio, and Rubin target ("sm_107a" or "sm_107f").
type SSMChunkSchedule ¶
type SSMChunkSchedule struct {
Name string
Target string // sm_100a, sm_103a, sm_107a or an f variant (default sm_100a)
Variant SSMVariant
HeadDimK int // d_k: 32, 64, 96 or 128
HeadDimV int // d_v: 32, 64, 96 or 128
ChunkLen int // L: 32, 64 or 128 tokens per chunk
NumChunks int // chunks per sequence
ConvKernel int // depthwise causal conv1d width over q, k, v (0 disables it, at most 4)
}
An SSMChunkSchedule configures a chunkwise linear-recurrence kernel that keeps the FP32 state S in TMEM across all chunks of a sequence, one head per CTA iteration of a persistent loop.
Per chunk of L tokens the kernel stages Q, K and V (after an optional causal depthwise convolution computed with tcgen05.shift.down) in shared memory, and with cumulative in-chunk decays g_t computes
O = diag(g) Q Sᵀ + (Γ ⊙ Q Kᵀ) U (inter + intra chunk) S = g_L S + Uᵀ diag(g_L / g) K (state update, enable_input_d = 1)
where U = V for Mamba-2 and, for the gated delta rule, U solves the unit lower-triangular system (I + diag(β) Γ⁻ ⊙ K Kᵀ) U = diag(β)(V - diag(g) K Sᵀ) by forward substitution. S is the TMEM A operand of the Q Sᵀ and K Sᵀ MMAs; the decays scale S and O in place with tcgen05.ld/st.
TMEM layout (lanes are state rows d_v): S at columns [0, HeadDimK), the K Kᵀ / Q Kᵀ scratch at [HeadDimK, +L), K Sᵀ at [HeadDimK+L, +L), O at [HeadDimK+2L, +L). The convolution reuses the two scratch ranges.
The sm_100a/sm_103a/sm_107a path of the emitted source is compiled by the native qualification test but has not been executed; the EG_EMU path is what the tests run (cudahostemu on the host, and sm_121a under CUDA_TCGEN05_NATIVE=1).
func (SSMChunkSchedule) CUDA ¶
func (s SSMChunkSchedule) CUDA() (string, error)
CUDA returns the kernel source without Prelude. The kernel signature is
name(int heads, const float* q, const float* k, const float* v,
const float* alpha, const float* beta,
const float* conv_q, const float* conv_k, const float* conv_v,
float* out, float* state)
with q, k [heads][T][d_k], v and out [heads][T][d_v], alpha and beta [heads][T], conv_x [heads][ConvKernel][d_x], and state [heads][d_v][d_k]. beta and conv_x may be null when unused.
func (SSMChunkSchedule) CUDAFile ¶
func (s SSMChunkSchedule) CUDAFile() (string, error)
CUDAFile returns Prelude followed by SSMChunkSchedule.CUDA.
func (SSMChunkSchedule) Grid ¶
func (s SSMChunkSchedule) Grid(heads, ctas int) (grid, block [3]int)
Grid returns the launch shape for heads heads on at most ctas resident CTAs (ctas <= 0 means one CTA per head).
func (SSMChunkSchedule) Reference ¶
func (s SSMChunkSchedule) Reference(in SSMInput) (out, state [][]float32, err error)
Reference runs the token-by-token recurrence in float64 and returns the outputs o_t [T][HeadDimV] and the final state S [HeadDimV][HeadDimK].
func (SSMChunkSchedule) ReferenceChunked ¶
func (s SSMChunkSchedule) ReferenceChunked(in SSMInput) (out, state [][]float32, err error)
ReferenceChunked computes the same result as SSMChunkSchedule.Reference in float64 with the chunkwise algorithm the kernel uses: per chunk an inter-chunk term from the carried state, a masked intra-chunk term, the delta-rule triangular solve, and one rank-L state update.
func (SSMChunkSchedule) SeqLen ¶
func (s SSMChunkSchedule) SeqLen() int
SeqLen returns ChunkLen * NumChunks.
func (SSMChunkSchedule) SharedBytes ¶
func (s SSMChunkSchedule) SharedBytes() int
SharedBytes returns the dynamic shared memory the kernel needs, or 0 if s is invalid.
func (SSMChunkSchedule) TMEMColumns ¶
func (s SSMChunkSchedule) TMEMColumns() uint32
TMEMColumns returns the TMEM allocation width of the kernel. It is 0 if the width exceeds MaxTMEMColumnsPerSM.
func (SSMChunkSchedule) TraceEvents ¶
func (s SSMChunkSchedule) TraceEvents() []layout.TraceEvent
TraceEvents returns the tcgen05 operation sequence of one head, for cudatmem.VerifyTrace.
func (SSMChunkSchedule) Validate ¶
func (s SSMChunkSchedule) Validate() error
Validate reports whether s describes a kernel this package can emit.
type SSMInput ¶
type SSMInput struct {
Q, K [][]float32 // [T][HeadDimK]
V [][]float32 // [T][HeadDimV]
Alpha []float32 // [T] decay in (0, 1]
Beta []float32 // [T] delta-rule write strength; unused by SSMMamba2SSD
ConvQ, ConvK [][]float32 // [ConvKernel][HeadDimK] depthwise taps; tap j weights x_{t-j}
ConvV [][]float32 // [ConvKernel][HeadDimV]
}
An SSMInput holds one head's sequence for SSMChunkSchedule.Reference.
type SSMVariant ¶
type SSMVariant uint8
An SSMVariant selects the linear recurrence an SSMChunkSchedule runs. S_t is the d_v x d_k state; o_t = S_t q_t.
const ( // SSMMamba2SSD is the Mamba-2 state-space dual recurrence // S_t = alpha_t S_{t-1} + v_t k_tᵀ. SSMMamba2SSD SSMVariant = iota // SSMGatedDeltaNet is the gated delta rule // S_t = alpha_t S_{t-1} (I - beta_t k_t k_tᵀ) + beta_t v_t k_tᵀ. SSMGatedDeltaNet )
func (SSMVariant) String ¶
func (v SSMVariant) String() string
type ScaleType ¶
type ScaleType uint8
A ScaleType is the element type of the block scale factors of a block-scaled tcgen05.mma.
type Schedule ¶
type Schedule struct {
Arch string
Roles []RoleAssignment // in chain order
TotalWarps int
LaunchRegs int // .maxnreg at launch; the pool is 32·TotalWarps·LaunchRegs
TotalRegsUsed int // 32·Σ Warps·Regs
PipelineStagesD int // shared-memory ring depth
RingDepths []int
TMEM []TMEMPlacement
TotalTMEMCols uint16 // columns to allocate; 0 if no TMEM
SMEMBytes int
SMEMCapBytes int
UseEarlySMEMRelease bool // the MMA issuer releases a stage on its commit
BottleneckCycTile uint64 // slowest role
SteadyStateCycTile uint64 // modelled period per tile
TMASlack int64 // D·period minus stage occupancy; negative means exposed latency
Candidates int // configurations enumerated
}
A Schedule is a warp-specialization plan that satisfies the invariants listed in the package documentation.
func Synthesize ¶
Synthesize searches the configurations described in the package documentation and returns the one with the smallest modelled period, then the largest TMA slack, then the fewest warps, the shallowest ring, early release before late, and the lexicographically smallest warp split.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/tcgen05"
)
func main() {
s, err := tcgen05.Synthesize(tcgen05.Problem{
Arch: "sm_100a",
SMEMCapBytes: 228 * 1024,
TileSMEMBytes: 32 * 1024,
TMALatency: 1000,
Roles: []tcgen05.RoleDemand{
{Kind: tcgen05.RoleTMAProducer, MinWarps: 4, MinRegs: 40, WorkCyclesTile: 400},
{Kind: tcgen05.RoleMMAIssuer, MinWarps: 4, MinRegs: 64, WorkCyclesTile: 1000},
{Kind: tcgen05.RoleEpilogueMath, MinWarps: 4, MinRegs: 200, WorkCyclesTile: 2400, ScalesWithWarps: true},
},
TMEM: []tcgen05.TMEMBufferReq{{Name: "acc", WidthCols: 256, DoubleBuf: true}},
})
if err != nil {
fmt.Println(err)
return
}
for _, r := range s.Roles {
fmt.Printf("%s: %d warps, setmaxnreg %d\n", r.Kind, r.Warps, r.Regs)
}
fmt.Printf("D=%d early=%v TMEM acc at %v of %d\n", s.PipelineStagesD, s.UseEarlySMEMRelease, s.TMEM[0].Cols, s.TotalTMEMCols)
fmt.Println("deadlock-free over 1000 tiles:", tcgen05.VerifyDeadlockFreedom(s, 1000) == nil)
}
Output: TMAProducer: 4 warps, setmaxnreg 40 MMAIssuer: 4 warps, setmaxnreg 72 EpilogueMath: 8 warps, setmaxnreg 200 D=7 early=true TMEM acc at [0 256] of 512 deadlock-free over 1000 tiles: true
func (Schedule) Check ¶
Check verifies the hardware invariants listed in the package documentation. Synthesize calls it on every schedule it returns.
func (Schedule) EmitHostEmuCUDA ¶
EmitHostEmuCUDA returns CUDA C++ for package cudahostemu that runs the schedule's ring protocol over numTiles tiles. kernelName(in, out) copies each tile of HostEmuElems floats from in into a ring stage with cp.async.bulk, and the following roles compute out = 2·in + 1 through the remaining rings, with the same waits, parities, role-local barriers, elected arrivals and release points as the PTX skeleton. The producer is a single elected thread, as a TMA issuer is. Launch it with eg_emu_launch(dim3(1), dim3(32·TotalWarps), PipelineStagesD·HostEmuElems·4, kernelName, in, out).
func (Schedule) EmitWarpSpecializedSkeletonPTX ¶
EmitWarpSpecializedSkeletonPTX returns a PTX entry kernelName(num_tiles) that runs the schedule's ring protocol with the work left as comments: role dispatch on %tid.x/32, setmaxnreg per role, mbarrier initialization, and per-tile wait loops on (k/D)&1 parity. Each role's warps meet at a role-local named barrier (bar.sync 1+role) before one elected thread arrives. The producer arrives with expect_tx of 0 bytes, standing in for the TMA transaction count. With UseEarlySMEMRelease on a target with TMEM, the MMA issuer releases a stage with tcgen05.commit, which arrives once the tcgen05 operations before it complete.
The output has not been assembled by this package; see the package documentation.
func (Schedule) Role ¶
func (s Schedule) Role(kind WarpRoleKind) (RoleAssignment, bool)
Role returns the assignment for kind, and false if the schedule has none.
type SegmentedLoRASchedule ¶
type SegmentedLoRASchedule struct {
Name string
Target string // sm_100a, sm_103a, sm_107a or an f variant (default sm_100a)
DimIn int // K, a multiple of BK
DimOut int // N, a multiple of TileN
TileN int // output columns per CTA: a multiple of 16 in [16, 256] (default min(DimOut, 256))
BK int // K step: 8, 16, 32 or 64 (default 32)
MaxRank int // largest adapter rank, at most 64
}
A SegmentedLoRASchedule configures a fused base + multi-adapter LoRA projection. Each CTA owns 128 consecutive tokens of a LoRAGatherPlan's order and TileN output columns:
D = X Wᵀ (TMEM columns [0, TileN)) U = X_s A_aᵀ (TMEM columns [TileN, TileN+R), per segment s) D += (scale_a U) B_aᵀ (enable_input_d = 1 onto the base accumulator)
where X_s keeps only the rows of segment s, so other tokens' rows of U are zero. Y_base and U never leave the CTA. Tokens are gathered by row index in four-row groups by the threads; the TMA .gather4 form of those loads is described by LoRAGatherPlan.Gather4Specs, not issued by the kernel. The sm_100a/sm_103a/sm_107a path of the emitted source has not been executed; the EG_EMU path runs in the tests.
func (SegmentedLoRASchedule) CUDA ¶
func (s SegmentedLoRASchedule) CUDA() (string, error)
CUDA returns the kernel source without Prelude. The kernel signature is
name(int tokens, int nsegs, const int* order,
const int* seg_start, const int* seg_end, const int* seg_rank,
const int* seg_aoff, const int* seg_boff, const float* seg_scale,
const float* x, const float* w, const float* a_pool,
const float* b_pool, float* y)
with order and the seg_ arrays taken from a LoRAGatherPlan, x [tokens][DimIn], w [DimOut][DimIn], and y [tokens][DimOut] in token order.
func (SegmentedLoRASchedule) CUDAFile ¶
func (s SegmentedLoRASchedule) CUDAFile() (string, error)
CUDAFile returns Prelude followed by SegmentedLoRASchedule.CUDA.
func (SegmentedLoRASchedule) Grid ¶
func (s SegmentedLoRASchedule) Grid(tokens int) (grid, block [3]int)
Grid returns the launch shape for tokens tokens.
func (SegmentedLoRASchedule) SharedBytes ¶
func (s SegmentedLoRASchedule) SharedBytes() int
SharedBytes returns the dynamic shared memory the kernel needs, or 0 if s is invalid.
func (SegmentedLoRASchedule) TMEMColumns ¶
func (s SegmentedLoRASchedule) TMEMColumns() uint32
TMEMColumns returns the TMEM allocation width: the base tile plus the shrink intermediate. It is 0 if the width exceeds MaxTMEMColumnsPerSM.
func (SegmentedLoRASchedule) TraceEvents ¶
func (s SegmentedLoRASchedule) TraceEvents(segments int) []layout.TraceEvent
TraceEvents returns the tcgen05 operation sequence of a CTA whose tokens span segments adapter segments.
func (SegmentedLoRASchedule) Validate ¶
func (s SegmentedLoRASchedule) Validate() error
Validate checks that the base accumulator and the shrink intermediate fit disjointly in TMEM and the operand tiles in shared memory.
type SharedDesc ¶
type SharedDesc struct {
}
SharedDesc models the 64-bit shared-memory matrix descriptor consumed by tcgen05.mma and tcgen05.cp (PTX ISA 9.4 section 9.7.18.4.1).
BaseAddr, LeadingByteOffset, and StrideByteOffset are 16-byte aligned byte offsets. BaseAddr and StrideByteOffset have an 18-bit byte range (bits 4..17, up to 0x3fff0). LeadingByteOffset has an 18-bit byte range in relative mode (LBOMode false, bits 16..29) and a 19-bit byte range in absolute mode (LBOMode true, bits 16..30, up to 0x7fff0). BaseOffset is a 3-bit matrix base offset (0..7, bits 49..51). LUTB sets bit 53 (lut::b). Bits 46..48 are fixed 0b001, and bits 14..15, 31, 54..60 (plus bit 30 when LBOMode is false) are fixed 0.
func DecodeSharedDesc ¶
func DecodeSharedDesc(w uint64) (SharedDesc, error)
DecodeSharedDesc unpacks a 64-bit tcgen05 shared-memory descriptor word per PTX ISA 9.4 section 9.7.18.4.1. It returns an error if the version bits (46..48) are not 0b001, the swizzle mode (61..63) is invalid, or any fixed zero bit is set.
func (SharedDesc) Encode ¶
func (d SharedDesc) Encode() (uint64, error)
Encode packs d into a 64-bit tcgen05 shared-memory descriptor word per PTX ISA 9.4 section 9.7.18.4.1. It returns an error if any field is misaligned, out of range, or holds an invalid swizzle mode.
type SpCompressDesc ¶
type SpCompressDesc struct {
Op SpCompressOp
ElemType SpElemType
}
SpCompressDesc models the 32-bit sparsity compression descriptor (spdesc) consumed by PTX ISA 9.4 §9.7.10.30.1 Table 36:
- bits 0..1: Op (MAX=0, MAXABS=1, MIN=2, MINABS=3)
- bits 2..4: ElemType (.f16=0, .bf16=1, .e5m2=2, .e4m3=3, .e3m2=4, .e2m3=5, .u8=6, .s8=7)
- bits 5..31: reserved (must be 0)
func DecodeSpCompressDesc ¶
func DecodeSpCompressDesc(v uint32) (SpCompressDesc, error)
DecodeSpCompressDesc unpacks a 32-bit spdesc register value into an SpCompressDesc, returning an error if any reserved bit in bits 5..31 is non-zero.
func (SpCompressDesc) Encode ¶
func (d SpCompressDesc) Encode() uint32
Encode packs d into a 32-bit spdesc register value with bits 5..31 cleared to 0.
func (SpCompressDesc) Validate ¶
func (d SpCompressDesc) Validate() error
Validate checks that d.Op and d.ElemType are within their PTX ISA 9.4 Table 36 ranges.
type SpCompressOp ¶
type SpCompressOp uint8
SpCompressOp specifies the comparison operation used by PTX ISA 9.4 §9.7.10.30 spcompress (bits 0..1 of the 32-bit spdesc descriptor, Table 36).
const ( SpOpMax SpCompressOp = 0 // MAX: select the 2 elements with largest signed value SpOpMaxAbs SpCompressOp = 1 // MAXABS: select the 2 elements with largest absolute value SpOpMin SpCompressOp = 2 // MIN: select the 2 elements with smallest signed value SpOpMinAbs SpCompressOp = 3 // MINABS: select the 2 elements with smallest absolute value )
func (SpCompressOp) String ¶
func (op SpCompressOp) String() string
String returns the PTX ISA 9.4 Table 36 mnemonic for op.
type SpElemType ¶
type SpElemType uint8
SpElemType specifies the element data type encoded in bits 2..4 of the 32-bit spdesc descriptor for PTX ISA 9.4 §9.7.10.30 spcompress (Table 36).
const ( SpTypeF16 SpElemType = 0 // .f16 (16-bit IEEE 754 binary16) SpTypeBF16 SpElemType = 1 // .bf16 (16-bit bfloat16) SpTypeE5M2 SpElemType = 2 // .e5m2 (8-bit OCP FP8 E5M2) SpTypeE4M3 SpElemType = 3 // .e4m3 (8-bit OCP FP8 E4M3) SpTypeE3M2 SpElemType = 4 // .e3m2 (8-bit-padded OCP FP6 E3M2) SpTypeE2M3 SpElemType = 5 // .e2m3 (8-bit-padded OCP FP6 E2M3) SpTypeU8 SpElemType = 6 // .u8 (8-bit unsigned integer) SpTypeS8 SpElemType = 7 // .s8 (8-bit signed integer) )
func (SpElemType) BitWidth ¶
func (t SpElemType) BitWidth() int
BitWidth returns the storage bit width (16 for .f16/.bf16, 8 for 8-bit types) of t in PTX spcompress (.b16 vs .b8).
func (SpElemType) String ¶
func (t SpElemType) String() string
String returns the PTX type qualifier for t.
type SubspaceKVProjector ¶
type SubspaceKVProjector struct {
NumKVHeads int
HeadDim int
Rank int
BasisK []float32
BasisV []float32
ExplainedVarK float64 // fraction of sum ||k||^2 in the calibration sample captured by BasisK
ExplainedVarV float64
}
SubspaceKVProjector projects GQA key and value rows of width NumKVHeads*HeadDim onto Rank-dimensional subspaces shared by all KV heads.
BasisK and BasisV are row-major [NumKVHeads*HeadDim, Rank] matrices with orthonormal columns (U^T U = I). A key row k is stored as c = k U_K and read back as c U_K^T. The basis is meant for keys before RoPE (or layers without RoPE): rotary embeddings applied after projection do not commute with U_K, and this package does not model them.
func CalibrateSubspaceBasis ¶
func CalibrateSubspaceBasis(sampleK, sampleV []float32, tokens, numKVHeads, headDim, rank int) (SubspaceKVProjector, error)
CalibrateSubspaceBasis returns the projector whose bases are the top-rank eigenvectors of the uncentered second-moment matrices K^T K and V^T V of the calibration rows sampleK, sampleV [tokens, numKVHeads*headDim], found by one-sided Jacobi on the sample itself (tokens <= D) or on the D x D second-moment matrix. No gradients or training are involved.
func (SubspaceKVProjector) AbsorbedLatentAttention ¶
func (p SubspaceKVProjector) AbsorbedLatentAttention(q []float32, numQHeads int, c CompressedKVPage) (scores, out []float32, err error)
AbsorbedLatentAttention computes single-position GQA attention for the queries q [numQHeads, HeadDim] against page without reconstructing K or V. For query head h in KV group g = h / (numQHeads/NumKVHeads), with U_{K,g} the HeadDim rows of BasisK belonging to head g, it forms q~ = q_h U_{K,g} in R^Rank, scores s_t = q~ . C_K[t] / sqrt(HeadDim), o~ = softmax(s) C_V and o_h = U_{V,g} o~. This equals attention over the reconstructed rows of SubspaceKVProjector.DecompressKVPage up to rounding. It returns the pre-softmax scores [numQHeads, Tokens] and the outputs [numQHeads, HeadDim].
func (SubspaceKVProjector) CompressKVPage ¶
func (p SubspaceKVProjector) CompressKVPage(k, v []float32, tokens, pageID int, use3BitLUT bool) (CompressedKVPage, error)
CompressKVPage projects the rows k, v [tokens, Dim()] onto the latent subspace. With use3BitLUT, each 32-value block of the latents (see CompressedKVPage) is fitted with FitBlock32LearnedLUT with unit weights, which needs Rank and tokens to be multiples of 32.
func (SubspaceKVProjector) CompressionRatio ¶
func (p SubspaceKVProjector) CompressionRatio(c CompressedKVPage) float64
CompressionRatio returns the BF16 size of the uncompressed K and V rows divided by c.Bytes().
func (SubspaceKVProjector) DecompressKVPage ¶
func (p SubspaceKVProjector) DecompressKVPage(c CompressedKVPage) (k, v []float32)
DecompressKVPage returns the reconstructed rows k = C_K U_K^T and v = C_V U_V^T, each [Tokens, Dim()].
func (SubspaceKVProjector) Dim ¶
func (p SubspaceKVProjector) Dim() int
Dim returns NumKVHeads*HeadDim, the width of a full KV row.
func (SubspaceKVProjector) Validate ¶
func (p SubspaceKVProjector) Validate() error
Validate checks the projector's shape and that both bases are orthonormal to within 1e-5.
type Swizzle ¶
type Swizzle uint8
Swizzle specifies the shared-memory swizzle pattern for a tcgen05 matrix descriptor (PTX ISA 9.4 section 9.7.18.4.1, bits 61-63).
type TCGen05BlockScaledGEMM ¶
type TCGen05BlockScaledGEMM struct {
Name string
M int // defaults to 128 (must be 128)
N int // defaults to 128 (must be 128)
K int // defaults to 64 (or 128 when ScaleVec4X is true; multiple of 16 in 16..256)
ScaleVec4X bool // when true, emits sm_103a scale_vec::4X (K multiple of 64, 4 E4M3 scales per step)
}
TCGen05BlockScaledGEMM emits an sm_100a/sm_103a NVFP4 block-scaled GEMM that stages UE4M3 block scales into shared memory, copies them into dedicated TMEM columns via tcgen05.cp.cta_group::1.32x128b, issues tcgen05.mma.cta_group::1.kind::mxf4nvf4.block_scale (or with .scale_vec::4X when ScaleVec4X is true on sm_103a), and reads the accumulated tile via 4-warp 32-row partitioned tcgen05.ld.
func (TCGen05BlockScaledGEMM) CUDA ¶
func (k TCGen05BlockScaledGEMM) CUDA() (string, error)
CUDA emits the complete CUDA C++ source (without Prelude) for k.
func (TCGen05BlockScaledGEMM) Grid ¶
func (k TCGen05BlockScaledGEMM) Grid() (grid, block [3]int)
Grid returns the single-CTA grid and 128-thread (4-warp) block dimensions.
func (TCGen05BlockScaledGEMM) TraceEvents ¶
func (k TCGen05BlockScaledGEMM) TraceEvents() []layout.TraceEvent
TraceEvents returns the formal sm_100a/sm_103a tcgen05 hardware protocol event trace for verification with cudatmem.VerifyTrace.
type TCGen05Cluster2GEMM ¶
type TCGen05Cluster2GEMM struct {
Name string
M int // defaults to 256 (must be 256)
N int // defaults to 128 (must be 128)
K int // defaults to 32 (must be a positive multiple of 16)
}
TCGen05Cluster2GEMM emits an sm_100a/sm_103a 2-CTA cooperative (__cluster_dims__(2,1,1)) M=256, N=128 GEMM (128x128 per CTA) using tcgen05.mma.cta_group::2, distributed shared memory via eg_emu_map_shared_rank, and 4-warp 32-row partitioned tcgen05.ld epilogue loads.
func (TCGen05Cluster2GEMM) CUDA ¶
func (k TCGen05Cluster2GEMM) CUDA() (string, error)
CUDA emits the complete CUDA C++ source (without Prelude) for k.
func (TCGen05Cluster2GEMM) Grid ¶
func (k TCGen05Cluster2GEMM) Grid() (grid, block [3]int)
Grid returns the 2-CTA cluster grid and 128-thread (4-warp) block dimensions.
func (TCGen05Cluster2GEMM) Launcher ¶
func (k TCGen05Cluster2GEMM) Launcher() (string, error)
Launcher returns the host launcher of k, which requests SharedBytes of dynamic shared memory.
func (TCGen05Cluster2GEMM) SharedBytes ¶
func (k TCGen05Cluster2GEMM) SharedBytes() int
SharedBytes returns the dynamic shared memory, in bytes, that each CTA of k declares and its launcher requests, or 0 if k is invalid.
func (TCGen05Cluster2GEMM) TraceEvents ¶
func (k TCGen05Cluster2GEMM) TraceEvents() []layout.TraceEvent
TraceEvents returns the formal sm_100a/sm_103a tcgen05 hardware protocol event trace for verification with cudatmem.VerifyTrace.
type TCGen05DynSparseSwiGLU ¶
type TCGen05DynSparseSwiGLU struct {
Name string
M int // token rows; must be 128
I int // intermediate size (MMA K); 32, 64 or 128 (default 64)
N int // down_proj output features; 32, 64 or 128 and <= 2*I (default 64)
Target string // "sm_100a", "sm_103a", "sm_107a" or "sm_107f" (default "sm_107a")
}
TCGen05DynSparseSwiGLU configures a single-CTA kernel that fuses a SwiGLU epilogue, runtime 2:4 pruning of h = SiLU(gate) * up, and a 2:4 sparse down_proj tcgen05.mma.sp against an unmodified dense weight.
gate and up [M, I] are staged into TMEM with tcgen05.st (standing in for the gate_proj and up_proj accumulators), h is computed in registers and written back over the gate columns, and each 4-column group of h is pruned: on sm_107a the kernel issues tcgen05.ld.red.spcompress.sync.aligned.32x32b.x4.max.sp::2:4.abs.f32.b2, which also returns the running row absmax used for UE8M0 scaling; on other targets the selection runs in registers. The compressed operand and its metadata then feed tcgen05.mma.sp.cta_group::1.kind::tf32 with the dense down_proj weight [N, I] as operand B.
The device instruction paths are emitted for sm_100a, sm_103a and sm_107a and use a structural instruction descriptor and shared-memory descriptors; they have not been executed on tcgen05 hardware. When EG_EMU is defined (cudahostemu and sm_12x devices) the same kernel runs an exact C++ fallback, which is what the tests check against TCGen05DynSparseSwiGLU.Reference.
func (TCGen05DynSparseSwiGLU) CUDA ¶
func (k TCGen05DynSparseSwiGLU) CUDA() (string, error)
CUDA returns the kernel source without Prelude. The kernel signature is
NAME(const float* gate, const float* up, const float* w_down,
float* out_h_comp, uint32_t* out_meta, float* out_row_absmax, float* out)
with gate, up [M, I], w_down [N, I], out_h_comp [M, I/2], out_meta [M, I/32], out_row_absmax [M] and out [M, N].
func (TCGen05DynSparseSwiGLU) CUDAFile ¶
func (k TCGen05DynSparseSwiGLU) CUDAFile() (string, error)
CUDAFile returns the self-contained translation unit (Prelude plus CUDA).
func (TCGen05DynSparseSwiGLU) Grid ¶
func (k TCGen05DynSparseSwiGLU) Grid() (grid, block [3]int)
Grid returns the single-CTA grid and 128-thread block.
func (TCGen05DynSparseSwiGLU) InstDescriptor ¶
func (k TCGen05DynSparseSwiGLU) InstDescriptor() (uint32, error)
InstDescriptor returns the tcgen05.mma.sp kind::tf32 instruction descriptor with the 2:4 sparsity bit set.
func (TCGen05DynSparseSwiGLU) Reference ¶
func (k TCGen05DynSparseSwiGLU) Reference(gate, up, wDown []float32) (DynSparseSwiGLUResult, error)
Reference computes the kernel's outputs on the host.
func (TCGen05DynSparseSwiGLU) TraceEvents ¶
func (k TCGen05DynSparseSwiGLU) TraceEvents() []layout.TraceEvent
TraceEvents returns the tcgen05 event sequence of the kernel for cudatmem.VerifyTrace.
func (TCGen05DynSparseSwiGLU) Validate ¶
func (k TCGen05DynSparseSwiGLU) Validate() error
Validate reports whether k describes a supported kernel.
type TCGen05EarlyReleasePipelineGEMM ¶
type TCGen05EarlyReleasePipelineGEMM struct {
Name string
M, N, K int // M=128, N=128, K multiple of 64 (default 128)
Stages int // shared-memory pipeline stages (default 2)
ClusterCTAs int // CTAs in cluster in 1..32 (default 4)
Target string // "sm_107a" or "sm_107f" (defaults to "sm_107f")
}
TCGen05EarlyReleasePipelineGEMM configures a Rubin sm_107a/sm_107f multi-stage pipelined GEMM kernel that uses:
- tcgen05.commit.cta_group::1.mbarrier::arrive::one.sync_restrict::shared::read::mma::a.shared::cluster.b64 (PTX ISA 9.4 §9.7.18.10.12) to signal mbar_read_a as soon as operand A is read from shared memory so the next K-tile stage of A can be overwritten before the MMA finishes, and
- tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.multicast::cluster::32b.b64 with a 32-bit ctaMask for up to 32-CTA cluster completion.
func (TCGen05EarlyReleasePipelineGEMM) CUDA ¶
func (k TCGen05EarlyReleasePipelineGEMM) CUDA() (string, error)
CUDA emits the complete CUDA C++ source (without Prelude) for k.
func (TCGen05EarlyReleasePipelineGEMM) CUDAFile ¶
func (k TCGen05EarlyReleasePipelineGEMM) CUDAFile() (string, error)
CUDAFile emits the self-contained CUDA C++ translation unit (including Prelude) for k, ready for cudahostemu.Run or nvcc.
func (TCGen05EarlyReleasePipelineGEMM) Grid ¶
func (k TCGen05EarlyReleasePipelineGEMM) Grid() (grid, block [3]int)
Grid returns the single-CTA grid and 128-thread (4-warp) block dimensions.
type TCGen05GEMM ¶
type TCGen05GEMM struct {
Name string
N, K int
BM, BN int // e.g., BM=128, BN=128 or 256 (accumulators live in TMEM, not registers!)
BK int // reduction tile step (default 64)
Weight WeightFormat // WeightBF16, WeightE4M3, WeightNVFP4
Out cuda.DType
Epilogue TileEpilogue // TileLinear, TileSiLU, TileGLU
}
TCGen05GEMM configures a Blackwell sm_100a/sm_103a Tensor Memory (TMEM) GEMM kernel using tcgen05.alloc, tcgen05.mma.cta_group::1, tcgen05.ld, and tcgen05.dealloc.
func (TCGen05GEMM) CUDA ¶
func (g TCGen05GEMM) CUDA() (string, error)
CUDA returns the kernel source without Prelude.
func (TCGen05GEMM) Grid ¶
func (g TCGen05GEMM) Grid(m int) (grid, block [3]int)
Grid returns the launch grid and block dimensions for m activation rows.
func (TCGen05GEMM) Launcher ¶
func (g TCGen05GEMM) Launcher() (string, error)
Launcher returns the host launch wrapper for g.
func (TCGen05GEMM) Reference ¶
func (g TCGen05GEMM) Reference(m int, x []uint16, w GEMMWeights) ([]float32, error)
Reference computes the float64 reference output for WeightBF16 or WeightE4M3 with FP32 epilogue and Out rounding.
func (TCGen05GEMM) ReferenceNVFP4 ¶
func (g TCGen05GEMM) ReferenceNVFP4(m int, aFP4, aScale, bFP4, bScale []uint8) ([]float32, error)
ReferenceNVFP4 computes the float64 reference output for WeightNVFP4 with block-scaled E2M1 operands (aFP4 [m, K/2], aScale [m, K/16], bFP4 [N, K/2], bScale [N, K/16]), FP32 epilogue, and Out rounding.
func (TCGen05GEMM) SharedBytes ¶
func (g TCGen05GEMM) SharedBytes() int
SharedBytes returns the dynamic shared memory bytes per CTA needed by g.
type TCGen05KVSubspaceProject ¶
type TCGen05KVSubspaceProject struct {
Name string
Tokens int // rows per CTA; must be 128
Dim int // full KV width; a positive multiple of 32
Rank int // latent rank; 32, 64 or 128 (default 128)
Target string // "sm_100a", "sm_103a", "sm_107a" or "sm_107f" (default "sm_100a")
}
TCGen05KVSubspaceProject configures the background compressor's projection kernel: one CTA computes C = X U for a tile of Tokens KV rows X [Tokens, Dim] and a basis U [Dim, Rank], streaming Dim in 32-wide chunks through shared memory into a Rank-column TMEM accumulator with tcgen05.mma.cta_group::1.kind::tf32 and an mbarrier wait per chunk.
The device path is emitted for sm_100a, sm_103a and sm_107a and has not been executed on tcgen05 hardware. Under EG_EMU (cudahostemu and sm_12x devices) an exact C++ fallback runs instead and is what the tests check. Quantizing the latents and swapping page pointers stay on the host side (SubspaceKVProjector.CompressKVPage, KVCompressSchedule).
func (TCGen05KVSubspaceProject) CUDA ¶
func (k TCGen05KVSubspaceProject) CUDA() (string, error)
CUDA returns the kernel source without Prelude. The kernel signature is
NAME(const float* x, const float* basis, float* out)
with x [Tokens, Dim], basis [Dim, Rank] and out [Tokens, Rank].
func (TCGen05KVSubspaceProject) CUDAFile ¶
func (k TCGen05KVSubspaceProject) CUDAFile() (string, error)
CUDAFile returns the self-contained translation unit (Prelude plus CUDA).
func (TCGen05KVSubspaceProject) Grid ¶
func (k TCGen05KVSubspaceProject) Grid() (grid, block [3]int)
Grid returns the single-CTA grid and 128-thread block.
func (TCGen05KVSubspaceProject) Reference ¶
func (k TCGen05KVSubspaceProject) Reference(x, basis []float32) ([]float32, error)
Reference returns x [Tokens, Dim] times basis [Dim, Rank] accumulated in float32 in chunk order, as the EG_EMU fallback computes it.
func (TCGen05KVSubspaceProject) TraceEvents ¶
func (k TCGen05KVSubspaceProject) TraceEvents() []layout.TraceEvent
TraceEvents returns the tcgen05 event sequence of the kernel for cudatmem.VerifyTrace.
func (TCGen05KVSubspaceProject) Validate ¶
func (k TCGen05KVSubspaceProject) Validate() error
Validate reports whether k describes a supported kernel.
type TCGen05LUTDecompressGEMM ¶
type TCGen05LUTDecompressGEMM struct {
Name string
M, N, K int // M=128, N=128, K multiple of 64 in 64..256 (default 64)
Target string // "sm_107a" or "sm_107f" (defaults to "sm_107f")
CollectorA CollectorOp // optional .collector::a::<op> qualifier
CollectorB CollectorOp // .collector::b::<op> qualifier (defaults to CollectorFill)
}
TCGen05LUTDecompressGEMM configures a Rubin sm_107a/sm_107f Tensor Memory GEMM kernel that decompresses 3-bit indexed weights B on the fly via tcgen05.mma.cta_group::1.kind::mxf8f6f4.block_scale.decompress::lut::b.block32 and controls the operand B collector reuse buffer with .collector::b::<op> (PTX ISA 9.4 section 9.7.18.10.10.1 #7).
Example ¶
k := TCGen05LUTDecompressGEMM{
Name: "rubin_lut_b_gemm",
M: 128,
N: 128,
K: 64,
Target: "sm_107f",
CollectorB: CollectorFill,
}
src, err := k.CUDA()
fmt.Println(
err == nil,
strings.Contains(src, "tcgen05.mma.cta_group::1.kind::mxf8f6f4.block_scale.decompress::lut::b.block32.collector::b::fill"),
)
Output: true true
func (TCGen05LUTDecompressGEMM) CUDA ¶
func (k TCGen05LUTDecompressGEMM) CUDA() (string, error)
CUDA emits the complete CUDA C++ source (without Prelude) for k.
func (TCGen05LUTDecompressGEMM) CUDAFile ¶
func (k TCGen05LUTDecompressGEMM) CUDAFile() (string, error)
CUDAFile emits the self-contained CUDA C++ translation unit (including Prelude) for k, ready for cudahostemu.Run or nvcc.
func (TCGen05LUTDecompressGEMM) Grid ¶
func (k TCGen05LUTDecompressGEMM) Grid() (grid, block [3]int)
Grid returns the single-CTA grid and 128-thread (4-warp) block dimensions.
func (TCGen05LUTDecompressGEMM) InstDescriptor ¶
func (k TCGen05LUTDecompressGEMM) InstDescriptor() (uint32, error)
InstDescriptor returns the 32-bit tcgen05.mma instruction descriptor (idesc) for kind::mxf8f6f4.block_scale.decompress::lut::b.block32: E4M3 A, E4M3 B (the LUT entries), UE8M0 scales, dense K=32.
func (TCGen05LUTDecompressGEMM) Reference ¶
func (k TCGen05LUTDecompressGEMM) Reference(aE4M3, aScales, bIndices, bLUTE4M3, bScales []uint8) ([]float32, error)
Reference computes the host reference output C [M, N] for k given E4M3 activations aE4M3 [M, K], UE8M0 activation scales aScales [M, K/32], 3-bit weight indices bIndices [K, N], 8-entry E4M3 LUTs bLUTE4M3 [(N/8)*8], and UE8M0 weight scales bScales [N, K/32].
type TCGen05LdRed ¶
type TCGen05LdRed = TCGen05LdRedConfig
TCGen05LdRed models the PTX ISA 9.4 §9.7.18.8.3 Tensor Memory load with inline row reduction instruction:
tcgen05.ld.red.sync.aligned.32x32b.x4.<max|min>{.abs}{.NaN}.f32 {r0..r3}, redval, [taddr];
supported on sm_103a/sm_103f and sm_107a/sm_107f.
type TCGen05LdRedConfig ¶
type TCGen05LdRedConfig struct {
M int // rows in TMEM (defaults to 128, must be a positive multiple of 32)
N int // columns in TMEM (defaults to 128, must be a positive multiple of 32)
RedOp LdRedOp // inline reduction operator ("max" or "min", defaults to LdRedMax)
Abs bool // when true, reduces |x| via .abs qualifier
NaN bool // when true, propagates NaN via .NaN qualifier
Target string // "sm_103a", "sm_103f", "sm_107a", or "sm_107f" (defaults to "sm_107a")
}
TCGen05LdRedConfig configures a Blackwell Ultra (sm_103a/sm_103f) or Vera Rubin (sm_107a/sm_107f) Tensor Memory load-with-reduction kernel modeling tcgen05.ld.red.sync.aligned.32x32b.x4.<max|min>{.abs}{.NaN}.f32 (PTX ISA 9.4 section 9.7.18.8.3).
func (TCGen05LdRedConfig) CUDA ¶
func (k TCGen05LdRedConfig) CUDA() (string, error)
CUDA emits the complete CUDA C++ source (without Prelude) for k.
func (TCGen05LdRedConfig) CUDAFile ¶
func (k TCGen05LdRedConfig) CUDAFile() (string, error)
CUDAFile emits the self-contained CUDA C++ translation unit (including Prelude) for k, ready for cudahostemu.Run or nvcc.
func (TCGen05LdRedConfig) Grid ¶
func (k TCGen05LdRedConfig) Grid() (grid, block [3]int)
Grid returns the single-CTA grid and 128-thread (4-warp) block dimensions.
func (TCGen05LdRedConfig) Reference ¶
func (k TCGen05LdRedConfig) Reference(in []float32) (data []float32, rowRed []float32, err error)
Reference computes the exact host reference for k given row-major input in [M, N], returning a copy of in (data [M*N]) and the per-row reduction rowRed [M].
func (TCGen05LdRedConfig) Validate ¶
func (k TCGen05LdRedConfig) Validate() error
Validate checks that k has valid matrix dimensions, reduction operator, and PTX target architecture.
type TCGen05LdSpCompress ¶
type TCGen05LdSpCompress struct {
M int // rows in TMEM (defaults to 128, must be in 1..128)
N int // columns in TMEM (defaults to 128, must be a positive multiple of 4)
RedOp LdRedOp // "max" or "min" selector for 2:4 pruning and reduction (defaults to LdRedMax)
Abs bool // when true, prunes and reduces by magnitude |x| via .abs
WithReduction bool // when true, emits tcgen05.ld.red.spcompress with inline redval output
Target string // "sm_107a" or "sm_107f" (defaults to "sm_107a")
}
TCGen05LdSpCompress models the PTX ISA 9.4 §9.7.18.8.3 Vera Rubin (sm_107a/sm_107f) Tensor Memory load with hardware 2:4 structured sparsity compression and optional inline reduction:
tcgen05.ld{.red}.spcompress.sync.aligned.32x32b.x4.<max|min>.sp::2:4{.abs}.f32.b2
{mdata}, {c0, c1}, {redval,} [taddr];
For each group of 4 consecutive FP32 elements along N, it selects the 2 elements with the largest (LdRedMax) or smallest (LdRedMin) value or magnitude (when Abs is true), breaking ties deterministically by smaller column index (0 < 1 < 2 < 3), orders the selected indices as 0 <= idx0 < idx1 <= 3, writes the 4-bit metadata nibble idx0 | (idx1 << 2) into packed uint32 metadata words (8 groups = 32 columns per uint32 word), writes the two selected FP32 values to cdata [M, N/2], and computes the per-row reduction rowRed [M].
Example ¶
sp := TCGen05LdSpCompress{
M: 1,
N: 8,
RedOp: LdRedMax,
Abs: true,
WithReduction: true,
Target: "sm_107a",
}
in := []float32{
1.0, -4.0, 2.5, -0.5, // group 0: top-2 |x| at indices 1 (-4.0) and 2 (2.5)
-6.0, 1.5, -1.0, 3.0, // group 1: top-2 |x| at indices 0 (-6.0) and 3 (3.0)
}
cdata, mdata, rowRed, err := sp.Reference(in)
dense, _ := DecompressReference(cdata, mdata, 1, 8)
src, _ := sp.CUDA()
fmt.Printf("err=%v cdata=%v mdata=0x%02x rowRed=%.1f dense=%v has_ptx=%v\n",
err,
cdata,
mdata[0],
rowRed[0],
dense,
strings.Contains(src, "tcgen05.ld.red.spcompress.sync.aligned.32x32b.x4.max.sp::2:4.abs.f32.b2"),
)
Output: err=<nil> cdata=[-4 2.5 -6 3] mdata=0xc9 rowRed=6.0 dense=[0 -4 2.5 0 -6 0 0 3] has_ptx=true
func (TCGen05LdSpCompress) CUDA ¶
func (k TCGen05LdSpCompress) CUDA() (string, error)
CUDA emits the complete CUDA C++ source (without Prelude) for k.
func (TCGen05LdSpCompress) CUDAFile ¶
func (k TCGen05LdSpCompress) CUDAFile() (string, error)
CUDAFile emits the self-contained CUDA C++ translation unit (including Prelude) for k, ready for cudahostemu.Run or nvcc.
func (TCGen05LdSpCompress) DecompressReference ¶
func (k TCGen05LdSpCompress) DecompressReference(cdata []float32, mdata []uint32, M, N int) ([]float32, error)
DecompressReference is a method alias for DecompressReference using k's configured M and N dimensions when M or N are omitted.
func (TCGen05LdSpCompress) Grid ¶
func (k TCGen05LdSpCompress) Grid() (grid, block [3]int)
Grid returns the single-CTA grid and 128-thread (4-warp) block dimensions.
func (TCGen05LdSpCompress) MetadataWordsPerRow ¶
func (k TCGen05LdSpCompress) MetadataWordsPerRow() int
MetadataWordsPerRow returns the number of packed uint32 metadata words per row: ceil(N / 32), where each uint32 word holds up to 8 groups of 4-bit (2x2-bit .b2) indices.
func (TCGen05LdSpCompress) Reference ¶
func (k TCGen05LdSpCompress) Reference(in []float32) (cdata []float32, mdata []uint32, rowRed []float32, err error)
Reference computes the exact host reference for k given row-major input in [M, N], returning:
- cdata: [M * (N/2)] compressed non-zero float32 values (2 per 4-element group),
- mdata: [M * ceil(N/32)] packed uint32 metadata words (4 bits = idx0 | (idx1<<2) per 4-element group),
- rowRed: [M] per-row reduction across all N columns.
func (TCGen05LdSpCompress) Validate ¶
func (k TCGen05LdSpCompress) Validate() error
Validate checks that k has valid dimensions, reduction operator, and Rubin sm_107a/sm_107f target.
type TCGen05MLAPagedAttention ¶
type TCGen05MLAPagedAttention struct {
Name string
NumHeads int
KVLoRARank int
RoPEDim int
VHeadDim int
PageSize int
MaxPages int
SeqLen int
Scale float32
Target string // "sm_100a", "sm_103a", "sm_100f", "sm_103f" (defaults to "sm_100a")
CTAGroup int // 1 or 2
PingPong bool
}
TCGen05MLAPagedAttention configures a Blackwell Multi-head Latent Attention (MLA) kernel with matrix absorption over a paged compressed KV cache (C_KV and decoupled K_rope) using tcgen05 TMEM accumulators and TMEM-resident operand A (O_latent = P * C_KV).
Example ¶
mla := TCGen05MLAPagedAttention{
Name: "fa4_mla_paged",
NumHeads: 4,
KVLoRARank: 16,
RoPEDim: 8,
VHeadDim: 16,
PageSize: 16,
MaxPages: 8,
SeqLen: 32,
Target: "sm_103a",
CTAGroup: 1,
PingPong: true,
}
sum, err := layout.VerifyTrace(layout.SM103A, mla.TMEMTrace())
fmt.Printf("err=%v ctas=%d group=%d mmas=%d grid=%v block=%v\n",
err, sum.CTAs, sum.CTAGroup, sum.MMAs, mla.Grid(), mla.Block())
Output: err=<nil> ctas=1 group=1 mmas=6 grid=[1 1 1] block=[288 1 1]
func (TCGen05MLAPagedAttention) Block ¶
func (k TCGen05MLAPagedAttention) Block() [3]int
Block returns the CTA thread-block dimensions for k.
func (TCGen05MLAPagedAttention) CUDA ¶
func (k TCGen05MLAPagedAttention) CUDA() string
CUDA emits the complete CUDA C++ device source for absorbed MLA on Blackwell tcgen05.
func (TCGen05MLAPagedAttention) Check ¶
func (k TCGen05MLAPagedAttention) Check() error
Check reports whether the kernel supports k, taking a zero field's default as the other methods do: instruction descriptors that encode the page and the latent rank, and shared memory within the 227 KiB opt-in limit. A latent rank of 512, DeepSeek's, does not encode as one O = P·C_KV descriptor. Source returns a kernel that does not compile, or cannot launch, for a k that Check refuses.
func (TCGen05MLAPagedAttention) Grid ¶
func (k TCGen05MLAPagedAttention) Grid() [3]int
Grid returns the launch grid dimensions for k.
func (TCGen05MLAPagedAttention) Launcher ¶
func (k TCGen05MLAPagedAttention) Launcher() string
Launcher returns the C++ host launcher function for k.
func (TCGen05MLAPagedAttention) Reference ¶
func (k TCGen05MLAPagedAttention) Reference(qAbsorbed, qRope, cKVPages, kRopePages []float32, pageTable []int32, seqLen int) []float32
Reference computes the exact float64 multi-page absorbed Multi-head Latent Attention reference output O_latent [NumHeads, KVLoRARank].
func (TCGen05MLAPagedAttention) SharedBytes ¶
func (k TCGen05MLAPagedAttention) SharedBytes() int
SharedBytes returns the shared-memory footprint in bytes per CTA.
func (TCGen05MLAPagedAttention) Source ¶
func (k TCGen05MLAPagedAttention) Source() string
Source returns the complete runnable/emulatable CUDA C++ translation unit (including device prelude, kernel, and host launcher) for k.
func (TCGen05MLAPagedAttention) TMEMTrace ¶
func (k TCGen05MLAPagedAttention) TMEMTrace() []layout.TraceEvent
TMEMTrace builds the multi-page tcgen05 TMEM hardware lifecycle trace for absorbed MLA: Alloc -> { MMA S_absorbed -> MMA S_rope -> Commit -> Wait -> Load S -> Store P -> MMA O_latent -> Commit -> Wait }* -> Load O_latent -> Dealloc.
func (TCGen05MLAPagedAttention) TraceEvents ¶
func (k TCGen05MLAPagedAttention) TraceEvents() []layout.TraceEvent
TraceEvents is an alias for TCGen05MLAPagedAttention.TMEMTrace.
type TCGen05MXFP8GEMM ¶
type TCGen05MXFP8GEMM struct {
Name string
M, N, K int // M=128, N=128, K multiple of 32 in 32..256 (default 64)
MixedW4A8 bool // when false: pure MXFP8 (E4M3 x E4M3); when true: W4A8 (MXFP8 E4M3 x MXFP4 E2M1)
UseShiftDown bool // when true: emits tcgen05.shift.cta_group::1.down on TMEM accumulator tile
}
TCGen05MXFP8GEMM emits a Blackwell sm_100a/sm_103a OCP microscaling GEMM using tcgen05.cp.cta_group::1.32x128b.warpx4 to stage 32-element UE8M0 block scales into TMEM and tcgen05.mma.cta_group::1.kind::mxf8f6f4.block_scale.scale_vec::1X for either pure MXFP8 (E4M3 x E4M3) or mixed W4A8 (MXFP8 E4M3 activations x MXFP4 E2M1 weights), with optional tcgen05.shift.cta_group::1.down TMEM row shifting.
Example ¶
k := TCGen05MXFP8GEMM{
Name: "blackwell_w4a8_shift_gemm",
M: 128,
N: 128,
K: 64,
MixedW4A8: true,
UseShiftDown: true,
}
idesc, _ := k.InstDescriptor()
dec, _ := DecodeInstDesc(KindMXF8F6F4, idesc)
sum, err := layout.VerifyTrace(layout.SM100A, k.TraceEvents())
src, _ := k.CUDA()
fmt.Printf("0x%08x\n", idesc)
fmt.Println(
err == nil,
dec.AType,
dec.BType,
dec.ScaleType,
sum.MMAs,
sum.Shifts,
strings.Contains(src, "tcgen05.mma.cta_group::1.kind::mxf8f6f4.block_scale.scale_vec::1X"),
strings.Contains(src, "tcgen05.shift.cta_group::1.down"),
)
Output: 0x08a01400 true e4m3 e2m1 ue8m0 1 1 true true
func (TCGen05MXFP8GEMM) CUDA ¶
func (k TCGen05MXFP8GEMM) CUDA() (string, error)
CUDA emits the complete CUDA C++ source (without Prelude) for k.
func (TCGen05MXFP8GEMM) CUDAFile ¶
func (k TCGen05MXFP8GEMM) CUDAFile() (string, error)
CUDAFile emits the self-contained CUDA C++ translation unit (including Prelude) for k, ready for cudahostemu.Run or nvcc.
func (TCGen05MXFP8GEMM) Grid ¶
func (k TCGen05MXFP8GEMM) Grid() (grid, block [3]int)
Grid returns the single-CTA grid and 128-thread (4-warp) block dimensions.
func (TCGen05MXFP8GEMM) InstDescriptor ¶
func (k TCGen05MXFP8GEMM) InstDescriptor() (uint32, error)
InstDescriptor returns the 32-bit tcgen05.mma instruction descriptor (idesc) for kind::mxf8f6f4.block_scale.scale_vec::1X: E4M3 A, E4M3 or (MixedW4A8) E2M1 B, UE8M0 scales, dense K=32.
func (TCGen05MXFP8GEMM) Reference ¶
func (k TCGen05MXFP8GEMM) Reference(aData, aScales, bData, bScales []uint8) ([]float32, error)
Reference computes the host reference output [M, N] for k given E4M3 activations aData [M, K] with UE8M0 scales aScales [M, K/32] and weights bData ([N, K] E4M3 when MixedW4A8 is false, or [N, K/2] packed E2M1 when MixedW4A8 is true) with UE8M0 scales bScales [N, K/32].
func (TCGen05MXFP8GEMM) TraceEvents ¶
func (k TCGen05MXFP8GEMM) TraceEvents() []layout.TraceEvent
TraceEvents returns the formal sm_100a/sm_103a tcgen05 hardware protocol event trace for verification with cudatmem.VerifyTrace.
type TCGen05PagedAttention ¶
type TCGen05PagedAttention struct {
Name string
NumQHeads int
NumKVHeads int
HeadDim int
PageSize int
MaxPages int
SeqLen int
Scale float32
Target string // "sm_100a", "sm_103a", "sm_100f", "sm_103f" (defaults to "sm_100a")
CTAGroup int // 1 for cta_group::1 (M=128) or 2 for cta_group::2 (M=256)
PingPong bool // 2 consumer warpgroups alternating MMA and SFU exp2 with TMA producer warp
KVFormat WeightFormat // WeightBF16, WeightFP8E4M3, or WeightNVFP4
}
TCGen05PagedAttention configures a multi-page Blackwell FlashAttention-4 grouped-query attention (GQA) kernel over a paged KV cache using Tensor Memory (TMEM) accumulators, in-place TMEM online softmax rescaling, and TMEM-resident operand A (P * V) tcgen05.mma instructions.
Example ¶
attn := TCGen05PagedAttention{
Name: "fa4_paged_gqa",
NumQHeads: 4,
NumKVHeads: 2,
HeadDim: 64,
PageSize: 16,
MaxPages: 8,
SeqLen: 32,
Target: "sm_103a",
CTAGroup: 2,
PingPong: true,
KVFormat: WeightNVFP4,
}
sum, err := layout.VerifyTrace(layout.SM103A, attn.TMEMTrace())
fmt.Printf("err=%v ctas=%d group=%d mmas=%d copies=%d has_scale_vec_4x=%v\n",
err, sum.CTAs, sum.CTAGroup, sum.MMAs, sum.Copies,
strings.Contains(attn.CUDA(), "scale_vec::4X"))
Output: err=<nil> ctas=2 group=2 mmas=4 copies=4 has_scale_vec_4x=true
func (TCGen05PagedAttention) Block ¶
func (k TCGen05PagedAttention) Block() [3]int
Block returns the CTA thread-block dimensions for k. When PingPong is true, 288 threads (2 consumer warpgroups of 128 threads + 1 dedicated 32-thread TMA producer warp) are launched; otherwise 128 threads.
func (TCGen05PagedAttention) CUDA ¶
func (k TCGen05PagedAttention) CUDA() string
CUDA emits the complete CUDA C++ device source for k.
func (TCGen05PagedAttention) Check ¶
func (k TCGen05PagedAttention) Check() error
Check reports whether the kernel supports k, taking a zero field's default as the other methods do: query heads a multiple of KV heads, instruction descriptors that encode the page and head dim, and shared memory within the 227 KiB opt-in limit. It checks the fields as given, with only zero fields defaulted, so a field the other methods would replace (a negative count, KV heads that do not divide the query heads, an unknown target, CTA group or KV format) is refused, not replaced. Source returns a kernel that does not compile, or cannot launch, for a k that Check refuses.
func (TCGen05PagedAttention) Grid ¶
func (k TCGen05PagedAttention) Grid() [3]int
Grid returns the launch grid dimensions for k.
func (TCGen05PagedAttention) Launcher ¶
func (k TCGen05PagedAttention) Launcher() string
Launcher returns the C++ host launcher function for k.
func (TCGen05PagedAttention) Reference ¶
func (k TCGen05PagedAttention) Reference(q []float32, kPages, vPages []float32, pageTable []int32, seqLen int) []float32
Reference computes the exact float64 multi-page grouped-query online-softmax attention reference over kPages and vPages indexed by pageTable.
func (TCGen05PagedAttention) SharedBytes ¶
func (k TCGen05PagedAttention) SharedBytes() int
SharedBytes returns the dynamic shared memory, in bytes, that k declares and its launcher requests. The kernel declares no static shared memory of its own on the device.
func (TCGen05PagedAttention) Source ¶
func (k TCGen05PagedAttention) Source() string
Source returns the complete runnable/emulatable CUDA C++ translation unit (including device prelude, kernel, and host launcher) for k.
func (TCGen05PagedAttention) TMEMTrace ¶
func (k TCGen05PagedAttention) TMEMTrace() []layout.TraceEvent
TMEMTrace builds the multi-page tcgen05 TMEM hardware lifecycle trace: Alloc -> { (Cp ->) MMA S -> Commit -> Wait -> Load S -> Store P -> MMA O -> Commit -> Wait }* -> Load O -> Dealloc.
func (TCGen05PagedAttention) TraceEvents ¶
func (k TCGen05PagedAttention) TraceEvents() []layout.TraceEvent
TraceEvents is an alias for TCGen05PagedAttention.TMEMTrace.
type TCGen05ScaleVec4XGEMM ¶
type TCGen05ScaleVec4XGEMM struct {
Name string
M int // defaults to 128 (must be 128)
N int // defaults to 128 (must be 128)
K int // defaults to 128 (must be 64, 128, 192, or 256)
}
TCGen05ScaleVec4XGEMM emits a Blackwell Ultra sm_103a NVFP4 block-scaled GEMM using tcgen05.mma.cta_group::1.kind::mxf4nvf4.block_scale.scale_vec::4X (K = 64 FP4 elements per MMA instruction, 4 UE4M3 scale factors per row per instruction, staged into TMEM via tcgen05.cp.cta_group::1.32x128b; a K = 128 tile issues two instructions).
func (TCGen05ScaleVec4XGEMM) CUDA ¶
func (k TCGen05ScaleVec4XGEMM) CUDA() (string, error)
CUDA emits the complete CUDA C++ source (without Prelude) for k.
func (TCGen05ScaleVec4XGEMM) CUDAFile ¶
func (k TCGen05ScaleVec4XGEMM) CUDAFile() (string, error)
CUDAFile emits the self-contained CUDA C++ translation unit (including Prelude) for k, ready for cudahostemu.Run or nvcc.
func (TCGen05ScaleVec4XGEMM) Grid ¶
func (k TCGen05ScaleVec4XGEMM) Grid() (grid, block [3]int)
Grid returns the single-CTA grid and 128-thread (4-warp) block dimensions.
func (TCGen05ScaleVec4XGEMM) TraceEvents ¶
func (k TCGen05ScaleVec4XGEMM) TraceEvents() []layout.TraceEvent
TraceEvents returns the formal sm_103a tcgen05 hardware protocol event trace for verification with cudatmem.VerifyTrace(cudatmem.SM103A, ...).
type TCGen05SparseGEMM ¶
type TCGen05SparseGEMM struct {
Name string
M, N, K int // M=128, N=128, K multiple of 64 in 64..256
Target string // "sm_100a" or "sm_103a" (defaults to "sm_100a")
CTAGroup int // 1 or 2 (defaults to 1)
BlockScaledNVFP4 bool // when true, emits kind::mxf4nvf4.block_scale (or .scale_vec::4X on sm_103a)
}
TCGen05SparseGEMM emits a Blackwell sm_100a/sm_103a 2:4 structured sparse Tensor Memory (TMEM) GEMM kernel using tcgen05.mma.sp.
Example ¶
k := TCGen05SparseGEMM{
Name: "blackwell_sparse_gemm",
M: 128,
N: 128,
K: 64,
Target: "sm_103a",
CTAGroup: 1,
BlockScaledNVFP4: true,
}
idesc, _ := k.InstDescriptor()
dec, _ := DecodeInstDesc(KindMXF4NVF4, idesc)
sum, err := layout.VerifyTrace(layout.SM103A, k.TraceEvents())
src, _ := k.CUDA()
fmt.Printf("0x%08x\n", idesc)
fmt.Println(
err == nil,
dec.Sparse,
dec.ScaleType,
sum.MMAs,
sum.MaxAllocatedColumns,
strings.Contains(src, "tcgen05.mma.sp.cta_group::1.kind::mxf4nvf4.block_scale.scale_vec::4X"),
)
Output: 0x08200484 true true ue4m3 1 160 true
func (TCGen05SparseGEMM) CUDA ¶
func (k TCGen05SparseGEMM) CUDA() (string, error)
CUDA emits the complete CUDA C++ source (without Prelude) for k.
func (TCGen05SparseGEMM) CUDAFile ¶
func (k TCGen05SparseGEMM) CUDAFile() (string, error)
CUDAFile emits the self-contained CUDA C++ translation unit (including Prelude) for k, ready for cudahostemu.Run or nvcc.
func (TCGen05SparseGEMM) Grid ¶
func (k TCGen05SparseGEMM) Grid() (grid, block [3]int)
Grid returns the launch grid and 128-thread (4-warp) block dimensions.
func (TCGen05SparseGEMM) InstDescriptor ¶
func (k TCGen05SparseGEMM) InstDescriptor() (uint32, error)
InstDescriptor returns the 32-bit tcgen05.mma.sp instruction descriptor (idesc) for the kind k emits: .kind::tf32 (TF32 x TF32 -> F32, K=16) or, with BlockScaledNVFP4, .kind::mxf4nvf4 (E2M1 x E2M1, UE4M3 scales, K=128) with the target's sparsity version (v0 on sm_100/sm_103, v1 on sm_107).
func (TCGen05SparseGEMM) Launcher ¶
func (k TCGen05SparseGEMM) Launcher() (string, error)
Launcher returns the host launcher of k, which requests SharedBytes of dynamic shared memory.
func (TCGen05SparseGEMM) Reference ¶
func (k TCGen05SparseGEMM) Reference(aCompressed []float32, aMeta []uint32, b []float32) ([]float32, error)
Reference computes the 2:4 metadata-indexed sparse matrix product C[M, N] = A_sparse[M, K] * B[K, N] from compressed values aCompressed [M, K/2], packed 2-bit index metadata aMeta [M, K/32], and dense B [K, N].
func (TCGen05SparseGEMM) SharedBytes ¶
func (k TCGen05SparseGEMM) SharedBytes() int
SharedBytes returns the dynamic shared memory, in bytes, that k declares and its launcher requests, or 0 if k is invalid.
func (TCGen05SparseGEMM) TraceEvents ¶
func (k TCGen05SparseGEMM) TraceEvents() []layout.TraceEvent
TraceEvents returns the formal sm_100a/sm_103a tcgen05 hardware protocol event trace for verification with cudatmem.VerifyTrace.
type TCGen05TMAMulticastGatherGEMM ¶
type TCGen05TMAMulticastGatherGEMM struct {
Name string
M int // total gathered token rows across the 2-CTA cluster; defaults to 256 (128 per CTA)
N int // output columns; defaults to 128 (must be 128)
K int // reduction dimension; defaults to 32 (positive multiple of 16)
Target string // PTX target ("sm_100a", "sm_103a", or "sm_100f"; defaults to "sm_100a")
ScatterOutput bool // when true, stages epilogue rows in shared memory and stores via TMA .scatter4
}
TCGen05TMAMulticastGatherGEMM emits a 2-CTA (__cluster_dims__(2, 1, 1), cta_group::2) Blackwell sm_100a/sm_103a routed GEMM kernel that:
- gathers non-contiguous token rows from global memory into each CTA's shared memory in 4-row batches via TMA .gather4 with an L2::evict_first cache hint,
- multicasts the shared weight tile B from CTA 0 into both CTAs' shared memory simultaneously via TMA .multicast::cluster (cta_mask = 0x3) with an L2::evict_last residency hint,
- issues a cooperative 2-CTA tcgen05.mma.cta_group::2.kind::tf32 and tcgen05.commit.cta_group::2 from CTA 0's elected leader thread, and
- reads each CTA's 128-row TMEM partition via 4-warp 32-row partitioned tcgen05.ld (and optionally stores the output rows in 4-row batches via TMA .scatter4 when ScatterOutput is true).
Example ¶
k := TCGen05TMAMulticastGatherGEMM{
Name: "routed_expert_gemm",
M: 256,
N: 128,
K: 32,
Target: "sm_100a",
}
grid, block := k.Grid()
sum, _ := layout.VerifyTrace(layout.SM100A, k.TraceEvents())
src, _ := k.CUDA()
fmt.Printf("grid=%v block=%v cta_group=%d mmas=%d loads=%d\n",
grid, block, sum.CTAGroup, sum.MMAs, sum.Loads)
fmt.Printf("has_gather4=%v has_multicast=%v has_evict_last=%v\n",
strings.Contains(src, ".tile::gather4."),
strings.Contains(src, ".multicast::cluster."),
strings.Contains(src, "createpolicy.fractional.L2::evict_last"))
Output: grid=[2 1 1] block=[128 1 1] cta_group=2 mmas=1 loads=8 has_gather4=true has_multicast=true has_evict_last=true
func (TCGen05TMAMulticastGatherGEMM) CUDA ¶
func (k TCGen05TMAMulticastGatherGEMM) CUDA() (string, error)
CUDA emits the complete CUDA C++ source (without Prelude) for k.
func (TCGen05TMAMulticastGatherGEMM) CUDAFile ¶
func (k TCGen05TMAMulticastGatherGEMM) CUDAFile() (string, error)
CUDAFile emits the self-contained CUDA C++ translation unit (including Prelude) for k, ready for cudahostemu.Run or nvcc.
func (TCGen05TMAMulticastGatherGEMM) Grid ¶
func (k TCGen05TMAMulticastGatherGEMM) Grid() (grid, block [3]int)
Grid returns the 2-CTA cluster grid and 128-thread (4-warp) block dimensions.
func (TCGen05TMAMulticastGatherGEMM) Reference ¶
func (k TCGen05TMAMulticastGatherGEMM) Reference(aGlobal []float32, totalGlobalRows int, gatherRows []int32, b []float32) ([]float32, error)
Reference computes the host reference output [M, N] for the routed gather4 + multicast GEMM. Only the rows of aGlobal indexed by gatherRows are accessed, so ungathered rows in aGlobal (even if poisoned with NaN) are never read.
func (TCGen05TMAMulticastGatherGEMM) TraceEvents ¶
func (k TCGen05TMAMulticastGatherGEMM) TraceEvents() []layout.TraceEvent
TraceEvents returns the formal sm_100a/sm_103a 2-CTA (cta_group::2) tcgen05 hardware protocol event trace for verification with cudatmem.VerifyTrace.
type TCGen05TMEMFlashAttention ¶
type TCGen05TMEMFlashAttention struct {
Name string
M int // query rows; defaults to 128 (must be 128)
KV int // key/value rows; defaults to 64 (must be 64)
D int // head dimension; defaults to 64 (must be 64)
Scale float32 // softmax logit scale; defaults to 1/sqrt(D)
}
TCGen05TMEMFlashAttention emits an sm_100a/sm_103a fused attention kernel where S = Q * K^T is accumulated into TMEM [tmem_s], rescaled in-place in TMEM (P = softmax(S * Scale)) using 4-warp 32-row partitioned tcgen05.ld / tcgen05.st, and O = P * V is issued via tcgen05.mma with operand A (P) read directly from TMEM ([tmem_o], [tmem_p], desc_v) without spilling P to shared memory.
func (TCGen05TMEMFlashAttention) CUDA ¶
func (k TCGen05TMEMFlashAttention) CUDA() (string, error)
CUDA emits the complete CUDA C++ source (without Prelude) for k.
func (TCGen05TMEMFlashAttention) Grid ¶
func (k TCGen05TMEMFlashAttention) Grid() (grid, block [3]int)
Grid returns the single-CTA grid and 128-thread (4-warp) block dimensions.
func (TCGen05TMEMFlashAttention) Launcher ¶
func (k TCGen05TMEMFlashAttention) Launcher() (string, error)
Launcher returns the host launcher of k, which requests SharedBytes of dynamic shared memory.
func (TCGen05TMEMFlashAttention) SharedBytes ¶
func (k TCGen05TMEMFlashAttention) SharedBytes() int
SharedBytes returns the dynamic shared memory, in bytes, that k declares and its launcher requests, or 0 if k is invalid.
func (TCGen05TMEMFlashAttention) TraceEvents ¶
func (k TCGen05TMEMFlashAttention) TraceEvents() []layout.TraceEvent
TraceEvents returns the formal sm_100a/sm_103a tcgen05 hardware protocol event trace for verification with cudatmem.VerifyTrace.
type TCGen05WeightsStationaryGEMM ¶
type TCGen05WeightsStationaryGEMM struct {
Name string
M, N, K int
CollectorBuffer WSCollectorBuffer
CollectorAction WSCollectorAction
Kind string
UseExclusive576Cols bool
ZeroColumnMask ZeroColumnMaskDesc
Sparse bool // not supported: no sparsity metadata is staged in TMEM
Target string
}
TCGen05WeightsStationaryGEMM configures a weights-stationary Tensor Memory GEMM kernel using tcgen05.mma.ws{.sp} (PTX ISA 9.4 §9.7.18.10.10.3–4), optional exclusive TMEM allocation (tcgen05.alloc.exclusive.cta_group::1, §9.7.18.7.1: 576 columns on sm_107, 512 on sm_100/sm_103), and a 64-bit ZeroColumnMaskDesc (§9.7.18.4.3).
Example ¶
zmask := ZeroColumnMaskDesc{
StartCount: [8]uint8{2, 0, 0, 0, 0, 0, 0, 0},
SkipSpan: [8]uint8{1, 0, 0, 0, 0, 0, 0, 0},
NonZeroMask: 0x01,
}
k := TCGen05WeightsStationaryGEMM{
M: 128,
N: 128,
K: 64,
CollectorBuffer: WSCollectorB2,
CollectorAction: WSActionUse,
Kind: "ti16",
UseExclusive576Cols: true,
ZeroColumnMask: zmask,
Target: "sm_107a",
}
src, err := k.CUDA()
fmt.Println(
err == nil,
zmask.IsColumnZeroed(1),
zmask.IsColumnZeroed(2),
strings.Contains(src, "tcgen05.alloc.exclusive.cta_group::1"),
strings.Contains(src, "tcgen05.mma.ws.cta_group::1.kind::ti16.collector::b2::use"),
)
Output: true false true true true
func (TCGen05WeightsStationaryGEMM) CUDA ¶
func (k TCGen05WeightsStationaryGEMM) CUDA() (string, error)
CUDA emits the complete CUDA C++ source (without Prelude) for k.
func (TCGen05WeightsStationaryGEMM) CUDAFile ¶
func (k TCGen05WeightsStationaryGEMM) CUDAFile() (string, error)
CUDAFile emits the self-contained CUDA C++ translation unit (including Prelude) for k, ready for cudahostemu.Run or nvcc.
func (TCGen05WeightsStationaryGEMM) Grid ¶
func (k TCGen05WeightsStationaryGEMM) Grid() (grid, block [3]int)
Grid returns the single-CTA grid and 128-thread (4-warp) block dimensions.
func (TCGen05WeightsStationaryGEMM) InstDescriptor ¶
func (k TCGen05WeightsStationaryGEMM) InstDescriptor() (uint32, error)
InstDescriptor returns the 32-bit tcgen05.mma.ws instruction descriptor (idesc) for k.Kind: TF32, BF16, E4M3, S8, or S1Z4M11 inputs with an F32 (S32 for i8 and ti16) accumulator, M=128, N=k.N, and the kind's dense K.
func (TCGen05WeightsStationaryGEMM) Reference ¶
func (k TCGen05WeightsStationaryGEMM) Reference(a, b []float32) ([]float32, error)
Reference computes C[m, n] = sum_k A_masked[m, k] * B[k, n] where A_masked[m, k] = 0 when k.ZeroColumnMask.IsColumnZeroed(k) is true.
func (TCGen05WeightsStationaryGEMM) Validate ¶
func (k TCGen05WeightsStationaryGEMM) Validate() error
Validate checks that k has valid dimensions, collector qualifiers, kind, and target.
type TMEMAddr ¶
TMEMAddr represents a 32-bit Tensor Memory address composed of a 16-bit lane row index in the upper half and a 16-bit column offset in the lower half.
func DecodeTMEMAddr ¶
DecodeTMEMAddr unpacks a 32-bit TMEM address word into its (Row, Col) pair.
type TMEMBufferReq ¶
type TMEMBufferReq struct {
Name string
WidthCols uint16 // 32, 64, 128, 256 or 512
DoubleBuf bool // two disjoint buffers, for overlap
}
A TMEMBufferReq asks for a TMEM buffer.
type TMEMCrossLayerSpec ¶
type TMEMCrossLayerSpec struct {
// Name is the megakernel plan identifier (defaults to "blackwell_tmem_crosslayer_mega").
Name string
// Target is the Blackwell architecture target ("sm_100a", "sm_103a",
// "sm_120a", or "sm_121a"; defaults to "sm_100a").
Target string
// NumLayers is the number of decoder layers fused in the plan (defaults to 2).
NumLayers int
// Tokens is the token batch row count M (defaults to 128; when NegativeTokens
// or < 0, rejected by validation).
Tokens int
// HiddenDim is the model hidden dimension H (defaults to 256).
HiddenDim int
// IntermediateDim is the FFN SwiGLU intermediate dimension I (defaults to 256).
IntermediateDim int
// QDim is the query projection dimension (defaults to HiddenDim).
QDim int
// KVDim is the key/value projection dimension (defaults to HiddenDim/4, min 64).
KVDim int
// ClusterSize is the cooperative CTA cluster size (1 or 2; defaults to 2 on
// sm_100a/sm_103a and 1 on sm_120a/sm_121a).
ClusterSize int
// GateCols is the TMEM column allocation for gate_proj accumulators (defaults to 128).
GateCols int
// UpCols is the TMEM column allocation for up_proj accumulators (defaults to 128).
UpCols int
// QKVCols is the TMEM column allocation for next-layer qkv_proj accumulators (defaults to 256).
QKVCols int
// WeightFormat selects the weight encoding ("nvfp4", "bf16", or "e4m3"; defaults to "nvfp4").
WeightFormat string
// OmitLayerExitDealloc disables the guarded tcgen05.dealloc at layer exit
// (used to test lifecycle verification of unbalanced TMEM allocations).
OmitLayerExitDealloc bool
}
TMEMCrossLayerSpec configures a Blackwell persistent cross-layer megakernel where intermediate GEMM accumulators (gate_proj, up_proj, qkv_proj) remain resident in Blackwell Tensor Memory (TMEM, 256 KB/SM via tcgen05.alloc, tcgen05.ld, tcgen05.st, and tcgen05.mma.cta_group::2) across fused epilogue stages (SwiGLU, RMSNorm) before committing to SMEM/GMEM, with tcgen05.dealloc guarded at layer exit.
type TMEMMegakernelPlan ¶
type TMEMMegakernelPlan struct {
Spec TMEMCrossLayerSpec
Name string
Target string
ClusterSize int
UsesNativeTMEM bool
TotalTMEMCols int
TotalTMEMBytes int
AllocCount int
DeallocCount int
Stages []TMEMStage
Trace []layout.TraceEvent
}
TMEMMegakernelPlan holds the validated stage schedule, TMEM column map, formal cudatmem hardware trace, and Hopper megakernel lowering for a Blackwell TMEM-resident cross-layer megakernel.
func BuildTMEMCrossLayerMegakernel ¶
func BuildTMEMCrossLayerMegakernel(spec TMEMCrossLayerSpec) (*TMEMMegakernelPlan, error)
BuildTMEMCrossLayerMegakernel validates spec, verifies the 512-column TMEM budget per SM, 2-CTA cluster alignment, and balanced tcgen05.alloc / tcgen05.dealloc lifecycle across layers, and constructs a TMEMMegakernelPlan.
func (*TMEMMegakernelPlan) PTXPreview ¶
func (p *TMEMMegakernelPlan) PTXPreview() string
PTXPreview emits a PTX 9.x / CUDA preview of the persistent Blackwell cross-layer megakernel showing TMEM-resident gate_proj, up_proj, SwiGLU, RMSNorm, and qkv_proj stages along with guarded tcgen05.dealloc at layer exit.
func (*TMEMMegakernelPlan) StageNames ¶
func (p *TMEMMegakernelPlan) StageNames() []string
StageNames returns the ordered slice of stage names in p.
func (*TMEMMegakernelPlan) VerifyLifecycle ¶
func (p *TMEMMegakernelPlan) VerifyLifecycle() error
VerifyLifecycle validates the TMEM column budget (<= 512 columns per SM), 2-CTA cluster alignment, balanced tcgen05.alloc / tcgen05.dealloc lifecycle, and formal cudatmem hardware trace invariants.
type TMEMPlacement ¶
type TMEMPlacement struct {
Name string
Width uint16
Cols [2]uint16 // first column of each buffer; equal when single-buffered
}
A TMEMPlacement is one TMEM buffer's columns.
type TMEMStage ¶
type TMEMStage struct {
Name string
Layer int
Op TMEMStageOp
TMEMOffset int
TMEMCols int
CTAGroup int
KeepInTMEM bool
CommitsToMemory bool
AllocatesTMEM bool
DeallocatesTMEM bool
}
TMEMStage describes a single stage in a TMEMMegakernelPlan, tracking its TMEM column slice [TMEMOffset, TMEMOffset+TMEMCols), cluster CTA group size, whether the accumulator remains resident in TMEM across the epilogue, and whether the stage allocates or deallocates TMEM columns.
type TMEMStageOp ¶
type TMEMStageOp string
TMEMStageOp identifies a stage operation inside a TMEMMegakernelPlan.
const ( TMEMStageGateProj TMEMStageOp = "gate_proj" TMEMStageUpProj TMEMStageOp = "up_proj" TMEMStageSwiGLUEpilog TMEMStageOp = "swiglu_epilogue" TMEMStageDownProj TMEMStageOp = "down_proj" TMEMStageRMSNormBridge TMEMStageOp = "rmsnorm_bridge" TMEMStageQKVProj TMEMStageOp = "qkv_proj" )
type TTTSchedule ¶
type TTTSchedule struct {
Name string
Target string // sm_100a, sm_103a, sm_107a or an f variant (default sm_100a)
Variant TTTVariant
HeadDim int // d: 32, 64, 96 or 128
ChunkLen int // L: 32 or 64 tokens per gradient step
NumChunks int // chunks per sequence
LR float32 // inner learning rate eta
WeightDecay float32 // forgetting gate alpha in [0, 1)
Momentum float32 // Titans momentum mu in [0, 1)
Eps float32 // LayerNorm epsilon (default 1e-5)
}
A TTTSchedule configures a test-time-training kernel that keeps the d x d fast weights W (and the Titans momentum M) in TMEM across all chunks of a sequence, one head per CTA iteration of a persistent loop.
For each chunk of L tokens with keys k_t, values v_t and queries q_t:
z_t = W k_t (tcgen05.mma, W the TMEM A operand) ℓ_t = ½‖LN(z_t) - v_t‖² (LN without affine parameters) g_t = ∂ℓ_t/∂z_t (exact LayerNorm VJP, one token per thread) G = Σ_t g_t k_tᵀ W = (1-α) W - η G or M = μ M - η G; W = (1-α) W + M o_t = W q_t (with the updated W)
The decay is applied in TMEM with tcgen05.ld/st and -ηG is accumulated onto W (or M) with enable_input_d = 1. W_0 enters TMEM through one MMA of the staged W_0 against an identity tile, so the fast-weight region is MMA-produced before its first use as an A operand.
TMEM layout (lanes are output rows of W): W at [0, d), z at [d, d+L), o at [d+L, d+2L), M at [d+2L, 2d+2L).
The sm_100a/sm_103a/sm_107a path of the emitted source has not been executed; the EG_EMU path runs in the tests. Stochastic rounding of the staged gradient (cvt.rs) is not implemented.
func (TTTSchedule) CUDA ¶
func (s TTTSchedule) CUDA() (string, error)
CUDA returns the kernel source without Prelude. The kernel signature is
name(int heads, const float* w0, const float* q, const float* k,
const float* v, float* out, float* w, float* loss)
with w0 and w [heads][d][d], q, k, v, out [heads][T][d], and loss [heads][T] receiving each token's ℓ_t before its chunk's update.
func (TTTSchedule) CUDAFile ¶
func (s TTTSchedule) CUDAFile() (string, error)
CUDAFile returns Prelude followed by TTTSchedule.CUDA.
func (TTTSchedule) Grid ¶
func (s TTTSchedule) Grid(heads, ctas int) (grid, block [3]int)
Grid returns the launch shape for heads heads on at most ctas resident CTAs (ctas <= 0 means one CTA per head).
func (TTTSchedule) Reference ¶
func (s TTTSchedule) Reference(w0, q, k, v [][]float32) (out, w [][]float32, chunkLoss []float64, err error)
Reference runs one head in float64. w0 is [d][d], q, k, v are [T][d]. It returns the outputs [T][d], the final W, and each chunk's mean token loss computed before that chunk's update.
func (TTTSchedule) SharedBytes ¶
func (s TTTSchedule) SharedBytes() int
SharedBytes returns the dynamic shared memory the kernel needs, or 0 if s is invalid.
func (TTTSchedule) TMEMColumns ¶
func (s TTTSchedule) TMEMColumns() uint32
TMEMColumns returns the TMEM allocation width of the kernel. It is 0 if the width exceeds MaxTMEMColumnsPerSM.
func (TTTSchedule) TraceEvents ¶
func (s TTTSchedule) TraceEvents() []layout.TraceEvent
TraceEvents returns the tcgen05 operation sequence of one head, for cudatmem.VerifyTrace.
func (TTTSchedule) Validate ¶
func (s TTTSchedule) Validate() error
Validate reports whether s describes a kernel this package can emit.
type TTTVariant ¶
type TTTVariant uint8
A TTTVariant selects the fast-weight update of a TTTSchedule.
const ( // TTTLinearSGD is TTT-Linear: W = (1 - alpha) W - eta G. TTTLinearSGD TTTVariant = iota // TTTTitansMomentum is the Titans memory update: // M = mu M - eta G; W = (1 - alpha) W + M. TTTTitansMomentum )
func (TTTVariant) String ¶
func (v TTTVariant) String() string
type TileEpilogue ¶
type TileEpilogue uint8
TileEpilogue selects the elementwise epilogue applied to TCGen05GEMM accumulators.
const ( TileLinear TileEpilogue = iota // identity: y = acc TileSiLU // SiLU: y = acc / (1 + exp(-acc)) TileGLU // SwiGLU over paired (gate, up) columns: y = silu(gate) * up )
func (TileEpilogue) String ¶
func (e TileEpilogue) String() string
type TubeletPatchSpec ¶
type TubeletPatchSpec struct {
Name string
Target string // sm_100a, sm_103a, sm_107a or an f variant (default sm_100a)
Frames, Height, Width int
Channels int // 4 to 32 in steps of 4 (pad RGB to 4)
PatchT, PatchH, PatchW int
EmbedDim int // a multiple of 16; the CTA tile is min(EmbedDim, 128) wide
}
A TubeletPatchSpec describes a spatiotemporal patch embedding: a video [Frames][Height][Width][Channels] of FP32 values is cut into PatchT x PatchH x PatchW tubelets (zero padded at the far edges) and each flattened tubelet (dt, dh, dw, c order) is projected by W [EmbedDim][Kp], Kp = PatchT*PatchH*PatchW*Channels.
func (TubeletPatchSpec) CUDA ¶
func (s TubeletPatchSpec) CUDA() (string, error)
CUDA returns the patch-embedding kernel source without Prelude:
name(const float* video, const float* w, float* out)
Each thread gathers one tubelet row per K step into shared memory in the order the TMA box of BuildTubeletTMADescriptor delivers it, with zeros past the far edges, and the tile is projected by tcgen05.mma into TMEM. The kernel does not issue the TMA load itself. The sm_100a path has not been executed; the EG_EMU path runs in the tests.
func (TubeletPatchSpec) Grid ¶
func (s TubeletPatchSpec) Grid() (grid, block [3]int)
Grid returns the launch shape: EmbedDim tiles by 128-tubelet tiles.
func (TubeletPatchSpec) GridTHW ¶
func (s TubeletPatchSpec) GridTHW() (t, h, w int)
GridTHW returns the number of tubelets along time, height and width.
func (TubeletPatchSpec) PatchLen ¶
func (s TubeletPatchSpec) PatchLen() int
PatchLen returns Kp, the flattened tubelet length.
func (TubeletPatchSpec) Patches ¶
func (s TubeletPatchSpec) Patches() int
Patches returns the number of tubelets.
func (TubeletPatchSpec) Reference ¶
func (s TubeletPatchSpec) Reference(video []float32, w [][]float32) ([][]float32, error)
Reference computes the patch embedding [Patches][EmbedDim] in float64; patch p is (pt, ph, pw) in row-major order of TubeletPatchSpec.GridTHW.
func (TubeletPatchSpec) SharedBytes ¶
func (s TubeletPatchSpec) SharedBytes() int
SharedBytes returns the dynamic shared memory the kernel needs, or 0 if s is invalid.
func (TubeletPatchSpec) TraceEvents ¶
func (s TubeletPatchSpec) TraceEvents() []layout.TraceEvent
TraceEvents returns the tcgen05 operation sequence of one CTA.
func (TubeletPatchSpec) Validate ¶
func (s TubeletPatchSpec) Validate() error
Validate reports whether s describes a kernel this package can emit.
type WSCollectorAction ¶
type WSCollectorAction string
WSCollectorAction specifies the lifecycle operation performed on a WSCollectorBuffer during tcgen05.mma.ws execution.
const ( WSActionFill WSCollectorAction = "fill" WSActionUse WSCollectorAction = "use" WSActionLastUse WSCollectorAction = "lastuse" WSActionDiscard WSCollectorAction = "discard" )
type WSCollectorBuffer ¶
type WSCollectorBuffer string
WSCollectorBuffer identifies one of the 4 hardware B-matrix collector reuse buffers in tcgen05.mma.ws (PTX ISA 9.4 section 9.7.18.10.10.3–4).
const ( WSCollectorB0 WSCollectorBuffer = "b0" WSCollectorB1 WSCollectorBuffer = "b1" WSCollectorB2 WSCollectorBuffer = "b2" WSCollectorB3 WSCollectorBuffer = "b3" )
type WarpRoleKind ¶
type WarpRoleKind string
A WarpRoleKind identifies a specialized warp role inside a persistent CTA. The roles form a chain in the order of the constants below: each role consumes what the previous one produced through a ring of stages.
const ( RoleTMAProducer WarpRoleKind = "TMAProducer" // issues cp.async.bulk.tensor RoleMMAIssuer WarpRoleKind = "MMAIssuer" // issues tcgen05.cp and tcgen05.mma RoleEpilogueMath WarpRoleKind = "EpilogueMath" // tcgen05.ld, softmax or SwiGLU, quantization RoleFabricStorer WarpRoleKind = "FabricStorer" // TMA store or fabric put )
type WeightFormat ¶
type WeightFormat uint8
A WeightFormat specifies how a GEMM weight matrix W [N, K] is stored.
const ( WeightBF16 WeightFormat = iota + 1 WeightBF16HiLo WeightNVFP4 WeightE4M3 )
func (WeightFormat) String ¶
func (f WeightFormat) String() string
type ZeroColumnMaskDesc ¶
ZeroColumnMaskDesc models the 64-bit zero-column mask descriptor consumed by tcgen05.mma and tcgen05.mma.ws (PTX ISA 9.4 section 9.7.18.4.3).
The 64-bit descriptor partitions each 64-column K-tile into 8 sub-masks i in 0..7 of 8 columns each:
- Bits 0..23: StartCount[i] (3 bits at i*3), number of initial non-zero columns in group i.
- Bits 24..31: NonZeroMask (bit i == 0 means all columns in group i are used; bit i == 1 means SkipSpan[i]+1 columns starting at StartCount[i] are zeroed).
- Bits 32..55: SkipSpan[i] (3 bits at 32 + i*3), storing skip_span - 1.
func DecodeZeroColumnMaskDesc ¶
func DecodeZeroColumnMaskDesc(v uint64) ZeroColumnMaskDesc
DecodeZeroColumnMaskDesc unpacks a 64-bit PTX zero-column mask descriptor word.
func (ZeroColumnMaskDesc) Encode ¶
func (d ZeroColumnMaskDesc) Encode() uint64
Encode packs d into the 64-bit PTX zero-column mask descriptor word.
func (ZeroColumnMaskDesc) IsColumnZeroed ¶
func (d ZeroColumnMaskDesc) IsColumnZeroed(col int) bool
IsColumnZeroed reports whether K-dimension column col is zeroed in operand A by the zero-column mask descriptor.
Source Files
¶
- attention.go
- blockfp8.go
- blocknvfp4.go
- clc.go
- cudalower_gemm.go
- cudalower_mma_cfg6_source.go
- cudalower_nvfp4_tma_source.go
- cudalower_rubin_ptx94.go
- cudalower_skinnymma.go
- cudalower_sm120.go
- cudalower_tensormap.go
- cudalower_tile.go
- cudalower_types.go
- cudalower_umma.go
- cudalower_warpspec.go
- cudalower_wgmma.go
- desc.go
- doc.go
- dynsparse.go
- flash_logits.go
- gb300.go
- kv_subspace.go
- ld_red_spcompress.go
- learned_lut.go
- lora.go
- megakernel_tmem.go
- multimodal.go
- mxfp8_fp6.go
- rubin.go
- sparse.go
- spcompress.go
- specs.go
- ssm.go
- tcgen05.go
- tcgen05_advanced.go
- tma_multicast.go
- tmem_mma.go
- ttt.go
- warpsynth_emit.go
- warpsynth_synth.go
- warpsynth_verify.go
- ws_exclusive.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package mmaarith models NVIDIA Blackwell tcgen05 dot and accumulator arithmetic with integers.
|
Package mmaarith models NVIDIA Blackwell tcgen05 dot and accumulator arithmetic with integers. |
|
cmd/sm103probe
command
Command sm103probe is a standalone GB300 (sm_103a) / B200 (sm_100a) hardware validation & differential fuzzer CLI for tcgen05 MMA reference arithmetic.
|
Command sm103probe is a standalone GB300 (sm_103a) / B200 (sm_100a) hardware validation & differential fuzzer CLI for tcgen05 MMA reference arithmetic. |