nvidia

package
v0.0.0-...-99ac9cd Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 36 Imported by: 1 module, 0 packages

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

Documentation

Index

Examples

Constants

View Source
const MaxDecisionAttentionTokens = 32768

Long attention is bounded by the public decision context contract. Its scratch is <=8 MiB regardless of query rows; rows are launched in chunks.

Variables

This section is empty.

Functions

func AffineLayerNormF32Buffer

func AffineLayerNormF32Buffer(out, x, gamma, beta *Buffer, rows, cols int, eps float32) error

AffineLayerNormF32Buffer normalizes row-major GPU-resident F32 input and applies per-column gamma and beta. Output may alias input, but not the gamma/beta buffers; non-aliased inputs remain unchanged.

func ArgmaxF32

func ArgmaxF32(buf *Buffer, n int) (int, float32, error)

ArgmaxF32 returns the max value/index for a GPU-resident float32 buffer. The GPU computes per-block winners, then the host reduces the small partials.

func Available

func Available() bool

Available returns true if CUDA GPU is accessible.

func BF16LMHead

func BF16LMHead(logits []float32, weightRaw []byte, x []float32, vocab, h int) error

func BF16LMHeadWithBuffer

func BF16LMHeadWithBuffer(logits []float32, wBuf *Buffer, x []float32, vocab, h int) error

func BatchGEMMReady

func BatchGEMMReady() bool

BatchGEMMReady returns true if batched GEMM kernel is available.

func BatchedFP8OProj

func BatchedFP8OProj(out, attn []float32, batch int, wO *GPUFP8E4M3Linear) error

BatchedFP8OProj runs the O projection FP8 GEMM. For batch > 1 it uses dequant+SGEMM for better throughput.

func BatchedFP8QKV

func BatchedFP8QKV(qOut, kOut, vOut, hidden []float32, batch int, wQ, wK, wV *GPUFP8E4M3Linear) error

BatchedFP8QKV runs Q, K, V FP8 GEMM projections sharing a single GPU upload of the hidden activations. When batch > 1 and SGEMM is available, it uses dequant + SGEMM which is dramatically faster than the per-element FP8 GEMM kernel for large batches.

All weight matrices must have the same InDim (hidden size). If wV is nil, vOut receives a copy of kOut.

func BeginCapture

func BeginCapture() error

BeginCapture starts capturing GPU operations on the default stream.

func CausalBatchAttentionBuffer

func CausalBatchAttentionBuffer(out, q, k, v *Buffer, rows, pos0, kvLen, window, nHeads, nKVHeads, headDim int, scale float32) error

func ChunkedLMHead

func ChunkedLMHead(logits, hidden, lmHead []float32, vocabSize, h int) bool

Chunked LM head: processes vocab projection in GPU-sized chunks.

When full LM head weights do not fit in VRAM, split into chunks:

  1. Allocate a GPU buffer for chunkRows rows
  2. Upload chunk of LM head weights
  3. GPU GEMV for chunkRows rows
  4. Download logits for those rows
  5. Repeat for all chunks

This trades upload bandwidth for GPU compute speed.

func ComputeCapability

func ComputeCapability() (major, minor int)

ComputeCapability returns the CUDA compute capability for device 0.

func CopyDtoD

func CopyDtoD(dst, src CUdeviceptr, bytes uint64) error

CopyDtoD wraps cuMemcpyDtoD for direct GPU→GPU copy.

func DequantNVFP4ToF32

func DequantNVFP4ToF32(w *GPUNVFP4Weight) ([]float32, error)

DequantNVFP4ToF32 materializes a GPU-resident NVFP4 weight as row-major F32. It first tries the CUDA dequant kernel, then falls back to downloading raw buffers and reusing the SIMD NVFP4 reference dequantizer.

func DevAdd

func DevAdd(out, a, b *DevBuf)

Add: out = a + b (element-wise)

func DevAddScaled

func DevAddScaled(out, a, b *DevBuf, s float32)

AddScaled: out = a + b * scalar.

func DevAttention

func DevAttention(out, q, kCache, vCache *DevBuf, seqLen, nHeads, nKVHeads, headDim int, scale float32)

DevAttention runs GQA attention on GPU. q[nHeads*headDim], kCache/vCache[seqLen*kvDim], out[nHeads*headDim]

func DevAttentionOK

func DevAttentionOK(out, q, kCache, vCache *DevBuf, seqLen, nHeads, nKVHeads, headDim int, scale float32) bool

DevAttentionOK is DevAttention plus a success flag for higher-level code that wants to preserve an explicit CPU fallback path.

func DevAttentionScores

func DevAttentionScores(out, q, kCache *DevBuf, seqLen, nHeads, nKVHeads, headDim int, scale float32) bool

DevAttentionScores runs the score phase of GQA attention on GPU. out[nHeads*seqLen], q[nHeads*headDim], kCache[seqLen*kvDim]

func DevAttentionSplitKV

func DevAttentionSplitKV(out, q, kCache, vCache *DevBuf, seqLen, nHeads, nKVHeads, headDim int, scale float32)

DevAttentionSplitKV launches the opt-in split-KV decode-attention candidate.

func DevAttentionSplitKVOK

func DevAttentionSplitKVOK(out, q, kCache, vCache *DevBuf, seqLen, nHeads, nKVHeads, headDim int, scale float32) bool

DevAttentionSplitKVOK launches the opt-in split-KV decode-attention candidate. Production dispatch remains on DevAttentionOK.

func DevAttentionSplitKVReady

func DevAttentionSplitKVReady() bool

DevAttentionSplitKVReady reports whether the opt-in split-KV candidate is available.

func DevBF16GELUTanhMul

func DevBF16GELUTanhMul(gate, up *Buffer, n int) bool

DevBF16GELUTanhMul computes gate[i] = BF16(GELUTanh(F32(gate[i])) * F32(up[i])) in-place.

func DevBF16RMSNorm

func DevBF16RMSNorm(x, w *Buffer, n int, eps float32) bool

DevBF16RMSNorm applies RMSNorm on BF16 data: x[i] = BF16(F32(x[i]) * invRMS * F32(w[i]))

func DevBF16RMSNormNoScale

func DevBF16RMSNormNoScale(x *Buffer, n int, eps float32) bool

DevBF16RMSNormNoScale applies RMSNormNoScale on BF16 data: x[i] = BF16(F32(x[i]) * invRMS).

func DevBF16SiLUMul

func DevBF16SiLUMul(dst, gate, up *Buffer, n int) bool

DevBF16SiLUMul computes dst[i] = BF16(SiLU(F32(gate[i])) * F32(up[i])).

func DevBF16VecAdd

func DevBF16VecAdd(dst, a, b *Buffer, n int) bool

DevBF16VecAdd computes dst[i] = BF16(F32(a[i]) + F32(b[i]))

func DevCopy

func DevCopy(dst, src *DevBuf)

Copy copies src data to dst (same device).

func DevCopyN

func DevCopyN(dst, src *DevBuf, n int)

DevCopyN copies the first n float32 elements from src to dst and marks dst authoritative on the device where the copy completed. It is useful for shared max-sized work buffers whose active row width is smaller than the allocation.

func DevGELUErf

func DevGELUErf(x *DevBuf, n int)

DevGELUErf applies exact-form GELU in place using the GPU erf approximation.

func DevGELUTanhMul

func DevGELUTanhMul(gate, up *DevBuf, n int)

DevGELUTanhMul: gate[i] = gelu_tanh(gate[i]) * up[i] in-place

func DevGemv

func DevGemv(out, x *DevBuf, W *DevBuf, M, K int)

Gemv: out[M] = W[M,K] * x[K] (matrix-vector multiply)

func DevGemvNN

func DevGemvNN(out, x *DevBuf, W *DevBuf, K, N int)

GemvNN: out[N] = x[K] @ W[K,N] (W is pre-transposed, column-major for output) This is for the non-Large path where weights are pre-transposed.

func DevLMHead

func DevLMHead(logits, x, W *DevBuf, vocab, h int)

DevLMHead computes logits[vocab] = W[vocab,h] · x[h] Uses a dedicated kernel optimized for large M (vocab) and small N (1).

func DevMul

func DevMul(out, a, b *DevBuf)

Mul: out = a * b (element-wise)

func DevNativeBF16RMSNorm

func DevNativeBF16RMSNorm(x, w *Buffer, n int, eps float32) bool

DevNativeBF16RMSNorm runs hardware BF16 RMSNorm on Ampere+.

func DevNativeBF16VecAdd

func DevNativeBF16VecAdd(dst, a, b *Buffer, n int) bool

DevNativeBF16VecAdd runs hardware BF16 add on Ampere+.

func DevRMSNorm

func DevRMSNorm(out, x, weight *DevBuf, eps float32)

RMSNorm: out = x * weight * rsqrt(mean(x^2) + eps)

func DevRMSNormNoScale

func DevRMSNormNoScale(out, x *DevBuf, eps float32)

DevRMSNormNoScale: normalize x by RMS without weight. out = x / rms(x)

func DevRMSNormOK

func DevRMSNormOK(out, x, weight *DevBuf, eps float32) bool

DevRMSNormOK is DevRMSNorm plus a success flag that reports whether the GPU kernel handled the operation. A false result means the CPU fallback path ran.

func DevRoPE

func DevRoPE(x *DevBuf, cosSin *DevBuf, pos, nHeads, headDim int) bool

DevRoPE applies rotary position embedding on GPU (in-place). cosSin is a precomputed [maxSeq * headDim] buffer with interleaved cos,sin pairs.

func DevRoPEPartial

func DevRoPEPartial(x *DevBuf, cosSin *DevBuf, pos, nHeads, headDim, rotHalf int) bool

DevRoPEPartial applies partial rotary position embedding on GPU (in-place). cosSin is [maxSeq * rotHalf * 2] with interleaved cos,sin pairs.

func DevScale

func DevScale(out, a *DevBuf, s float32)

Scale: out = a * scalar

func DevSiLU

func DevSiLU(out, a *DevBuf)

SiLU: out = a * sigmoid(a)

func DevSiLUMul

func DevSiLUMul(out, a, b *DevBuf)

DevSiLUMul computes out = silu(a) * b in one kernel launch

func DevSoftmax

func DevSoftmax(x *DevBuf, n int)

Softmax in-place (CPU only for now — sequential reduction)

func DevSoftmaxRows

func DevSoftmaxRows(out, in *DevBuf, nRows, seqLen int) bool

DevSoftmaxRows runs the softmax phase over contiguous score rows. in/out[nRows*seqLen], one block per row.

func DevToBF16

func DevToBF16(x *DevBuf, n int)

ToBF16: truncate float32 values in-place to BF16 precision.

func DeviceName

func DeviceName() string

DeviceName returns the GPU name.

func DiffusionDenseSample

func DiffusionDenseSample(logits *Buffer, uniforms []float32, positions, vocab int, invTemp float32) ([]int, []float64, []int, error)

DiffusionDenseSample reads device-resident row-major logits [positions,vocab] and returns per-position argmax, entropy and one multinomial sample. It mirrors llama.cpp's CUDA diffusion_dense_sample_kernel and copies back only O(C) data.

func DiffusionSoftmaxRows

func DiffusionSoftmaxRows(logits, probs *Buffer, positions, vocab int, invTemp float32) error

func EnsureContext

func EnsureContext()

EnsureContext sets the CUDA context on the calling thread. It does not pin a subsequent driver call. Internal driver wrappers must instead hold an OS-thread pin and cudaMu across ensureContextLocked and the driver operation, as the checked buffer/launch methods do.

func ExpertMetaReduce

func ExpertMetaReduce(offsets, weights, counts, sums *Buffer, groups int) error

func F32BatchedCausalGQAAttention

func F32BatchedCausalGQAAttention(out, qAll, kCache, vCache []float32, positions, nHeads, nKVHeads, headDim int, scale float32) error

F32BatchedCausalGQAAttention computes causal prompt self-attention for all query positions. K,V are uploaded once; each query position attends only to the prefix [0,pos]. This is a stepping stone toward a fully fused/device- resident prompt prefill graph while preserving causal semantics.

func F32BatchedGQAAttention

func F32BatchedGQAAttention(out, qAll, kCache, vCache []float32, positions, seqLen, nHeads, nKVHeads, headDim int, scale float32) error

F32BatchedGQAAttention computes GQA attention for multiple query positions against a shared KV cache, uploading K,V only once. qAll is [positions, nHeads, headDim], out is [positions, nHeads, headDim]. kCache, vCache are [seqLen, nKVHeads, headDim] (shared across positions).

func F32GQAAttention

func F32GQAAttention(out, q, kCache, vCache []float32, seqLen, nHeads, nKVHeads, headDim int, scale float32) error

F32GQAAttention computes one causal GQA attention output for a single query row against prefix KV caches. q is [nHeads, headDim], k/v are [seqLen, nKVHeads, headDim], out is [nHeads, headDim].

func F32Mul

func F32Mul(out, a, b []float32) error

F32Mul computes out = a*b through temporary device buffers.

func F32MulBuffer

func F32MulBuffer(out, a, b *Buffer, n int) error

F32MulBuffer computes out = a*b on GPU-resident F32 buffers.

func F32RMSNorm

func F32RMSNorm(out, x, weight []float32, eps float32) error

F32RMSNorm computes out = RMSNorm(x) * weight through temporary device buffers. It is a correctness/wiring wrapper for early GPU conversion stages.

func F32RMSNormBuffer

func F32RMSNormBuffer(out, x, weight *Buffer, n int, eps float32) error

F32RMSNormBuffer computes out = RMSNorm(x) * weight on GPU-resident F32 buffers. It exposes the existing NVIDIA RMSNorm kernel for model code that uses low-level Buffer rather than DevBuf.

func F32RoPE

func F32RoPE(x []float32, cos, sin []float32, pos, nHeads, headDim int) error

F32RoPE applies rotary position embedding to one or more row-major F32 heads through the existing NVIDIA RoPEPartial kernel. cos and sin are separate [seqLen, headDim/2] tables, matching Ideogram/Qwen's CPU ropeTable layout.

func F32SiLU

func F32SiLU(out, x []float32) error

F32SiLU computes out = silu(x) through temporary device buffers.

func F32SiLUBuffer

func F32SiLUBuffer(out, x *Buffer, n int) error

F32SiLUBuffer computes out = silu(x) on GPU-resident F32 buffers.

func F32SiLUMul

func F32SiLUMul(out, a, b []float32) error

F32SiLUMul computes out = silu(a)*b through temporary device buffers.

func F32SiLUMulBuffer

func F32SiLUMulBuffer(out, a, b *Buffer, n int) error

func FreeBF16LMHeadScratch

func FreeBF16LMHeadScratch()

func FreeExpertEntry

func FreeExpertEntry(e *ExpertEntry)

FreeExpertEntry releases GPU resources for an evicted expert.

func GELUErfF32Buffer

func GELUErfF32Buffer(x *Buffer, n int) error

GELUErfF32Buffer applies the exact-form erf GELU approximation in place to n GPU-resident F32 values. It returns an error rather than falling back to CPU.

func GELUTanhMulBuffer

func GELUTanhMulBuffer(gate, up *Buffer, n int) error

GELUTanhMulBuffer computes gate = GELU(gate) * up in-place on device buffers.

func GateUpGELUBuffer

func GateUpGELUBuffer(src, out *Buffer, batch, intermediate int) error

func GateUpGELUQ4KBatchToBuffer

func GateUpGELUQ4KBatchToBuffer(outBuf *Buffer, xBuf *Buffer, batch, intermediate int, m *GPUQ4KMatrix) error

func GateUpGELUQ4KByWorkPtrsToBuffer

func GateUpGELUQ4KByWorkPtrsToBuffer(outBuf, xBuf, workExperts *Buffer, workLen, intermediate int, table *GPUQ4KPointerTable) error

func GateUpGELUQ4KByWorkToBuffer

func GateUpGELUQ4KByWorkToBuffer(outBuf, xBuf, workExperts *Buffer, workLen, intermediate, activeExperts int, m *GPUQ4KMatrix) error

func GateUpQ4KByWorkPtrsToBuffers

func GateUpQ4KByWorkPtrsToBuffers(gateBuf, upBuf, xBuf, workExperts *Buffer, workLen, intermediate int, table *GPUQ4KPointerTable) error

func GatherRows

func GatherRows(dst, src, pos *Buffer, rows, hidden int) error

func Gemm2FP8E4M3SameInput

func Gemm2FP8E4M3SameInput(outA, outB, x []float32, batch int, wA, wB *GPUFP8E4M3Linear) error

func GemmDiTLayerIslandsFP8E4M3

func GemmDiTLayerIslandsFP8E4M3(hidden []float32, attnN1, scaleMSA, gateMSA, normQ, normK, attnN2, ffnN1, scaleMLP, gateMLP, ffnN2, cos, sin []float32, tokens, heads, headDim int, scaleAttn, normEps float32, qkv, o, w1, w3, w2 *GPUFP8E4M3Linear) error

Gemm2FP8E4M3SameInput computes two row-major FP8 GEMMs sharing one uploaded activation matrix. This is intended for SwiGLU-style projection pairs such as Ideogram/Qwen W1+W3, where both linears consume the exact same [batch,InDim] input. It reduces host-device traffic without changing numerical kernels.

func GemmFP8E4M3

func GemmFP8E4M3(out, x []float32, batch int, w *GPUFP8E4M3Linear) error

GemmFP8E4M3 computes dense row-major out[batch,OutDim] = x[batch,InDim] · W^T.

func GemmFP8E4M3Buffer

func GemmFP8E4M3Buffer(outBuf, xBuf *Buffer, batch int, w *GPUFP8E4M3Linear) error

func GemmFP8E4M3ViaSgemmBuffer

func GemmFP8E4M3ViaSgemmBuffer(outBuf, xBuf *Buffer, batch int, w *GPUFP8E4M3Linear) error

func GemmMLX

func GemmMLX(out, input *DevBuf, w *GPUMLXWeight, B int)

GemmMLX performs batched GPU GEMM with MLX quantized weights.

func GemmNVFP4

func GemmNVFP4(out, x []float32, batch int, w *GPUNVFP4Weight) error

GemmNVFP4 computes dense out[batch,outDim] = x[batch,inDim] @ W_nvfp4^T. Native packed GEMM is not implemented yet; this correctness-first entrypoint uses the packed SIMD NVFP4 reference as the CPU fallback contract future CUDA kernels must match.

func GemmQ4

func GemmQ4(out, input *DevBuf, w *GPUQuantWeight, B int)

GemmQ4 performs batched matrix multiply: out[B×outDim] = input[B×inDim] × W_q4[inDim×outDim] where W is INT4 quantized with group scales.

func GemmQ4CoalescedF32ToBuffer

func GemmQ4CoalescedF32ToBuffer(outBuf, xBuf *Buffer, batch int, m *GPUQ4KMatrix) error

func GemmQ4CoalescedQ8ToBuffer

func GemmQ4CoalescedQ8ToBuffer(outBuf, xBuf *Buffer, batch int, m *GPUQ4KMatrix) error

func GemmQ4KBatch8ToBuffer

func GemmQ4KBatch8ToBuffer(outBuf, xBuf *Buffer, batch int, m *GPUQ4KMatrix) error

func GemmQ4KQ8ToBuffer

func GemmQ4KQ8ToBuffer(outBuf, xBuf *Buffer, batch int, m *GPUQ4KMatrix) error

func GemmQKVAttentionFP8E4M3

func GemmQKVAttentionFP8E4M3(out, x, normQ, normK, cos, sin []float32, tokens, heads, headDim int, scale float32, wqkv *GPUFP8E4M3Linear) error

func GemmQKVAttentionOResidualFP8E4M3

func GemmQKVAttentionOResidualFP8E4M3(hidden, x, gate, normQ, normK, normOut, cos, sin []float32, tokens, heads, headDim int, scale float32, wqkv, wo *GPUFP8E4M3Linear) error

func GemmQKVAttentionOResidualFP8E4M3Buffer

func GemmQKVAttentionOResidualFP8E4M3Buffer(hiddenBuf, xBuf, gateBuf, normQBuf, normKBuf, normOutBuf, cosBuf, sinBuf *Buffer, tokens, heads, headDim int, scale float32, wqkv, wo *GPUFP8E4M3Linear) error

func GemmSwiGLUFP8E4M3

func GemmSwiGLUFP8E4M3(out, x []float32, batch int, w1, w3, w2 *GPUFP8E4M3Linear) error

func GemmSwiGLUResidualFP8E4M3

func GemmSwiGLUResidualFP8E4M3(hidden, x, gate, normOut []float32, batch int, w1, w3, w2 *GPUFP8E4M3Linear) error

func GemmSwiGLUResidualFP8E4M3Buffer

func GemmSwiGLUResidualFP8E4M3Buffer(hiddenBuf, xBuf, gateBuf, normOutBuf *Buffer, batch int, w1, w3, w2 *GPUFP8E4M3Linear) error

func GemvFP8E4M3

func GemvFP8E4M3(out, x []float32, w *GPUFP8E4M3Linear) error

GemvFP8E4M3 computes dense out[OutDim] = dequant(W) · x with row/tensor scale and optional bias. It uses the CUDA direct FP8 GEMV kernel when available and falls back to the CPU fp8 backend otherwise.

func GemvFP8E4M3Buffer

func GemvFP8E4M3Buffer(outBuf, xBuf *Buffer, w *GPUFP8E4M3Linear) error

GemvFP8E4M3Buffer computes into GPU-resident buffers. It is the lower-level primitive intended for Ideogram graph wiring once activations stay on-device.

func GemvMLX

func GemvMLX(out *DevBuf, x *DevBuf, w *GPUMLXWeight)

GemvMLX performs GPU GEMV with MLX quantized weights using optimized kernel.

func GemvMLXDirect

func GemvMLXDirect(out *DevBuf, x *DevBuf, w *GPUMLXWeight)

func GemvNVFP4

func GemvNVFP4(out, x []float32, w *GPUNVFP4Weight) error

GemvNVFP4 computes dense out[outDim] = W_nvfp4[outDim,inDim] · x[inDim]. It keeps the hot path on-device: packed NVFP4 is dequantized into a transient GPU F32 matrix and multiplied with SGEMM, downloading only the output vector. If any CUDA step fails, callers can fall back to the CPU SIMD NVFP4 path.

func GemvNVFP4Buffer

func GemvNVFP4Buffer(outBuf, xBuf *Buffer, w *GPUNVFP4Weight) error

func GemvQ4

func GemvQ4(out *DevBuf, x *DevBuf, w *GPUQuantWeight)

GemvQ4 computes out[outDim] = x[inDim] @ dequant(W) on GPU.

func GemvQ4K

func GemvQ4K(out, x []float32, m *GPUQ4KMatrix) error

func GemvQ4KBatch

func GemvQ4KBatch(out, x []float32, batch int, m *GPUQ4KMatrix) error

func GemvQ4KBatchToBuffer

func GemvQ4KBatchToBuffer(outBuf *Buffer, xBuf *Buffer, batch int, m *GPUQ4KMatrix) error

func GemvQ4OrGemm

func GemvQ4OrGemm(out, input *DevBuf, w *GPUQuantWeight, B int)

GemvQ4OrGemm dispatches to GEMV (B=1) or batched GEMM (B>1).

func GemvQ5KBatch

func GemvQ5KBatch(out, x []float32, batch int, m *GPUQKMatrix) error

func GemvQ5KBatchToBuffer

func GemvQ5KBatchToBuffer(out, x *Buffer, batch int, m *GPUQKMatrix) error

func GemvQ5_0Batch

func GemvQ5_0Batch(out, x []float32, batch int, m *GPUQ5_0Matrix) error

func GemvQ5_0ScatterByWork

func GemvQ5_0ScatterByWork(dstBuf, xBuf, workActive, workPos, workWeight *Buffer, workLen, activeExperts int, m *GPUQ5_0Matrix) error

func GemvQ5_0ScatterByWorkPtrs

func GemvQ5_0ScatterByWorkPtrs(dstBuf, xBuf, workActive, workPos, workWeight *Buffer, workLen int, table *GPUQ5_0PointerTable) error

func GemvQ6KBatch

func GemvQ6KBatch(out, x []float32, batch int, m *GPUQKMatrix) error

func GemvQ6KBatchToBuffer

func GemvQ6KBatchToBuffer(out, x *Buffer, batch int, m *GPUQKMatrix) error

func GemvQ8_0

func GemvQ8_0(out, x []float32, m *GPUQ8_0Matrix) error

func GemvQ8_0Batch

func GemvQ8_0Batch(out, x []float32, batch int, m *GPUQ8_0Matrix) error

func GemvQ8_0BatchScatter

func GemvQ8_0BatchScatter(dstBuf, xBuf, posBuf, weightBuf *Buffer, batch int, m *GPUQ8_0Matrix) error

func GemvQ8_0BatchToBuffer

func GemvQ8_0BatchToBuffer(outBuf *Buffer, xBuf *Buffer, batch int, m *GPUQ8_0Matrix) error

func GemvQ8_0ScatterByWork

func GemvQ8_0ScatterByWork(dstBuf, xBuf, workActive, workPos, workWeight *Buffer, workLen, activeExperts int, m *GPUQ8_0Matrix) error

func GemvQ8_0ScatterByWorkPtrs

func GemvQ8_0ScatterByWorkPtrs(dstBuf, xBuf, workActive, workPos, workWeight *Buffer, workLen int, table *GPUQ8_0PointerTable) error

func GraphsReady

func GraphsReady() bool

GraphsReady reports whether CUDA graph capture/replay entry points are loaded.

func IdeogramAdaLNTransform

func IdeogramAdaLNTransform(mod []float32, emb int) error

IdeogramAdaLNTransform transforms a CPU modulation slice through temporary GPU storage. It is an early wiring/correctness wrapper before DiT blocks keep adaLN tensors GPU-resident.

func IdeogramAdaLNTransformBuffer

func IdeogramAdaLNTransformBuffer(mod *Buffer, emb int) error

IdeogramAdaLNTransformBuffer transforms [scale_msa, gate_msa, scale_mlp, gate_mlp] in-place on a GPU-resident F32 buffer, each slice length emb.

func IdeogramAttentionScoresBuffer

func IdeogramAttentionScoresBuffer(scores, q, k *Buffer, tokens, heads, headDim int, scale float32) error

func IdeogramAttentionValuesBuffer

func IdeogramAttentionValuesBuffer(out, probs, v *Buffer, tokens, heads, headDim int) error

func IdeogramCFGStep

func IdeogramCFGStep(out, latents, cond, uncond []float32, guidance, sigma float32) error

IdeogramCFGStep computes the fused CFG+Euler update using temporary device buffers. It is a convenience/validation wrapper for the current Ideogram pipeline, which still returns DiT velocities as CPU slices.

func IdeogramCFGStepBuffer

func IdeogramCFGStepBuffer(out, latents, cond, uncond *Buffer, n int, guidance, sigma float32) error

IdeogramCFGStepBuffer fuses asymmetric CFG and FlowMatch Euler update on GPU-resident F32 buffers:

out = latents + sigma * (uncond + guidance * (cond - uncond))

All buffers must hold at least n float32 elements.

func IdeogramConv2D

func IdeogramConv2D(out, in, weight, bias []float32, outC, inC, h, w, kh, kw int) error

IdeogramConv2D applies stride-1 same-padding CHW/OIHW F32 convolution through the NVIDIA direct-convolution kernel.

func IdeogramConv2DBuffer

func IdeogramConv2DBuffer(outBuf, inBuf, wBuf, bBuf *Buffer, outC, inC, h, w, kh, kw int, hasBias bool) error

IdeogramConv2DBuffer applies stride-1 same-padding CHW/OIHW F32 convolution on GPU-resident buffers.

func IdeogramFullAttention

func IdeogramFullAttention(out, q, k, v []float32, tokens, heads, headDim int, scale float32) error

IdeogramFullAttention computes full non-causal attention for token-major [tokens, heads, headDim] Q/K/V through temporary device buffers.

func IdeogramFullAttentionSgemm

func IdeogramFullAttentionSgemm(out, q, k, v []float32, tokens, dim int, scale float32) error

func IdeogramGatedResidual

func IdeogramGatedResidual(hidden, update, gate []float32) error

IdeogramGatedResidual computes hidden += gate * update using temporary device buffers. Hidden is downloaded back in-place.

func IdeogramGatedResidualBuffer

func IdeogramGatedResidualBuffer(hidden, update, gate *Buffer, n int) error

IdeogramGatedResidualBuffer computes hidden += gate * update in-place on GPU-resident F32 buffers.

func IdeogramGatedResidualRows

func IdeogramGatedResidualRows(hidden, update, gate []float32, rows, cols int) error

IdeogramGatedResidualRows computes hidden[row,col] += gate[col] * update[row,col] through temporary device buffers. Hidden is downloaded back in-place.

func IdeogramGatedResidualRowsBuffer

func IdeogramGatedResidualRowsBuffer(hidden, update, gate *Buffer, rows, cols int) error

func IdeogramGroupNorm

func IdeogramGroupNorm(out, in, gamma, beta []float32, c, h, w, groups int, eps float32) error

IdeogramGroupNorm applies CHW GroupNorm with per-channel affine through the NVIDIA kernel.

func IdeogramGroupNormBuffer

func IdeogramGroupNormBuffer(outBuf, inBuf, gBuf, bBuf *Buffer, c, h, w, groups int, eps float32) error

IdeogramGroupNormBuffer applies CHW GroupNorm with per-channel affine on GPU-resident buffers.

func IdeogramLatentDenorm

func IdeogramLatentDenorm(x, scale, shift []float32, channels int) error

IdeogramLatentDenorm applies per-channel latent denormalization in place on host F32 data by staging through the NVIDIA kernel.

func IdeogramLatentDenormBuffer

func IdeogramLatentDenormBuffer(x, scale, shift *Buffer, n, channels int) error

IdeogramLatentDenormBuffer applies per-channel latent denormalization in place on a GPU-resident F32 buffer laid out [tokens, channels].

func IdeogramLayerNormNoAffine

func IdeogramLayerNormNoAffine(out, x []float32, rows, cols int, eps float32) error

IdeogramLayerNormNoAffine computes row-wise non-affine LayerNorm using temporary device buffers. It is intended for correctness validation and early model wiring before the full Ideogram graph is GPU-resident.

func IdeogramLayerNormNoAffineBuffer

func IdeogramLayerNormNoAffineBuffer(out, x *Buffer, rows, cols int, eps float32) error

IdeogramLayerNormNoAffineBuffer computes row-wise non-affine LayerNorm on GPU-resident F32 buffers. x/out are row-major [rows, cols].

func IdeogramMRoPE

func IdeogramMRoPE(x, cosTable, sinTable []float32, tokens, heads, headDim int) error

IdeogramMRoPE applies precomputed MRoPE tables through temporary GPU buffers. It is a correctness/wiring wrapper for current CPU-slice DiT execution.

func IdeogramMRoPEBuffer

func IdeogramMRoPEBuffer(x, cosBuf, sinBuf *Buffer, tokens, heads, headDim int) error

IdeogramMRoPEBuffer applies precomputed Ideogram MRoPE tables to a GPU-resident row-major [tokens, heads, headDim] F32 tensor in place. cos/sin are [tokens, headDim/2].

func IdeogramRGBClamp

func IdeogramRGBClamp(out, in []float32, hw int) error

IdeogramRGBClamp converts CHW RGB F32 values in [-1,1] to interleaved RGB F32 values in [0,255] through the NVIDIA kernel.

func IdeogramRGBClampBuffer

func IdeogramRGBClampBuffer(outBuf, inBuf *Buffer, hw int) error

IdeogramRGBClampBuffer converts CHW RGB F32 values in [-1,1] to interleaved RGB F32 values in [0,255] on GPU-resident buffers.

func IdeogramRMSNormRows

func IdeogramRMSNormRows(out, x, weight, scale []float32, rows, cols int, eps float32) error

func IdeogramRMSNormRowsBuffer

func IdeogramRMSNormRowsBuffer(out, x, weight, scale *Buffer, rows, cols int, eps float32, useScale bool) error

func IdeogramRMSNormRowsNoWeightBuffer

func IdeogramRMSNormRowsNoWeightBuffer(out, x *Buffer, rows, cols int, eps float32) error

func IdeogramSplitQKVBuffer

func IdeogramSplitQKVBuffer(qkv, q, k, v *Buffer, tokens, emb int) error

func IdeogramUnpatchify

func IdeogramUnpatchify(out, tokens []float32, gridH, gridW, inChannels, latentChannels, patchH, patchW int) error

IdeogramUnpatchify converts token-major patchified latents to a CHW F32 map.

func IdeogramUpsampleNearest

func IdeogramUpsampleNearest(out, in []float32, c, h, w, factor int) error

IdeogramUpsampleNearest upsamples a CHW F32 feature map by nearest-neighbour.

func IdeogramUpsampleNearestBuffer

func IdeogramUpsampleNearestBuffer(outBuf, inBuf *Buffer, c, h, w, factor int) error

IdeogramUpsampleNearestBuffer upsamples a GPU-resident CHW F32 feature map.

func IndependentBranchAttentionBuffer

func IndependentBranchAttentionBuffer(out, q, trunkK, trunkV, suffixK, suffixV, active *Buffer, batch, branchSlots, trunkLen, suffixStride, seqStart, seqLen, nHeads, nKVHeads, headDim int, scale float32) error

IndependentBranchAttentionBuffer computes one query per branch over one shared trunk and a branch-local suffix arena. No branch can address another branch's suffix rows.

func Init

func Init() bool

Init attempts to load CUDA and initialize the GPU.

func InitAllKernels

func InitAllKernels()

InitAllKernels loads all GPU ptx. Call from the CUDA-owning thread.

func InitNativeBF16

func InitNativeBF16()

InitNativeBF16 loads native BF16 ptx. Call after mega module init.

func LaunchBatch

func LaunchBatch(commands []KernelLaunch) error

LaunchBatch validates every command before launching any, then enqueues in order on the current capture/default stream under one pinned driver scope. A driver error may follow earlier launches; callers must synchronise before freeing resources. An empty batch is a no-op. This does not synchronise on success unless the explicit diagnostic launch-check mode is enabled.

func LaunchKernel

func LaunchKernel(fn CUfunction, gridX, gridY, gridZ, blockX, blockY, blockZ uint32, sharedMem uint32, args ...unsafe.Pointer) error

LaunchKernel launches a CUDA kernel.

func LaunchKernelOnStream

func LaunchKernelOnStream(fn CUfunction, gridX, gridY, gridZ, blockX, blockY, blockZ, sharedMem uint32, stream CUstream, args ...unsafe.Pointer) error

LaunchKernelOnStream is like LaunchKernel but on a specific stream.

func LogitSoftcapF32

func LogitSoftcapF32(buf *Buffer, n int, cap float32) error

func MarkComputeDone

func MarkComputeDone()

MarkComputeDone records an event on the default (compute) stream.

func MemInfo

func MemInfo() (uint64, uint64)

MemInfo returns (free, total) GPU memory in bytes.

func MulWeights

func MulWeights(out, a, b *Buffer, n int) error

func NativeBF16Ready

func NativeBF16Ready() bool

func NativeNVFP4TensorCoreSupported

func NativeNVFP4TensorCoreSupported() bool

NativeNVFP4TensorCoreSupported reports whether the active CUDA device is new enough for native NVFP4 tensor-core work. Blackwell-class GPUs are expected to expose compute capability 10.x or newer. This is a capability gate only; the native kernel path remains disabled until implemented and validated.

func PrefetchWeights

func PrefetchWeights(weights ...*GPUQuantWeight)

PrefetchWeights launches a lightweight read kernel on the prefetch stream to warm L2 cache for the given GPU weight buffers.

func ProbeQ4UpstreamMMQ

func ProbeQ4UpstreamMMQ(out, x, raw *Buffer, batch, inDim, outDim int) error

ProbeQ4UpstreamMMQ runs a pinned upstream Q4_K tile for validation.

func ProjectQ4PairToBuffers

func ProjectQ4PairToBuffers(outA, outB, x *Buffer, batch int, a, b *GPUGGUFMatrix) error

ProjectQ4PairToBuffers quantises x once and projects it through two Q4_K matrices with identical input dimensions. Output dimensions may differ.

func Q4Ready

func Q4Ready() bool

Q4Ready returns true if the INT4 GPU kernel is available.

func RoPEPartialRowsBuffer

func RoPEPartialRowsBuffer(x, cosSin *Buffer, rows, pos, nHeads, headDim, rotHalf int) error

func RoPEPartialSequenceBuffer

func RoPEPartialSequenceBuffer(x, cosSin *Buffer, rows, pos0, nHeads, headDim, rotHalf int) error

RoPEPartialSequenceBuffer applies successive absolute positions to packed F32 rows without downloading Q/K. The launch uses u32 element indexing.

func SMCount

func SMCount() int

SMCount returns the number of streaming multiprocessors.

func ScatterWeightedRows

func ScatterWeightedRows(dst, src, pos *Buffer, weight float32, rows, hidden int) error

func ScatterWeightedRowsBatch

func ScatterWeightedRowsBatch(dst, src, pos, weights *Buffer, rows, hidden int) error

func SetStatsEnabled

func SetStatsEnabled(enabled bool) bool

func Sgemm

func Sgemm(M, N, K int, alpha float32, A, B, C *Buffer) error

func SgemmCompensated

func SgemmCompensated(M, N, K int, alpha float32, A, B, C *Buffer) error

SgemmCompensated is an opt-in accuracy-first F32 projection. It reduces cancellation/reduction drift without changing ordinary Sgemm numerics.

func SgemmHost

func SgemmHost(M, N, K int, alpha float32, A, B []float32) ([]float32, error)

SgemmHost computes C = alpha * A * B on GPU from host data. Handles upload, compute, download, and cleanup. A is [M,K], B is [K,N], C (output) is [M,N].

func SgemmReady

func SgemmReady() bool

SgemmReady returns true if GPU SGEMM is available.

func SgemmReg2

func SgemmReg2(M, N, K int, alpha float32, A, B, C *Buffer) error

SgemmReg2 explicitly selects the two-column candidate for a qualified caller. General Sgemm dispatch remains on the oracle kernel.

func Shutdown

func Shutdown()

Shutdown releases global CUDA-side resources so a fresh context can be created. Intended for a quiescent process owner only: stop/join all inference and release every encoder first. Per-driver locks cannot make global handle/cache teardown safe against arbitrary concurrent model execution.

func SoftmaxRowsBuffer

func SoftmaxRowsBuffer(out, in *Buffer, rows, cols int) error

SoftmaxRowsBuffer runs the existing NVIDIA row-softmax kernel over contiguous F32 rows. It is used by Ideogram full attention between score and value phases. in/out may be the same buffer.

func SplitGateUpBuffer

func SplitGateUpBuffer(src, gate, up *Buffer, batch, intermediate int) error

func Sync

func Sync()

Sync waits for all GPU operations to complete.

func SyncAll

func SyncAll()

SyncAll synchronizes both streams.

func SyncErr

func SyncErr() error

SyncErr waits for all GPU operations and reports CUDA driver errors.

func SyncForTiming

func SyncForTiming()

SyncForTiming waits for GPU operations before/after a timed section without incrementing GPU operation counters. Use this for profiling fences so the diagnostic sync counter reflects model work, not measurement overhead.

func UploadFP8E4M3LinearReuse

func UploadFP8E4M3LinearReuse(dst **GPUFP8E4M3Linear, weight []byte, scale []float32, bias []float32, outDim, inDim int) error

UploadFP8E4M3LinearReuse uploads into *dst, reusing existing GPU buffers when capacity allows. This is intended for later streamed Ideogram weights.

func UploadNVFP4WeightReuse

func UploadNVFP4WeightReuse(dst **GPUNVFP4Weight, qw *simdnvfp4.NVFP4Weight) error

UploadNVFP4WeightReuse uploads qw into *dst, reusing sufficiently large device buffers when possible. This is intended for transient streamed weights where dimensions change but allocation churn is more expensive than copies.

func UploadQ4KMatrixRowsInto

func UploadQ4KMatrixRowsInto(m *GPUQ4KMatrix, raw []byte, inDim, outDim int) error

func UploadQ5_0MatrixRowsInto

func UploadQ5_0MatrixRowsInto(m *GPUQ5_0Matrix, raw []byte, inDim, outDim int) error

func UploadQ8_0MatrixRowsInto

func UploadQ8_0MatrixRowsInto(m *GPUQ8_0Matrix, raw []byte, inDim, outDim int) error

func ValidateNVFP4KernelSpec

func ValidateNVFP4KernelSpec(spec NVFP4KernelSpec) error

ValidateNVFP4KernelSpec checks packed NVFP4 GEMV/GEMM dimensions without requiring GPU buffers. It is the shared shape gate for future native kernels.

func VecAddF32Buffer

func VecAddF32Buffer(a, b, out *Buffer, n int) error

func VecScaleF32Buffer

func VecScaleF32Buffer(src, out *Buffer, n int, scale float32) error

func WaitPrefetch

func WaitPrefetch()

WaitPrefetch makes the default stream wait for prefetch to complete.

func WhisperAttentionFullBuffer

func WhisperAttentionFullBuffer(out, q, k, v *Buffer, seqQ, seqKV, numHeads, headDim int, scale float32) error

func WhisperAttentionFullOnlineBuffer

func WhisperAttentionFullOnlineBuffer(out, q, k, v *Buffer, seqQ, seqKV, numHeads, headDim int, scale float32) error

WhisperAttentionFullOnlineBuffer launches the no-score-materialization candidate kernel. Keep the default dispatcher on WhisperAttentionFullBuffer unless this variant proves faster while staying within the current parity tolerance on live benchmarks.

func WhisperAttentivePoolBuffer

func WhisperAttentivePoolBuffer(out, h, attnW, attnB, v *Buffer, channels, length, attnDim int, vBias float32) error

func WhisperConv1DK3S1Buffer

func WhisperConv1DK3S1Buffer(out, in, weight, bias *Buffer, inChannels, inLength, outChannels, outLength int) error

func WhisperConv1DK3S2Buffer

func WhisperConv1DK3S2Buffer(out, in, weight, bias *Buffer, inChannels, inLength, outChannels, outLength int) error

func WhisperCrossAttentionBuffer

func WhisperCrossAttentionBuffer(out, q, k, v *Buffer, decLen, encLen, numHeads, headDim int, scale float32) error

func WhisperGELUTanhBuffer

func WhisperGELUTanhBuffer(x *Buffer, n int) error

WhisperGELUTanhBuffer applies the tanh GELU approximation in-place.

func WhisperMelSpectrogramBuffer

func WhisperMelSpectrogramBuffer(out, audio, window, filters *Buffer, numFrames, fftSize, hopLength, numMels, numBins int) error

WhisperMelSpectrogramBuffer launches the correctness-first fused Whisper mel PTX kernel over GPU-resident buffers. Output is mel-major [numMels,numFrames].

func WhisperRowAffineBuffer

func WhisperRowAffineBuffer(out, x, weight, bias *Buffer, rows, cols int) error

WhisperRowAffineBuffer computes out[row,col] = x[row,col]*weight[col]+bias[col].

func WhisperRowBiasBuffer

func WhisperRowBiasBuffer(x, bias *Buffer, rows, cols int) error

WhisperRowBiasBuffer adds bias[col] to each row in-place.

func WhisperTransposeBuffer

func WhisperTransposeBuffer(out, in *Buffer, rows, cols int) error

WhisperTransposeBuffer transposes row-major [rows,cols] into [cols,rows].

func WidenBF16Transpose

func WidenBF16Transpose(dst, src *Buffer, rows, cols int) error

WidenBF16Transpose expands compact row-major BF16 weights [rows,cols] into caller-owned F32 [cols,rows] scratch for the existing checked SGEMM path. No host copies, vocabulary projection, silent fallback or persistent F32 weight allocation occurs. Caller serialises scratch use and owns its buffers.

func ZeroFloat32Buffer

func ZeroFloat32Buffer(buf *Buffer, n int) error

ZeroFloat32Buffer clears the first n float32 elements of a device buffer.

Types

type AttentionSegment

type AttentionSegment struct{ Length, ParentStart, ParentLength int }

AttentionSegment optionally reads one earlier context before its own suffix. Parents must be complete, root-level segments; sibling branches stay isolated.

type AttentionSplitKVCandidate

type AttentionSplitKVCandidate struct {
	// contains filtered or unexported fields
}

AttentionSplitKVCandidate is an opt-in decode-attention candidate that keeps score materialization chunk-local. It is not part of the production DevAttention dispatcher.

The caller must not call RunOK again, or Free the candidate, until prior launches that used the candidate have completed on the default stream. Launches from one RunOK call are serialized together so the shared partial buffers cannot be interleaved across concurrent callers.

func NewAttentionSplitKVCandidate

func NewAttentionSplitKVCandidate() *AttentionSplitKVCandidate

func (*AttentionSplitKVCandidate) Free

func (c *AttentionSplitKVCandidate) Free()

func (*AttentionSplitKVCandidate) RunOK

func (c *AttentionSplitKVCandidate) RunOK(out, q, kCache, vCache *DevBuf, seqLen, nHeads, nKVHeads, headDim int, scale float32) bool

RunOK launches the split-KV decode-attention candidate using reusable scratch buffers owned by the candidate.

type Buffer

type Buffer struct {
	Ptr  CUdeviceptr
	Size int
}

Buffer holds GPU device memory.

func DequantTransposeFP8E4M3Linear

func DequantTransposeFP8E4M3Linear(w *GPUFP8E4M3Linear) (*Buffer, error)

func Malloc

func Malloc(n int) (*Buffer, error)

Malloc allocates GPU memory for n float32s.

func MallocBytes

func MallocBytes(n int) (*Buffer, error)

func UploadBF16LMHead

func UploadBF16LMHead(weightRaw []byte, vocab, h int) (*Buffer, error)

func (*Buffer) Download

func (b *Buffer) Download(data []float32) error

Download copies GPU data to host.

func (*Buffer) DownloadBytes

func (b *Buffer) DownloadBytes(data []byte) error

DownloadBytes copies raw GPU bytes to host.

func (*Buffer) Free

func (b *Buffer) Free()

Free retains the legacy signature. On driver failure the pointer remains owned, but callers needing error handling must use FreeChecked instead.

func (*Buffer) FreeChecked

func (b *Buffer) FreeChecked() error

FreeChecked releases device memory only after the driver confirms the free. A failed free keeps the handle for process-level diagnosis; it does not authorise a blind retry after device/context loss.

func (*Buffer) Upload

func (b *Buffer) Upload(data []float32) error

Upload copies host data to GPU.

func (*Buffer) UploadBytes

func (b *Buffer) UploadBytes(data []byte) error

UploadBytes copies raw host bytes to GPU. The destination buffer is sized in bytes even though Malloc takes float32-element slots.

func (*Buffer) UploadUint32

func (b *Buffer) UploadUint32(data []uint32) error

UploadUint32 copies host uint32 data to GPU without repacking. The destination buffer is still sized in 4-byte elements, so uint32 and float32 slices have the same byte footprint.

type CUcontext

type CUcontext uintptr

type CUdevice

type CUdevice int32

CUDA types

type CUdeviceptr

type CUdeviceptr uint64

type CUevent

type CUevent uintptr

CUevent handle

type CUfunction

type CUfunction uintptr

func LoadPTX

func LoadPTX(ptx string, kernelName string) (CUfunction, error)

LoadPTX loads a PTX module and returns a kernel function by name. The backing module is retained until Shutdown() so the function pointer stays valid.

type CUgraph

type CUgraph uintptr

CUgraph / CUgraphExec handles

type CUgraphExec

type CUgraphExec uintptr

type CUmodule

type CUmodule uintptr

type CUresult

type CUresult int32
const (
	CUDA_SUCCESS CUresult = 0
)

type CUstream

type CUstream uintptr

CUstream handle

type CapturedGraph

type CapturedGraph struct {
	// contains filtered or unexported fields
}

CapturedGraph holds an instantiated CUDA graph for replay.

func EndCapture

func EndCapture() (*CapturedGraph, error)

EndCapture stops capturing and instantiates the graph.

func (*CapturedGraph) Destroy

func (cg *CapturedGraph) Destroy()

Destroy frees graph resources.

func (*CapturedGraph) Launch

func (cg *CapturedGraph) Launch() error

Launch replays the captured graph on the default stream.

type CompiledKernel

type CompiledKernel struct {
	Fn        CUfunction
	Mod       CUmodule
	Name      string
	NumBufs   int
	GridDiv   int // grid = (N + GridDiv - 1) / GridDiv
	BlockSz   int
	SharedMem int
	// contains filtered or unexported fields
}

CompiledKernel is a cached compiled PTX kernel

func Compile

func Compile(spec *KernelSpec) (*CompiledKernel, error)

Compile compiles a KernelSpec into a PTX kernel and caches it.

func (*CompiledKernel) Destroy

func (k *CompiledKernel) Destroy()

func (*CompiledKernel) Launch

func (k *CompiledKernel) Launch(n int, bufs ...*Buffer) bool

Launch executes a compiled kernel with the given buffers and element count. It returns true only when the CUDA launch was accepted by the driver.

type DevBuf

type DevBuf struct {
	// contains filtered or unexported fields
}

DevBuf is a device-agnostic buffer that can live on CPU or GPU.

func NewDevBuf

func NewDevBuf(n int) *DevBuf

NewDevBuf creates a CPU buffer.

func NewDevBufFrom

func NewDevBufFrom(data []float32) *DevBuf

NewDevBufFrom wraps existing CPU data.

func NewDevBufGPU

func NewDevBufGPU(n int) (*DevBuf, error)

NewDevBufGPU allocates a GPU-only buffer without uploading zeroed CPU data. Its contents are undefined until overwritten by a GPU operation.

func (*DevBuf) Data

func (b *DevBuf) Data() []float32

Data returns CPU-side data (downloading from GPU if needed).

func (*DevBuf) EnsureGPU

func (b *DevBuf) EnsureGPU() error

EnsureGPU ensures GPU buffer exists without uploading CPU data.

func (*DevBuf) Free

func (b *DevBuf) Free()

Free releases owned GPU resources held by this buffer. CPU memory is left to Go; non-owning slice views do not free the parent pointer.

func (*DevBuf) GPUBuffer

func (b *DevBuf) GPUBuffer() *Buffer

GPUBuffer returns the underlying GPU buffer when present. Callers must ensure the DevBuf is GPU-resident before using the returned buffer.

func (*DevBuf) GPUPtr

func (b *DevBuf) GPUPtr() *Buffer

GPUPtr returns the GPU buffer, uploading if needed.

func (*DevBuf) Len

func (b *DevBuf) Len() int

Len returns element count.

func (*DevBuf) MarkDirty

func (b *DevBuf) MarkDirty()

MarkDirty marks CPU data as authoritative (will re-upload on next GPU access).

func (*DevBuf) MarkOnGPU

func (b *DevBuf) MarkOnGPU()

MarkOnGPU marks GPU data as authoritative after in-place GPU-side mutation.

func (*DevBuf) OnGPU

func (b *DevBuf) OnGPU() bool

OnGPU returns true if data is authoritatively on GPU.

func (*DevBuf) Slice

func (b *DevBuf) Slice(offset, n int) *DevBuf

Slice returns a DevBuf view into a sub-range [offset:offset+n] of this buffer. The slice shares CPU memory with the parent. GPU pointer is offset accordingly. The caller must not outlive the parent buffer.

func (*DevBuf) ToCPU

func (b *DevBuf) ToCPU()

ToCPU ensures data is on CPU. No-op if already there.

func (*DevBuf) ToGPU

func (b *DevBuf) ToGPU() error

ToGPU ensures data is on GPU. No-op if already there.

type Device

type Device int

Device represents where data lives.

const (
	CPU Device = iota
	GPU_DEVICE
)

type ExpertCachePolicy

type ExpertCachePolicy string

ExpertCachePolicy names the eviction policy used by ExpertPool.

const (
	ExpertCachePolicyLRU ExpertCachePolicy = "lru"
	ExpertCachePolicyLFU ExpertCachePolicy = "lfu"
)

func ParseExpertCachePolicy

func ParseExpertCachePolicy(name string) (ExpertCachePolicy, error)

ParseExpertCachePolicy normalizes a user-supplied expert cache policy name. The empty string defaults to LRU for backwards compatibility.

func (ExpertCachePolicy) String

func (p ExpertCachePolicy) String() string

type ExpertEntry

type ExpertEntry struct {
	ExpertID  int
	GateW     *GPUMLXWeight // gate projection [hidden → moe_inter]
	UpW       *GPUMLXWeight // up projection [hidden → moe_inter]
	DownW     *GPUMLXWeight // down projection [moe_inter → hidden]
	SizeBytes int64         // total VRAM used
}

ExpertEntry holds one expert's GPU-resident weights.

type ExpertPool

type ExpertPool struct {

	// Stats
	Hits   atomic.Uint64
	Misses atomic.Uint64
	Evicts atomic.Uint64
	// contains filtered or unexported fields
}

ExpertPool manages a fixed number of MoE expert weight sets on GPU. Experts are cached with configurable LRU/LFU eviction and hit/miss tracking.

func NewExpertPool

func NewExpertPool(slots int, budget *placement.BudgetManager) *ExpertPool

NewExpertPool creates a pool with the given number of GPU slots using the historical default LRU eviction policy.

func NewExpertPoolWithPolicy

func NewExpertPoolWithPolicy(slots int, budget *placement.BudgetManager, policy ExpertCachePolicy) *ExpertPool

NewExpertPoolWithPolicy creates a pool with the given number of GPU slots and eviction policy. Unsupported policy values fall back to LRU.

func (*ExpertPool) EvictLRU

func (p *ExpertPool) EvictLRU() *ExpertEntry

EvictLRU explicitly evicts the least-recently-used expert. Returns the evicted entry or nil if pool is empty.

func (*ExpertPool) Get

func (p *ExpertPool) Get(expertID int) *ExpertEntry

Get returns the cached expert, or nil if not present (miss). On hit, the expert is moved to the most-recently-used position and its whole- run use count/recency are updated.

func (*ExpertPool) Peek

func (p *ExpertPool) Peek(expertID int) *ExpertEntry

Peek returns the cached expert without changing hit/miss/eviction stats, use counts, recency, or LRU order. Use it for planning checks; use Get for actual expert use.

func (*ExpertPool) Policy

func (p *ExpertPool) Policy() ExpertCachePolicy

Policy returns the pool's configured eviction policy.

func (*ExpertPool) Put

func (p *ExpertPool) Put(entry *ExpertEntry) *ExpertEntry

Put adds an expert to the pool, evicting according to the configured policy if full. Returns the evicted entry (if any) so the caller can free its GPU resources.

func (*ExpertPool) Report

func (p *ExpertPool) Report() string

Report returns a human-readable summary.

func (*ExpertPool) Size

func (p *ExpertPool) Size() int

Size returns the number of currently cached experts.

func (*ExpertPool) Slots

func (p *ExpertPool) Slots() int

Slots returns the maximum number of expert slots.

type ExpertPoolReplayFixture

type ExpertPoolReplayFixture struct {
	Name       string
	GlobalKeys []int
	Layers     []int
}

ExpertPoolReplayFixture records a deterministic sequence of global expert-pool key lookups together with their source layer, so tests and benchmarks can replay the exact same route stream against different slot counts and cache policies.

func NewExpertPoolReplayFixture

func NewExpertPoolReplayFixture(name string, globalKeys []int, expertsPerLayer int) (ExpertPoolReplayFixture, error)

NewExpertPoolReplayFixture derives layer IDs from global pool keys using the production key layout layer*expertsPerLayer+expert.

func (ExpertPoolReplayFixture) Replay

Replay runs the fixture through the production expert-pool implementation using the historical default LRU policy.

func (ExpertPoolReplayFixture) ReplaySlots

func (f ExpertPoolReplayFixture) ReplaySlots(slotSizes ...int) ([]ExpertPoolReplayStats, error)

ReplaySlots replays the same fixture against multiple slot sizes in the caller-supplied order using the historical default LRU policy.

func (ExpertPoolReplayFixture) ReplaySlotsWithPolicy

func (f ExpertPoolReplayFixture) ReplaySlotsWithPolicy(policy ExpertCachePolicy, slotSizes ...int) ([]ExpertPoolReplayStats, error)

ReplaySlotsWithPolicy replays the same fixture against multiple slot sizes in the caller-supplied order using one cache policy.

func (ExpertPoolReplayFixture) ReplayWithPolicy

func (f ExpertPoolReplayFixture) ReplayWithPolicy(slots int, policy ExpertCachePolicy) (ExpertPoolReplayStats, error)

ReplayWithPolicy runs the fixture through the production expert-pool implementation using the caller-selected cache policy and dummy expert entries so the measured hit/miss/eviction behaviour matches the configured policy.

func (ExpertPoolReplayFixture) Validate

func (f ExpertPoolReplayFixture) Validate() error

Validate checks that the fixture can be replayed deterministically.

type ExpertPoolReplayLayerStats

type ExpertPoolReplayLayerStats struct {
	Layer    int
	Accesses int
	Hits     int
	Misses   int
}

ExpertPoolReplayLayerStats holds per-layer replay results for one slot size.

func (ExpertPoolReplayLayerStats) AccessShare

func (s ExpertPoolReplayLayerStats) AccessShare(totalAccesses int) float64

func (ExpertPoolReplayLayerStats) HitRate

func (s ExpertPoolReplayLayerStats) HitRate() float64

type ExpertPoolReplayStats

type ExpertPoolReplayStats struct {
	Fixture       string
	Policy        ExpertCachePolicy
	Slots         int
	Accesses      int
	UniqueExperts int
	Hits          int
	Misses        int
	Evictions     int
	Layers        []ExpertPoolReplayLayerStats
}

ExpertPoolReplayStats reports the aggregate and per-layer results from replaying one fixture against one slot count.

func (ExpertPoolReplayStats) HitRate

func (s ExpertPoolReplayStats) HitRate() float64

func (ExpertPoolReplayStats) Report

func (s ExpertPoolReplayStats) Report() string

Report formats a compact human-readable replay summary.

type GPUFP8E4M3Linear

type GPUFP8E4M3Linear struct {
	Weight      *Buffer // raw E4M3 bytes, padded to float32 allocation granularity
	Scale       *Buffer // F32, length 1 or OutDim
	Bias        *Buffer // optional F32, length OutDim
	OutDim      int
	InDim       int
	ScaleLen    int
	HasBias     bool
	WeightBytes int
}

GPUFP8E4M3Linear is a GPU-resident row-major [OutDim, InDim] F8_E4M3 linear weight with F32 per-tensor or per-row scale and optional F32 bias. It mirrors backends/simd/quant/fp8.Linear so Ideogram Qwen/DiT projections can move from CPU LUT GEMV to a CUDA kernel without changing tensor layout.

func UploadFP8E4M3Linear

func UploadFP8E4M3Linear(weight []byte, scale []float32, bias []float32, outDim, inDim int) (*GPUFP8E4M3Linear, error)

UploadFP8E4M3Linear uploads an F8_E4M3 row-major linear to GPU memory. Scale must be length 1 or OutDim; bias may be nil or OutDim.

func (*GPUFP8E4M3Linear) Free

func (w *GPUFP8E4M3Linear) Free()

type GPUGGUFMatrix

type GPUGGUFMatrix struct {
	QType  gguf.QuantType
	InDim  int
	OutDim int
	// contains filtered or unexported fields
}

GPUGGUFMatrix is a resident projection in one of the Go System One-admitted K formats.

func UploadGGUFMatrix

func UploadGGUFMatrix(m *gguf.QuantMatrix) (*GPUGGUFMatrix, error)

func (*GPUGGUFMatrix) Free

func (m *GPUGGUFMatrix) Free()

func (*GPUGGUFMatrix) ProjectBatchToBuffer

func (m *GPUGGUFMatrix) ProjectBatchToBuffer(out, x *Buffer, batch int) error

func (*GPUGGUFMatrix) ProjectSelectedBatch

func (m *GPUGGUFMatrix) ProjectSelectedBatch(x *Buffer, candidates [][]int) ([][]float32, error)

ProjectSelectedBatch computes only named vocabulary entries for each hidden row. IDs are validated on the host; scratch lives through the download fence.

func (*GPUGGUFMatrix) ProjectSelectedRows

func (m *GPUGGUFMatrix) ProjectSelectedRows(out, x, rows *Buffer, count int) error

func (*GPUGGUFMatrix) ResidentBytes

func (m *GPUGGUFMatrix) ResidentBytes() int

type GPUMLXWeight

type GPUMLXWeight struct {
	QWeight *Buffer // packed uint32 weights
	Scales  *Buffer // float32 scales
	Biases  *Buffer // float32 biases
	InDim   int
	OutDim  int
	Groups  int
	GroupSz int
	// Transposed for GPTQ kernel + correction buffer
	AsGPTQ     *GPUQuantWeight // transposed weights for fast GPTQ kernel
	Correction *Buffer         // [outDim * numGroups] f32: 8*scale+bias per group
}

GPUMLXWeight holds MLX quantized weight data on GPU.

func UploadMLXWeight

func UploadMLXWeight(weight []uint32, scales, biases []float32, inDim, outDim, groupSize int, wantNative bool) (*GPUMLXWeight, error)

UploadMLXWeight uploads MLX quantized weight to GPU VRAM. It can upload the GPTQ-transposed fast path, native MLX buffers, or both.

func UploadMLXWeightNative

func UploadMLXWeightNative(weight []uint32, scales, biases []float32, inDim, outDim, groupSize int) (*GPUMLXWeight, error)

UploadMLXWeightNative uploads only the native MLX buffers. Use this when the caller will use GemvMLXDirect and does not need the transposed GPTQ fast path.

func (*GPUMLXWeight) Free

func (w *GPUMLXWeight) Free()

Free releases GPU buffers owned by the MLX quantized weight.

type GPUNVFP4Weight

type GPUNVFP4Weight struct {
	Weight        *Buffer // raw U8 packed FP4 bytes, padded to float32 allocation granularity
	WeightScale   *Buffer // raw F8_E4M3 scale bytes, padded to float32 allocation granularity
	WeightScale2  float32
	InputScale    float32
	HasInputScale bool
	OutDim        int
	InDim         int
	Groups        int
	GroupSize     int
	WeightBytes   int
	ScaleBytes    int
}

GPUNVFP4Weight is the GPU-resident representation for ModelOpt/NVFP4 weights. It is deliberately separate from GPTQ/MLX upload structures because NVFP4 uses U8 packed FP4 weights plus F8_E4M3 per-block scales and scalar scale metadata, not affine INT4 or GPTQ group-index metadata.

func UploadNVFP4Weight

func UploadNVFP4Weight(qw *simdnvfp4.NVFP4Weight) (*GPUNVFP4Weight, error)

UploadNVFP4Weight uploads the observed NVFP4 packed representation to GPU memory without converting it to MLX/GPTQ. Kernel dispatch is added separately.

func (*GPUNVFP4Weight) Free

func (w *GPUNVFP4Weight) Free()

type GPUQ4KMatrix

type GPUQ4KMatrix struct {
	Q      *Buffer // GGUF packed bytes, or coalesced [outDim, inDim/32, 16]
	Scales *Buffer // [outDim, inDim/32]
	Mins   *Buffer // [outDim, inDim/32]
	InDim  int
	OutDim int
	// contains filtered or unexported fields
}

func UploadQ4KMatrixRaw

func UploadQ4KMatrixRaw(raw []byte, inDim, outDim int) (*GPUQ4KMatrix, error)

func UploadQ4KMatrixRows

func UploadQ4KMatrixRows(raw []byte, inDim, outDim int) (*GPUQ4KMatrix, error)

func UploadQ4KMatrixRowsCoalesced

func UploadQ4KMatrixRowsCoalesced(raw []byte, inDim, outDim int) (*GPUQ4KMatrix, error)

UploadQ4KMatrixRowsCoalesced preserves the Q4_K bit width while arranging each 32-value group contiguously for the Go System One DP4A kernels.

func (*GPUQ4KMatrix) Free

func (m *GPUQ4KMatrix) Free()

type GPUQ4KPointerTable

type GPUQ4KPointerTable struct {
	QPtrs     *Buffer // uint64 device pointers, one per active expert
	ScalePtrs *Buffer // uint64 device pointers, one per active expert
	MinPtrs   *Buffer // uint64 device pointers, one per active expert
	InDim     int
	OutDim    int
	Count     int
}

func UploadQ4KPointerTable

func UploadQ4KPointerTable(mats []*GPUQ4KMatrix) (*GPUQ4KPointerTable, error)

func (*GPUQ4KPointerTable) Free

func (t *GPUQ4KPointerTable) Free()

type GPUQ5_0Matrix

type GPUQ5_0Matrix struct {
	Q      *Buffer // packed low nibbles [outDim, inDim/32, 16]
	High   *Buffer // uint32 high-bit masks [outDim, inDim/32]
	Scales *Buffer // F32 scales [outDim, inDim/32]
	InDim  int
	OutDim int
}

func UploadQ5_0MatrixRows

func UploadQ5_0MatrixRows(raw []byte, inDim, outDim int) (*GPUQ5_0Matrix, error)

func (*GPUQ5_0Matrix) Free

func (m *GPUQ5_0Matrix) Free()

type GPUQ5_0PointerTable

type GPUQ5_0PointerTable struct {
	QPtrs     *Buffer
	HighPtrs  *Buffer
	ScalePtrs *Buffer
	InDim     int
	OutDim    int
	Count     int
}

func UploadQ5_0PointerTable

func UploadQ5_0PointerTable(mats []*GPUQ5_0Matrix) (*GPUQ5_0PointerTable, error)

func (*GPUQ5_0PointerTable) Free

func (t *GPUQ5_0PointerTable) Free()

type GPUQ8_0Matrix

type GPUQ8_0Matrix struct {
	Q      *Buffer // int8 bytes stored in device memory; Size is bytes
	Scales *Buffer // F32 scales [outDim, inDim/32]
	InDim  int
	OutDim int
}

func UploadQ8_0MatrixRows

func UploadQ8_0MatrixRows(raw []byte, inDim, outDim int) (*GPUQ8_0Matrix, error)

func (*GPUQ8_0Matrix) Free

func (m *GPUQ8_0Matrix) Free()

type GPUQ8_0PointerTable

type GPUQ8_0PointerTable struct {
	QPtrs     *Buffer // uint64 device pointers, one per active expert
	ScalePtrs *Buffer // uint64 device pointers, one per active expert
	InDim     int
	OutDim    int
	Count     int
}

func UploadQ8_0PointerTable

func UploadQ8_0PointerTable(mats []*GPUQ8_0Matrix) (*GPUQ8_0PointerTable, error)

func (*GPUQ8_0PointerTable) Free

func (t *GPUQ8_0PointerTable) Free()

type GPUQKMatrix

type GPUQKMatrix struct {
	Raw         *Buffer
	PackedQ     *Buffer
	PackedScale *Buffer
	PackedMin   *Buffer
	InDim       int
	OutDim      int
	BlockSize   int
	// contains filtered or unexported fields
}

GPUQKMatrix owns canonical row-major GGUF Q5_K or Q6_K bytes on the device.

func UploadQ5KMatrixRows

func UploadQ5KMatrixRows(raw []byte, inDim, outDim int) (*GPUQKMatrix, error)

func UploadQ6KMatrixRows

func UploadQ6KMatrixRows(raw []byte, inDim, outDim int) (*GPUQKMatrix, error)

func (*GPUQKMatrix) Free

func (m *GPUQKMatrix) Free()

type GPUQuantWeight

type GPUQuantWeight struct {
	QWeight *Buffer // [inDim/8, outDim] packed int32
	Scales  *Buffer // [numGroups, outDim] float32
	GIdx    *Buffer // [inDim] int32
	InDim   int
	OutDim  int
	Groups  int
}

GPUQuantWeight holds INT4 weights in GPU VRAM.

func UploadQuantWeight

func UploadQuantWeight(qweight, gIdx []int32, scales []float32, inDim, outDim int) (*GPUQuantWeight, error)

UploadQuantWeight uploads INT4 quantized weight to GPU VRAM.

func (*GPUQuantWeight) Free

func (w *GPUQuantWeight) Free()

Free releases GPU buffers owned by the quantized weight.

type KNode

type KNode struct {
	Op       KernelOp
	Inputs   []*KNode
	BufIdx   int     // buffer index for Load/Store ops
	ConstVal float32 // for KOpConst
	RegName  string  // assigned register (filled by codegen)
}

KNode represents a node in the kernel computation graph

type KernelLaunch

type KernelLaunch struct {
	Function    CUfunction
	Grid, Block [3]uint32
	SharedMem   uint32
	ArgCount    int
	Args        [8]uint64
	// contains filtered or unexported fields
}

KernelLaunch holds one launch and its owned scalar argument storage. Args are the bit patterns for at most eight by-value arguments, each at most 64 bits. Pointers use CUdeviceptr values; float32 uses math.Float32bits. This matches the little-endian CUDA driver ABI of the supported Linux amd64/arm64 hosts. Do not copy or mutate a launch while LaunchBatch is running. No device memory is owned by this structure; callers keep referenced buffers/modules alive.

type KernelOp

type KernelOp int

Op types for the kernel compiler

const (
	KOpLoad      KernelOp = iota // load from global memory (input)
	KOpStore                     // store to global memory (output)
	KOpAdd                       // a + b
	KOpMul                       // a * b
	KOpNeg                       // -a
	KOpSiLU                      // a * sigmoid(a)
	KOpScale                     // a * scalar
	KOpFMA                       // a*b + c
	KOpRsqrt                     // 1/sqrt(a)
	KOpSumReduce                 // sum reduction
	KOpMaxReduce                 // max reduction
	KOpExp                       // exp(a)
	KOpDiv                       // a / b
	KOpSub                       // a - b
	KOpConst                     // constant value
)

type KernelSpec

type KernelSpec struct {
	Name      string
	Nodes     []*KNode // computation graph in topological order
	NumBufs   int      // number of input/output buffers
	HasReduce bool     // needs shared memory for reduction
}

KernelSpec defines a fused kernel to compile

func FusedRMSNormElemSpec

func FusedRMSNormElemSpec() *KernelSpec

FusedRMSNormElemSpec: out = x * scale * weight (the per-element part of RMSNorm, after the reduction computes scale)

func FusedResidualAddSpec

func FusedResidualAddSpec() *KernelSpec

FusedResidualAddSpec: out = a + b (trivial but tests the compiler)

func FusedSiLUMulSpec

func FusedSiLUMulSpec() *KernelSpec

FusedSiLUMulSpec: out = silu(a) * b

type LaunchTimer

type LaunchTimer struct {
	// contains filtered or unexported fields
}

LaunchTimer owns a fixed CUDA event ring for bounded diagnostic timing on the default stream. It is not safe to copy. Close owners before global Shutdown. Events perturb short launches; results are diagnostic GPU timeline intervals, not a replacement for uninstrumented whole-request latency measurements.

func NewLaunchTimer

func NewLaunchTimer(capacity int) (*LaunchTimer, error)

NewLaunchTimer allocates one timing-enabled CUDA event per launch boundary. Capacity is diagnostic-only and bounded to keep event ownership simple.

func (*LaunchTimer) Close

func (lt *LaunchTimer) Close() error

Close synchronizes outstanding work, then destroys any remaining events. Destroy failures retain the surviving handles for a later retry.

func (*LaunchTimer) Measure

func (lt *LaunchTimer) Measure(commands []KernelLaunch) ([]float32, error)

Measure launches the commands on the default stream and returns one elapsed time in milliseconds per command.

type MLXSelectedExpertPersistentCandidate

type MLXSelectedExpertPersistentCandidate struct {
	// contains filtered or unexported fields
}

MLXSelectedExpertPersistentCandidate is an opt-in candidate launcher for the persistent selected-expert MLX projection PTX kernel.

The caller must not call Run again, or Free the candidate, until the prior launch has completed on the default stream (for example via Sync, SyncErr, or SyncForTiming).

Output is written as one contiguous row-major [len(workExperts), outDim] tile, where each row is weights[workExperts[i]] @ x.

Example
fmt.Println("set GO_PHERENCE_RUN_MLX_SELECTED_EXPERT_PERSISTENT=1 and run go test ./backends/nvidia/runtime -run TestMLXSelectedExpertPersistentLiveParity -count=1")
Output:
set GO_PHERENCE_RUN_MLX_SELECTED_EXPERT_PERSISTENT=1 and run go test ./backends/nvidia/runtime -run TestMLXSelectedExpertPersistentLiveParity -count=1

func NewMLXSelectedExpertPersistentCandidate

func NewMLXSelectedExpertPersistentCandidate() *MLXSelectedExpertPersistentCandidate

func (*MLXSelectedExpertPersistentCandidate) Free

func (*MLXSelectedExpertPersistentCandidate) Run

func (c *MLXSelectedExpertPersistentCandidate) Run(out, x *DevBuf, weights []*GPUMLXWeight, workExperts []uint32) error

type NVFP4KernelKind

type NVFP4KernelKind int

NVFP4KernelKind identifies the packed NVFP4 kernel family a caller wants. The interface is intentionally defined before native dispatch exists so the fallback and future tensor-core paths agree on dimensions and buffer layout.

const (
	NVFP4KernelGEMV NVFP4KernelKind = iota
	NVFP4KernelGEMM
)

type NVFP4KernelSpec

type NVFP4KernelSpec struct {
	Kind      NVFP4KernelKind
	OutDim    int
	InDim     int
	Batch     int
	Groups    int
	GroupSize int
}

NVFP4KernelSpec describes a packed NVFP4 multiply request.

Layout contract:

  • W is row-major [OutDim, InDim] packed as U8 [OutDim, InDim/2]
  • WeightScale is row-major F8_E4M3 [OutDim, InDim/GroupSize]
  • X is F32 row-major [Batch, InDim] for GEMM, or [1, InDim] for GEMV
  • Out is F32 row-major [Batch, OutDim]
  • GroupSize is currently required to be 16 for ModelOpt NVFP4 native paths

Native Blackwell/tensor-core dispatch can use this spec without changing the public fallback entry points.

type PTXModule

type PTXModule struct {
	// contains filtered or unexported fields
}

PTXModule owns a separately loaded module. Close must follow completion of its launches; the caller must not use returned functions afterwards. Global Shutdown also requires all such owners to have closed first.

func LoadPTXFunctions

func LoadPTXFunctions(ptx string, names []string) (*PTXModule, error)

LoadPTXFunctions loads one owned module for a fixed, nonempty function set. Failed construction unloads the module; no handle enters the global cache.

func (*PTXModule) Close

func (m *PTXModule) Close() error

func (*PTXModule) Function

func (m *PTXModule) Function(name string) CUfunction

type PTXResidentDriver

type PTXResidentDriver struct{ Operator *TrainingF32 }

func (*PTXResidentDriver) Accumulate

func (d *PTXResidentDriver) Accumulate(ctx context.Context, dst, a, b train.ResidentBuffer, n int, scale float32) error

func (*PTXResidentDriver) CompactEmbeddingAccumulate

func (d *PTXResidentDriver) CompactEmbeddingAccumulate(ctx context.Context, out, previous, compact, index train.ResidentBuffer, rows, width, vocabulary int, scale float32) error

func (*PTXResidentDriver) NewBoundTape

func (d *PTXResidentDriver) NewBoundTape(ctx context.Context, t train.Tape, parameters map[int]train.ResidentBuffer, maxBytes int64) (train.ResidentBoundTape, error)

func (*PTXResidentDriver) NewBuffer

func (d *PTXResidentDriver) NewBuffer(ctx context.Context, n int) (train.ResidentBuffer, error)

func (*PTXResidentDriver) NewReuseBoundTape

func (d *PTXResidentDriver) NewReuseBoundTape(ctx context.Context, tape train.Tape, bindings map[int]train.ResidentBuffer, maxBytes int64) (train.ResidentBoundTape, error)

func (*PTXResidentDriver) NewZeroBoundTape

func (d *PTXResidentDriver) NewZeroBoundTape(ctx context.Context, t train.Tape, parameters map[int]train.ResidentBuffer, maxBytes int64) (train.ResidentBoundTape, error)

func (*PTXResidentDriver) NormClip

func (d *PTXResidentDriver) NormClip(ctx context.Context, dst, a train.ResidentBuffer, elements int64, maxNorm float32) error

func (*PTXResidentDriver) NormMerge

func (d *PTXResidentDriver) NormMerge(ctx context.Context, dst, a, b train.ResidentBuffer, n int, previous int64, mode uint32) error

func (*PTXResidentDriver) NormStats

func (d *PTXResidentDriver) NormStats(ctx context.Context, dst, x train.ResidentBuffer, n int, nonnegative bool) error

func (*PTXResidentDriver) Update

func (d *PTXResidentDriver) Update(ctx context.Context, p, g, m, v, ema train.ResidentBuffer, n int, step train.AdamWStep) error

func (*PTXResidentDriver) UpdateScaled

func (d *PTXResidentDriver) UpdateScaled(ctx context.Context, p, g, m, v, ema, clip train.ResidentBuffer, n int, step train.AdamWStep) error

func (*PTXResidentDriver) ValidateAccumulate

func (d *PTXResidentDriver) ValidateAccumulate(ctx context.Context, dst, a, b train.ResidentBuffer, n int, scale float32) error

func (*PTXResidentDriver) ValidateCompactEmbeddingAccumulate

func (d *PTXResidentDriver) ValidateCompactEmbeddingAccumulate(ctx context.Context, out, previous, compact, index train.ResidentBuffer, rows, width, vocabulary int, scale float32) error

func (*PTXResidentDriver) ValidateHandoffTape

func (d *PTXResidentDriver) ValidateHandoffTape(ctx context.Context, t train.Tape, bindings map[int]train.ResidentBuffer, maxBytes int64) error

func (*PTXResidentDriver) ValidateNormClip

func (d *PTXResidentDriver) ValidateNormClip(ctx context.Context, dst, a train.ResidentBuffer, elements int64, maxNorm float32) error

func (*PTXResidentDriver) ValidateNormMerge

func (d *PTXResidentDriver) ValidateNormMerge(ctx context.Context, dst, a, b train.ResidentBuffer, n int, previous int64, mode uint32) error

func (*PTXResidentDriver) ValidateScaledUpdate

func (d *PTXResidentDriver) ValidateScaledUpdate(ctx context.Context, p, g, m, v, ema, clip train.ResidentBuffer, n int, step train.AdamWStep) error

func (*PTXResidentDriver) ValidateUpdate

func (d *PTXResidentDriver) ValidateUpdate(ctx context.Context, p, g, m, v, ema train.ResidentBuffer, n int, step train.AdamWStep) error

type SegmentedRows

type SegmentedRows struct {
	// contains filtered or unexported fields
}

SegmentedRows owns immutable per-row sequence starts, uploaded once and reused by every layer. Close only after all work using this plan has completed.

func NewBranchedRows

func NewBranchedRows(segments []AttentionSegment, prefix int) (*SegmentedRows, error)

func NewSegmentedRows

func NewSegmentedRows(lengths []int, prefix int) (*SegmentedRows, error)

func (*SegmentedRows) Attention

func (p *SegmentedRows) Attention(out, q, k, v, pk, pv *Buffer, window, heads, kvHeads, dim int, scale float32) error

func (*SegmentedRows) AttentionFromPrefix

func (p *SegmentedRows) AttentionFromPrefix(out, q, k, v, pk, pv *Buffer, base, window, heads, kvHeads, dim int, scale float32) error

AttentionFromPrefix reads a compacted sliding prefix while RoPE still uses the original absolute positions from the immutable plan.

func (*SegmentedRows) Close

func (p *SegmentedRows) Close()

func (*SegmentedRows) RoPE

func (p *SegmentedRows) RoPE(x, table *Buffer, heads, dim, rot int) error

type Stats

type Stats struct {
	KernelLaunches      uint64
	HostToDevice        uint64
	HostToDeviceBytes   uint64
	DeviceToHost        uint64
	DeviceToHostBytes   uint64
	DeviceToDevice      uint64
	DeviceToDeviceBytes uint64
	Mallocs             uint64
	MallocBytes         uint64
	Frees               uint64
	FreeBytes           uint64
	Syncs               uint64
}

func StatsSnapshot

func StatsSnapshot() Stats

type TrainingF32

type TrainingF32 struct {
	// contains filtered or unexported fields
}

TrainingF32 owns experimental training kernels, not model parameters. All buffers and this module must outlive launches. Methods synchronise before returning: an error may follow partial device mutation; recover a coherent checkpoint, never blindly replay the update. No CPU fallback is performed. Close retains a failed module for explicit recovery, matching PTXModule.

func NewTrainingF32

func NewTrainingF32() (*TrainingF32, error)

func (*TrainingF32) AdamW

func (op *TrainingF32) AdamW(parameter, gradient, m, v, ema *Buffer, n int, p train.AdamWStep) error

func (*TrainingF32) AdamWScaled

func (op *TrainingF32) AdamWScaled(parameter, gradient, m, v, ema, clip *Buffer, n int, p train.AdamWStep) error

AdamWScaled consumes clip[3] directly. The caller must first validate the completed clip diagnostics; no device readback or fallback occurs here.

func (*TrainingF32) AttentionBackward

func (op *TrainingF32) AttentionBackward(dst, q, k, v, prob, dy, aux *Buffer, rows, heads, dim, contextRows int, mode uint32, scale float32) error

AttentionBackward is one overwrite stage of causal attention differentiation. Buffer layouts and mode semantics are defined by training.AttentionShape. Aux remains a valid dense tensor when unused. No implicit masking/padding shortcut, RoPE application, atomic addition or CPU fallback occurs.

func (*TrainingF32) AttentionBackwardPass

func (op *TrainingF32) AttentionBackwardPass(dq, dk, dv, dp, ds, q, k, v, prob, dy *Buffer, rows, heads, dim, contextRows int, scale float32) error

AttentionBackwardPass validates all scratch/output/input ranges before any launch, then evaluates five ordered stages. All writes are disjoint. This wrapper synchronises each stage; resident launch fusion is a separate future optimisation, not a throughput claim. dQ/dK need inverse RoPE afterwards.

func (*TrainingF32) AttentionForward

func (op *TrainingF32) AttentionForward(dst, q, k, v, aux *Buffer, rows, heads, dim, contextRows int, mode uint32, scale float32) error

AttentionForward overwrites one causal score, probability or output tensor. Q/K/V are [S,H,D]; aux is distinct [H,S,S] scores(mode1)/probabilities(mode2) or owned scratch(mode0). Whole pass preflight belongs to tape/plan admission. Uncertain launches poison this operator; no retry/fallback occurs.

func (*TrainingF32) AttentionReady

func (op *TrainingF32) AttentionReady() bool

AttentionReady performs a host-only ownership check. It never Initialises CUDA or probes driver state. A live handle is not proof of device health.

func (*TrainingF32) Close

func (op *TrainingF32) Close() error

func (*TrainingF32) CompactEmbeddingAccumulate

func (op *TrainingF32) CompactEmbeddingAccumulate(out, previous, compact, index *Buffer, rows, width, vocabulary int, scale float32) error

func (*TrainingF32) EOS

func (op *TrainingF32) EOS(dst, x, labels *Buffer, n, active int, mode uint32, weight float32) error

func (*TrainingF32) EOSAdmission

func (op *TrainingF32) EOSAdmission(dst, hidden, weight, bias *Buffer, rows, width int) error

func (*TrainingF32) Embedding

func (op *TrainingF32) Embedding(dst, source, ids *Buffer, rows, width, vocabulary int, mode uint32) error

Embedding requires IDs or an occurrence index admitted by Tape.Validate; raw callers are responsible for content admission before dispatch.

func (*TrainingF32) GELU

func (op *TrainingF32) GELU(dst, x, seed *Buffer, n int, mode uint32) error

GELU applies tanh-approximate GELU or its input VJP. Inputs must keep the F32 cubic/intermediate derivative finite (|x|<=1e10 suffices). Raw buffers are not host-scanned. Native failures poison the operator; no retry/fallback.

func (*TrainingF32) LSDLoss

func (op *TrainingF32) LSDLoss(dst, prediction, desired, logvar *Buffer, channels int, mode uint32) error

func (*TrainingF32) LayerNormBackward

func (op *TrainingF32) LayerNormBackward(dst, xhat, inv, weight, dy *Buffer, rows, width int, mode uint32) error

func (*TrainingF32) LinearBackward

func (op *TrainingF32) LinearBackward(dst, x, w, dy *Buffer, m, k, n int, mode uint32) error

LinearBackward overwrites one destination (mode0=dX,1=dW,2=dBias). Read-only inputs may overlap; output may not overlap any input.

func (*TrainingF32) LinearDualBackward

func (op *TrainingF32) LinearDualBackward(dst, x, xt, w, gv, gt *Buffer, m, k, n int, mode uint32) error

func (*TrainingF32) LinearDualForward

func (op *TrainingF32) LinearDualForward(dst, x, xt, w, bias *Buffer, m, k, n int, mode uint32) error

func (*TrainingF32) ModDualBackward

func (op *TrainingF32) ModDualBackward(dst, a, at, b, bt, gv, gt *Buffer, n int, kind, mode uint32) error

func (*TrainingF32) ModDualForward

func (op *TrainingF32) ModDualForward(dst, a, at, b, bt *Buffer, n int, kind, mode uint32) error

func (*TrainingF32) NormDualBackward

func (op *TrainingF32) NormDualBackward(dst, x, xt, w, gv, gt, stats *Buffer, m, n int, kind, mode uint32) error

func (*TrainingF32) NormDualForward

func (op *TrainingF32) NormDualForward(dst, x, xt, w, bias, stats *Buffer, m, n int, kind, mode uint32, epsilon float32) error

func (*TrainingF32) NormStats

func (op *TrainingF32) NormStats(dst, x *Buffer, n int, nonnegative bool) error

NormStats writes (maximum, scaled-square-sum, invalid) per <=256-value chunk; optional nonnegative admission is used for second moments. Native failure poisons the operator; callers retain owners until coherent recovery.

func (*TrainingF32) ReLU

func (op *TrainingF32) ReLU(dst, x, seed *Buffer, n int, mode uint32) error

ReLU overwrites a disjoint forward/VJP vector. Raw inputs must be finite; seed is a real owned input even for forward. No implicit runtime/fallback.

func (*TrainingF32) RoPE

func (op *TrainingF32) RoPE(dst, x, table *Buffer, rows, heads, dim int, mode uint32) error

RoPE applies adjacent-pair forward or transpose rotation to owned F32 storage. Tables are caller-computed [rows,dim/2,2] cosine,sine values; no device trig approximation or CPU fallback is implicit. Any attempted launch/sync failure poisons this operator; caller must retain buffers and recover coherently.

func (*TrainingF32) Row

func (op *TrainingF32) Row(dst, a, b *Buffer, rows, width, parts, slot int, mode uint32) error

Row overwrites a gather/scatter, shared-scale multiply or row dot reduction.

func (*TrainingF32) SiLUBackward

func (op *TrainingF32) SiLUBackward(dst, x, dy *Buffer, n int) error

SiLUBackward writes the pre-activation derivative to distinct destination. Device exponential approximation is experimental, with no CPU fallback.

func (*TrainingF32) SiLUDualBackward

func (op *TrainingF32) SiLUDualBackward(dx, dt, x, xt, gv, gt *Buffer, n int) error

SiLUDualBackward returns both input adjoints for the analytic reverse-over-forward SiLU operation. Outputs overwrite disjoint buffers.

func (*TrainingF32) SiLUDualForward

func (op *TrainingF32) SiLUDualForward(dst, x, xt *Buffer, n int, mode uint32) error

func (*TrainingF32) TimeEmbedding

func (op *TrainingF32) TimeEmbedding(dst, frequency, time, gv, gt *Buffer, half int, mode uint32) error

func (*TrainingF32) Vector

func (op *TrainingF32) Vector(dst, a, b *Buffer, n, source, offset int, mode uint32, scale float32) error

type TrainingTape

type TrainingTape struct {
	// contains filtered or unexported fields
}

TrainingTape owns device tensors for a validated ordered flow tape. Transfers occur only at construction and requested outputs; each operation currently synchronises. Caller owns kernel modules and must retain them until Close. An uncertain device error retains all allocations, never blind free/retry.

func NewTrainingTape

func NewTrainingTape(op *TrainingF32, t train.Tape, maxBytes int64) (*TrainingTape, error)

func (*TrainingTape) Close

func (t *TrainingTape) Close() error

func (*TrainingTape) Run

func (t *TrainingTape) Run() ([][]float32, error)

Jump to

Keyboard shortcuts

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