moe

package
v0.1.0 Latest Latest
Warning

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

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

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

Documentation

Overview

Package moe provides Mixture-of-Experts routing, token permutation, grouped GEMM epilogues, NVFP4 expert weight streaming, Engram memory lookup, and Two-Batch Overlap (TBO) expert-parallel kernels.

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

Index

Examples

Constants

View Source
const MaxSmallM = 64

MaxSmallM is the maximum batch/token row count M admitted by SmallMMatMulBF16.

View Source
const MaxSupportedExperts = 256

MaxSupportedExperts is the maximum number of routed experts supported by BuildCompactWorklist.

Variables

This section is empty.

Functions

func ComputeCommSMPartition

func ComputeCommSMPartition(totalSMs int, commRatio float64, minCommSMs int) (commSMs int, computeSMs int, err error)

ComputeCommSMPartition partitions totalSMs into overlap communication SMs and compute SMs (totalSMs - commSMs), clamping commSMs to even CTA pairs in [minCommSMs, totalSMs-2].

func ComputeEngramMultipliers

func ComputeEngramMultipliers(maxNgramSize int, layerID int, seed int64) []int64

ComputeEngramMultipliers returns maxNgramSize deterministic positive odd multipliers for a given layerID and seed, matching DeepInfer's NgramHashMapping odd-multiplier construction.

func DecodeBF16

func DecodeBF16(bits uint16) float32

DecodeBF16 converts a bfloat16 bit pattern to float32 by zero-extending the low 16 mantissa bits.

Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	val := nnmoe.DecodeBF16(0x4000)
	fmt.Printf("%.1f\n", val)
}
Output:
2.0

func EmitEPKernelsCUDA

func EmitEPKernelsCUDA(n string, R, S, K, L, E, C, H int) string

EmitEPKernelsCUDA returns the peer table struct and the layout, dispatch, and combine CUDA C++ kernels with their inline launchers for an expert-parallel plan.

func EmitTBOMegakernelCUDA

func EmitTBOMegakernelCUDA(
	baseSrc, n string,
	totalCTAs, computeCTAs, dispatchCTAs, combineCTAs, c2cDoorbellCTAs, threadsPerCTA int,
	R, S, K, L, E, C, H int,
	enableC2CBool bool,
	coldTokenCrossover int,
	doorbellTimeoutNs uint64,
) string

EmitTBOMegakernelCUDA emits the persistent Two-Batch Overlap MoE CUDA C++ source.

func EncodeBF16

func EncodeBF16(f float32) uint16

EncodeBF16 converts a float32 value to IEEE 754 bfloat16 using round-to-nearest-even. NaN payloads are canonicalized to quiet NaN (0x7fc0).

Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	bits := nnmoe.EncodeBF16(1.5)
	fmt.Printf("0x%04x %.1f\n", bits, nnmoe.DecodeBF16(bits))
}
Output:
0x3fc0 1.5

func EngramGateCPU

func EngramGateCPU(
	query []float32,
	key []float32,
	value []float32,
	rmsQueryW []float32,
	rmsKeyW []float32,
	numTokens, hiddenDim int,
	eps float32,
) ([]float32, error)

EngramGateCPU computes DeepInfer's engram_gate on host:

  1. RMSNorm on query and key per token using rmsQueryW, rmsKeyW, and eps.
  2. Dot product scaled by 1 / sqrt(hiddenDim).
  3. Signed square-root sigmoid gate: alpha = sigmoid(sign(s) * sqrt(|s| + eps)).
  4. Gated value output: out[t, d] = alpha * value[t, d].

func EngramHashIndicesCPU

func EngramHashIndicesCPU(compressedIDs []int32, cuSeqlens []int32, spec EngramSpec) ([]int64, error)

EngramHashIndicesCPU computes causal n-gram XOR-multiplicative hash indices within each sequence boundary defined by cuSeqlens (preventing cross-sequence n-gram leakage by padding prefix positions < k with spec.PadID) and reduces each hash modulo spec.TablePrimes[n-2][h].

The returned slice has length len(compressedIDs) * (MaxNgramSize-1) * NumHeadsPerNgram, laid out in row-major [token, ngramOrder(2..MaxNgramSize), head] order.

func FusedEngramGateSource

func FusedEngramGateSource(hiddenDim int, eps float32) (string, error)

FusedEngramGateSource generates the NVRTC CUDA C++ source for engram_gate_kernel.

func Gather16

func Gather16(experts [][]float32, indices []int, width int) ([]float32, error)

Gather16 gathers expert-major rows using checked scalar indices. Vectorized uint4 lowering is admitted only when the byte alignment contract holds; tails use scalar loads.

func Gather16Checked

func Gather16Checked(experts [][]float32, indices []int, width, expertCount int) ([]float32, error)

Gather16Checked adds the routing-table bound required by generated kernels.

func GatherArtifact

func GatherArtifact(tile int, target string) (*kernel.Artifact, error)

GatherArtifact compiles the tile16 or tile32 gather for a physical CUDA target, preserving compiled resources and options. It requires NVRTC and CUDA headers but does not load or launch GPU work. Its ABI is expert, output and int32 route pointers, followed by int32 token count, width and expert count. Use GatherGeometry with the same tile for launch dimensions.

func GatherGeometry

func GatherGeometry(tokens, width, tile int) (grid, block [3]uint32, err error)

GatherGeometry returns the one-dimensional grid and block for GatherSource. It accounts for inactive columns at the end of each tile-aligned row and rejects dimensions outside the kernel's signed-int ABI or CUDA grid limit. The layouts of the actual input and output remain tightly packed; padding applies only to the logical thread schedule, not to tensor storage.

Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	grid, block, err := nnmoe.GatherGeometry(5, 33, 16)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(grid, block)
}
Output:
[2 1 1] [128 1 1]

func GatherScalarArtifact

func GatherScalarArtifact(target string) (*kernel.Artifact, error)

GatherScalarArtifact compiles GatherScalarSource with the same ABI as GatherArtifact. It requires NVRTC and CUDA headers but does not launch work.

func GatherScalarSource

func GatherScalarSource() string

GatherScalarSource emits a scalar reference alternative to GatherSource. Use the scalar entry from GatherCandidates for its unpadded launch geometry. It has the same ABI, routing bounds and tightly packed layouts as the tiled kernels and copies each output with a separate float32 load and store.

func GatherSource

func GatherSource(tile int) (string, error)

GatherSource emits a bounds-checked expert-major gather. uint4 loads are used only when both input and output groups are aligned. Each output has one writer; unaligned groups and tails use scalar loads. Each group of tile threads handles tile adjacent columns; the final group of each row may have inactive threads. Use GatherGeometry for the padded launch dimensions. Input and output must not overlap. Invalid expert routes leave output untouched.

func GroupedGEMMPsumCPU

func GroupedGEMMPsumCPU(a [][]float32, b [][]float32, psum [][]float32, cfg GroupedPsumGEMMConfig) ([][]float32, error)

GroupedGEMMPsumCPU computes per-expert grouped matrix multiplication D_g = ScaleD * (A_g * B_g) + psum_g, simulating Blackwell UMMA AccumulateInPsumLayout chained accumulation without intermediate zero-fill.

func LaunchChainedStepPipelineBF16

func LaunchChainedStepPipelineBF16(
	ctx context.Context,
	dev *cuda.Device,
	stream *cuda.Stream,
	target string,
	xNormBF16, wProjBF16, wVocabBF16 []uint16,
	mRows, kCols, vocabSize int,
) (projBF16 []uint16, tokenIDs []int32, maxLogits []float32, retErr error)

LaunchChainedStepPipelineBF16 executes SmallMMatMulBF16(xNormBF16, wProjBF16) -> on-device BF16 RNE conversion -> ProjArgmaxEpilogueBF16(lastRow, wVocabBF16) chained in GPU memory on a single stream without intermediate host roundtrips before synchronizing once at the end.

func LaunchProjArgmaxEpilogueBF16

func LaunchProjArgmaxEpilogueBF16(
	ctx context.Context,
	dev *cuda.Device,
	stream *cuda.Stream,
	target string,
	xBF16, wVocabBF16 []uint16,
	mRows, vocabSize, kCols int,
) (tokenIDs []int32, maxLogits []float32, retErr error)

LaunchProjArgmaxEpilogueBF16 compiles and launches ProjArgmaxEpilogueBF16Artifact on dev and stream, returning per-row greedy token IDs and maximum logits without materializing a dense logit matrix.

func LaunchProjSpecVerifyEpilogueBF16

func LaunchProjSpecVerifyEpilogueBF16(
	ctx context.Context,
	dev *cuda.Device,
	stream *cuda.Stream,
	target string,
	xBF16, wVocabBF16 []uint16,
	draftTokens []int32,
	vocabSize, kCols int,
) (acceptedCount int, bonusTokenID int32, targetTokens []int32, retErr error)

LaunchProjSpecVerifyEpilogueBF16 compiles and launches ProjSpecVerifyEpilogueBF16Artifact on dev and stream, verifying proposed draftTokens against greedy target argmax token IDs without materializing a dense logit matrix.

func LaunchProjTopKEpilogueBF16

func LaunchProjTopKEpilogueBF16(
	ctx context.Context,
	dev *cuda.Device,
	stream *cuda.Stream,
	target string,
	xBF16, wVocabBF16 []uint16,
	mRows, vocabSize, kCols, topK int,
) (topKIDs [][]int32, topKLogits [][]float32, retErr error)

LaunchProjTopKEpilogueBF16 compiles and launches ProjTopKEpilogueBF16Artifact on dev and stream, returning per-row top-K token IDs and logits without materializing a dense logit matrix.

func LaunchSharedInputMultiProjBF16

func LaunchSharedInputMultiProjBF16(
	ctx context.Context,
	dev *cuda.Device,
	stream *cuda.Stream,
	target string,
	xBF16 []uint16,
	weightsBF16 [][]uint16,
	mRows, kCols int,
	outDims []int,
) (_ [][]float32, retErr error)

LaunchSharedInputMultiProjBF16 compiles and launches SharedInputMultiProjBF16Artifact on dev and stream, returning the projected float32 outputs for each weight matrix in weightsBF16.

func LaunchSmallMMatMulBF16

func LaunchSmallMMatMulBF16(
	ctx context.Context,
	dev *cuda.Device,
	stream *cuda.Stream,
	target string,
	aBF16, bBF16 []uint16,
	mRows, nCols, kCols int,
) (_ []float32, retErr error)

LaunchSmallMMatMulBF16 compiles and launches SmallMMatMulBF16Artifact on dev and stream for 1 <= mRows <= MaxSmallM.

func MoEGateNoAuxTCCPU

func MoEGateNoAuxTCCPU(
	logits []float32,
	correctionBias []float32,
	biasVL []float32,
	tokenVisionMask []bool,
	cfg NoAuxTCGateConfig,
) (topkIds [][]int32, topkWeights [][]float32, err error)

MoEGateNoAuxTCCPU implements DeepInfer's noaux_tc MoE routing gate supporting "sigmoid" and "sqrtsoftplus" scoring, optional biasVL adjustment for vision tokens, group top-2 score summation to pick TopKGroup groups, TopK expert selection, and weight normalization scaled by RoutedScalingFactor.

func MoEWeightSchema

func MoEWeightSchema() (cudakernel.Schema, error)

MoEWeightSchema is the common ABI of both ordinary weight consumers. Pointer slots are naturally eight-byte aligned; pointed-to FP8 storage needs only byte alignment and FP32 storage needs four-byte alignment.

Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	schema, err := nnmoe.MoEWeightSchema()
	fmt.Println(len(schema.Params), schema.TotalParamBytes, err)
}
Output:
9 56 <nil>

func MoEWeightSource

func MoEWeightSource(kind MoEWeightConsumerKind) (source, entry string, err error)

MoEWeightSource returns the ordinary CUDA consumer and its declared entry. One thread computes each output neuron in increasing hidden-column order; scale multiplication follows the FP32 dot sum. Slab indexing preserves global layer holes. Compiler options must disable contraction to match this identity.

Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	_, entry, err := nnmoe.MoEWeightSource(nnmoe.MoEWeightSlabConsumer)
	fmt.Println(entry, err)
}
Output:
moe_weight_slab <nil>

func PartitionTBOCTAs

func PartitionTBOCTAs(totalCTAs int, computeUs, dispatchUs, combineUs float64, enableC2C bool) (computeCTAs, dispatchCTAs, combineCTAs int)

PartitionTBOCTAs partitions totalCTAs across Compute, FabricDispatch, and FabricCombine warpgroup CTAs in proportion to computeUs, dispatchUs, and combineUs. When totalCTAs >= 3, each role receives at least one CTA and computeCTAs + dispatchCTAs + combineCTAs == totalCTAs. When enableC2C is true and computeCTAs > 1, one CTA is shifted from Compute to Dispatch to host the dedicated Grace/Vera C2C cold-expert doorbell warpgroup.

func PrefillW256Artifact

func PrefillW256Artifact(target string) (*kernel.Artifact, error)

PrefillW256Artifact compiles the W=256 kernel for sm_100a or sm_121a. It requires NVRTC and CUDA headers but does not load or launch GPU work. Input values must be finite. FP32 accumulation may differ from a scalar reference by rounding; this kernel does not promise bitwise equivalence.

func PrefillW256Layouts

func PrefillW256Layouts(k, n int) ([3]layout.Tile, error)

PrefillW256Layouts returns row-major A, B, C layouts for PrefillW256Source. A and B contain IEEE binary16 values; C contains float32 values. Conversion and expert routing happen before this kernel and must be measured separately.

Example
tiles, err := PrefillW256Layouts(32, 48)
if err != nil {
	fmt.Println(err)
	return
}
for _, tile := range tiles {
	size, _ := tile.FootprintBytes()
	fmt.Println(size)
}
Output:
16384
3072
49152

func PrefillW256ScalarArtifact

func PrefillW256ScalarArtifact(target string) (*kernel.Artifact, error)

PrefillW256ScalarArtifact compiles an ordinary scalar alternative with the same matrix layouts and ABI as PrefillW256Artifact. Launch 256*N logical threads in a one-dimensional grid. It uses FP32 accumulation over FP16 inputs.

func PrefillW256Source

func PrefillW256Source() (string, error)

PrefillW256Source emits a 256-row FP16-input, FP32-output Tensor Core GEMM. Inputs are row-major A[256,K] and B[K,N]; output is row-major C[256,N]. K and N must be positive multiples of 16, pointers 32-byte aligned, and buffers nonoverlapping. Launch grid (N/16,4,1) with block (128,1,1). The caller must group independent tokens for one expert before launch. It includes cuda_fp16.h and mma.h and uses NVRTC's predefined size_t.

func ProjArgmaxEpilogueBF16

func ProjArgmaxEpilogueBF16(xBF16, wVocabBF16 []uint16, m, vocabSize, k int) ([]int32, []float32, error)

ProjArgmaxEpilogueBF16 computes the vocabulary projection X * W_vocab^T for xBF16 ([m, k]) and wVocabBF16 ([vocabSize, k]) and reduces each row online to its greedy token ID and maximum logit without materializing a dense [m, vocabSize] logit matrix.

Ties are broken deterministically in favor of the lowest vocabulary token ID.

Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	x := []uint16{
		nnmoe.EncodeBF16(1), nnmoe.EncodeBF16(2),
	}
	// Vocabulary of 3 tokens; tokens 1 and 2 tie at logit 4.0, lowest ID (1) wins.
	wVocab := []uint16{
		nnmoe.EncodeBF16(1), nnmoe.EncodeBF16(1),
		nnmoe.EncodeBF16(2), nnmoe.EncodeBF16(1),
		nnmoe.EncodeBF16(0), nnmoe.EncodeBF16(2),
	}
	ids, vals, err := nnmoe.ProjArgmaxEpilogueBF16(x, wVocab, 1, 3, 2)
	if err != nil {
		panic(err)
	}
	fmt.Printf("id=%d logit=%.1f\n", ids[0], vals[0])
}
Output:
id=1 logit=4.0

func ProjArgmaxEpilogueBF16Artifact

func ProjArgmaxEpilogueBF16Artifact(target string) (*kernel.Artifact, error)

ProjArgmaxEpilogueBF16Artifact compiles ProjArgmaxEpilogueBF16Source for target ("sm_90", "sm_90a", "sm_100a", or "sm_121a").

func ProjArgmaxEpilogueBF16Source

func ProjArgmaxEpilogueBF16Source() (source string, entry string)

ProjArgmaxEpilogueBF16Source returns the CUDA C++ source and entry symbol for the online vocabulary projection + argmax epilogue kernel corresponding to ProjArgmaxEpilogueBF16.

func ProjSpecVerifyEpilogueBF16

func ProjSpecVerifyEpilogueBF16(
	xBF16, wVocabBF16 []uint16,
	draftTokens []int32,
	vocabSize, kCols int,
) (acceptedCount int, bonusTokenID int32, targetTokens []int32, err error)

ProjSpecVerifyEpilogueBF16 evaluates the vocabulary projection [len(draftTokens)+1, kCols] x [vocabSize, kCols]^T in BF16/FP32 and verifies proposed draftTokens against greedy target argmax token IDs without materializing the dense [len(draftTokens)+1, vocabSize] logit matrix.

It returns acceptedCount in [0, len(draftTokens)], the bonus/correction token ID at row acceptedCount, and all [len(draftTokens)+1] greedy target token IDs.

Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	// 2 draft tokens + 1 bonus verification row (mRows = 3, kCols = 2, vocabSize = 3).
	x := []uint16{
		nnmoe.EncodeBF16(1), nnmoe.EncodeBF16(2), // row 0 -> greedy token 1
		nnmoe.EncodeBF16(0), nnmoe.EncodeBF16(3), // row 1 -> greedy token 2
		nnmoe.EncodeBF16(3), nnmoe.EncodeBF16(0), // row 2 -> greedy token 1
	}
	wVocab := []uint16{
		nnmoe.EncodeBF16(1), nnmoe.EncodeBF16(0), // token 0
		nnmoe.EncodeBF16(2), nnmoe.EncodeBF16(1), // token 1
		nnmoe.EncodeBF16(0), nnmoe.EncodeBF16(2), // token 2
	}
	// Draft proposes [1, 0]; token 0 matches (1 == 1), token 1 mismatches (0 != 2).
	accepted, bonus, targets, err := nnmoe.ProjSpecVerifyEpilogueBF16(x, wVocab, []int32{1, 0}, 3, 2)
	if err != nil {
		panic(err)
	}
	fmt.Printf("accepted=%d bonus=%d targets=%v\n", accepted, bonus, targets)
}
Output:
accepted=1 bonus=2 targets=[1 2 1]

func ProjSpecVerifyEpilogueBF16Artifact

func ProjSpecVerifyEpilogueBF16Artifact(target string) (*kernel.Artifact, error)

ProjSpecVerifyEpilogueBF16Artifact compiles ProjSpecVerifyEpilogueBF16Source for target ("sm_90", "sm_90a", "sm_100a", or "sm_121a").

func ProjSpecVerifyEpilogueBF16Source

func ProjSpecVerifyEpilogueBF16Source() (source string, entry string)

ProjSpecVerifyEpilogueBF16Source returns the CUDA C++ source and entry symbol for the online vocabulary projection + speculative draft verification epilogue kernel corresponding to ProjSpecVerifyEpilogueBF16.

func ProjTopKEpilogueBF16Artifact

func ProjTopKEpilogueBF16Artifact(target string) (*kernel.Artifact, error)

ProjTopKEpilogueBF16Artifact compiles ProjTopKEpilogueBF16Source for target ("sm_90", "sm_90a", "sm_100a", or "sm_121a").

func ProjTopKEpilogueBF16Source

func ProjTopKEpilogueBF16Source() (source string, entry string)

ProjTopKEpilogueBF16Source returns the CUDA C++ source and entry symbol for the online vocabulary projection + top-K epilogue kernel corresponding to ProjTopKEpilogueBF16.

func ResolveNumPhysicalExperts

func ResolveNumPhysicalExperts(numRoutedExperts, numRedundantExperts, epSize int) (int, error)

ResolveNumPhysicalExperts returns the total number of physical experts by adding numRedundantExperts to numRoutedExperts and rounding up to the next multiple of epSize. It returns an error if the result does not fit in an int.

func SharedInputMultiProjBF16

func SharedInputMultiProjBF16(xBF16 []uint16, weightsBF16 [][]uint16, outDims []int, m, k int) ([][]float32, error)

SharedInputMultiProjBF16 computes multiple BF16 linear projections Y_p = X * W_p^T from a single decoded shared input matrix X of row-major shape [m, k].

Each weight matrix weightsBF16[p] has row-major shape [outDims[p], k], and each returned output slice has row-major shape [m, outDims[p]]. Inner products use deterministic 8-lane pairwise tree accumulation with explicit K-tail and N-tail handling for arbitrary m, outDims[p], k >= 1.

Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	x := []uint16{
		nnmoe.EncodeBF16(1), nnmoe.EncodeBF16(2), nnmoe.EncodeBF16(3),
	}
	w0 := []uint16{
		nnmoe.EncodeBF16(1), nnmoe.EncodeBF16(0), nnmoe.EncodeBF16(1),
		nnmoe.EncodeBF16(0), nnmoe.EncodeBF16(2), nnmoe.EncodeBF16(0),
	}
	w1 := []uint16{
		nnmoe.EncodeBF16(2), nnmoe.EncodeBF16(1), nnmoe.EncodeBF16(0),
	}
	outs, err := nnmoe.SharedInputMultiProjBF16(x, [][]uint16{w0, w1}, []int{2, 1}, 1, 3)
	if err != nil {
		panic(err)
	}
	fmt.Printf("proj0=%v proj1=%v\n", outs[0], outs[1])
}
Output:
proj0=[4 4] proj1=[4]

func SharedInputMultiProjBF16Artifact

func SharedInputMultiProjBF16Artifact(target string) (*kernel.Artifact, error)

SharedInputMultiProjBF16Artifact compiles SharedInputMultiProjBF16Source for target ("sm_90", "sm_90a", "sm_100a", or "sm_121a").

func SharedInputMultiProjBF16Source

func SharedInputMultiProjBF16Source() (source string, entry string)

SharedInputMultiProjBF16Source returns the CUDA C++ source and entry symbol for the shared-input BF16 multi-projection kernel corresponding to SharedInputMultiProjBF16.

func SmallMMatMulBF16

func SmallMMatMulBF16(xBF16, wBF16 []uint16, m, n, k int) ([]float32, error)

SmallMMatMulBF16 computes Y = X * W^T for small token batches (1 <= m <= MaxSmallM), where xBF16 has row-major shape [m, k], wBF16 has row-major shape [n, k], and the returned slice has row-major shape [m, n].

Accumulation uses deterministic 8-lane block-tree reduction with explicit N-tile and K-tail handling for arbitrary positive n and k.

Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	x := []uint16{
		nnmoe.EncodeBF16(1), nnmoe.EncodeBF16(2),
		nnmoe.EncodeBF16(3), nnmoe.EncodeBF16(4),
	}
	w := []uint16{
		nnmoe.EncodeBF16(1), nnmoe.EncodeBF16(1),
		nnmoe.EncodeBF16(2), nnmoe.EncodeBF16(0),
	}
	out, err := nnmoe.SmallMMatMulBF16(x, w, 2, 2, 2)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%v\n", out)
}
Output:
[3 2 7 6]

func SmallMMatMulBF16Artifact

func SmallMMatMulBF16Artifact(target string) (*kernel.Artifact, error)

SmallMMatMulBF16Artifact compiles SmallMMatMulBF16Source for target ("sm_90", "sm_90a", "sm_100a", or "sm_121a").

func SmallMMatMulBF16Source

func SmallMMatMulBF16Source() (source string, entry string)

SmallMMatMulBF16Source returns the CUDA C++ source and entry symbol for the small-M BF16 matrix multiplication kernel corresponding to SmallMMatMulBF16.

func SqrtSoftplus

func SqrtSoftplus(x float32) float32

SqrtSoftplus computes sqrt(log(1 + exp(x))) with numerical stability for large positive inputs (returning sqrt(x) when x > 20).

Types

type CUDALowerAlignOpts

type CUDALowerAlignOpts struct {
	Name              string
	K, Experts, Local int
	Warps             int
	Params            []string
}

CUDALowerAlignOpts configures CUDALowerAlignOpts.CUDA.

func (CUDALowerAlignOpts) CUDA

func (a CUDALowerAlignOpts) CUDA() (string, error)

CUDA returns the kernel source (without [Prelude]), launched as one block of 32·Warps threads:

__global__ void Name(int tokens, ids, local_start, offsets, rows, slots)

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 CUDALowerExpertSumOpts

type CUDALowerExpertSumOpts struct {
	Name        string
	Width, K    int
	Y, Out, Acc CUDALowerDType
	Eps         float32
	PreNormed   bool
	Params      []string
}

CUDALowerExpertSumOpts configures CUDALowerExpertSumOpts.CUDA.

func (CUDALowerExpertSumOpts) CUDA

func (s CUDALowerExpertSumOpts) CUDA() (string, error)

CUDA returns the kernel source (without [Prelude]):

__global__ void Name(int tokens, y, ss, slots, weights, out)

type CUDALowerOperand

type CUDALowerOperand struct {
	Name      string
	DType     CUDALowerDType
	Broadcast CUDALowerBroadcast
}

CUDALowerOperand mirrors the cudalower epilogue extra Operand.

type CUDALowerScaleLayout

type CUDALowerScaleLayout uint8

CUDALowerScaleLayout mirrors the cudalower ScaleLayout enum.

func (CUDALowerScaleLayout) String

func (l CUDALowerScaleLayout) String() string

type CUDALowerStore

type CUDALowerStore uint8

CUDALowerStore mirrors the cudalower GEMMStore enum.

type CUDALowerTileEpilogue

type CUDALowerTileEpilogue uint8

CUDALowerTileEpilogue mirrors the cudalower TileEpilogue enum.

func (CUDALowerTileEpilogue) String

func (e CUDALowerTileEpilogue) String() string

type CUDALowerTopKOpts

type CUDALowerTopKOpts struct {
	Name       string
	D, K       int
	X, Bias    CUDALowerDType
	Score, Key string
	ScoreCUDA  func(string) (string, error)
	KeyCUDA    func(string, string) (string, error)
	Normalize  bool
	Eps, Scale float32
	Params     []string
}

CUDALowerTopKOpts configures CUDALowerTopKOpts.CUDA.

func (CUDALowerTopKOpts) CUDA

func (k CUDALowerTopKOpts) CUDA() (string, error)

CUDA returns the kernel source (without [Prelude]): __global__ void Name(int rows, x, [bias,] ids, weights).

type CUDALowerWeight

type CUDALowerWeight uint8

CUDALowerWeight mirrors the cudalower WeightFormat enum.

func (CUDALowerWeight) String

func (f CUDALowerWeight) String() string

type CompactWorklist

type CompactWorklist struct {
	NumExperts      int
	TopK            int
	TotalRoutes     int
	ActiveExperts   []int32
	ExpertOffsets   []int32
	SortedTokenIdx  []int32
	SortedSlotIdx   []int32
	MaxExpertLoad   int
	TileAssignments []ExpertTileAssignment
}

CompactWorklist holds a compacted, active-expert-only routing schedule and balanced tile assignments built by BuildCompactWorklist.

func BuildCompactWorklist

func BuildCompactWorklist(routeIDs []int32, tokens, topK, numExperts, tileTokens int) (*CompactWorklist, error)

BuildCompactWorklist builds a deterministic compact MoE worklist from row-major token route IDs of shape [tokens, topK].

It supports any 1 <= numExperts <= MaxSupportedExperts and 1 <= topK <= numExperts, validates that every route ID lies in [0, numExperts), omits zero-token experts from ActiveExperts, builds a prefix-sum offset table ExpertOffsets of length numExperts+1, orders routed entries by (expertID, tokenIdx, slotIdx), and splits heavily loaded experts (load > tileTokens) into balanced ExpertTileAssignment work items.

Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	// 4 tokens, topK=2 across 8 experts; expert 2 is hot (3 tokens) with tileTokens=2.
	routes := []int32{
		2, 5,
		0, 2,
		2, 5,
		5, 0,
	}
	wl, err := nnmoe.BuildCompactWorklist(routes, 4, 2, 8, 2)
	if err != nil {
		panic(err)
	}
	fmt.Printf("active=%v maxLoad=%d tiles=%d\n", wl.ActiveExperts, wl.MaxExpertLoad, len(wl.TileAssignments))
	for _, tile := range wl.TileAssignments {
		fmt.Printf("expert=%d start=%d count=%d\n", tile.ExpertID, tile.StartOffset, tile.TokenCount)
	}
}
Output:
active=[0 2 5] maxLoad=3 tiles=5
expert=0 start=0 count=2
expert=2 start=2 count=2
expert=2 start=4 count=1
expert=5 start=5 count=2
expert=5 start=7 count=1

type CompressedTokenizer

type CompressedTokenizer struct {
	NumCompressed int
	// contains filtered or unexported fields
}

CompressedTokenizer holds a surjective mapping from raw vocabulary token IDs onto canonical compressed token IDs by collapsing surface-equivalent token variants (compatibility width, case, and whitespace runs).

func NewCompressedTokenizer

func NewCompressedTokenizer(vocab []string) *CompressedTokenizer

NewCompressedTokenizer builds a CompressedTokenizer from vocab by grouping normalized token representations into equivalence classes in order of first appearance.

func (*CompressedTokenizer) CompressIDs

func (ct *CompressedTokenizer) CompressIDs(ids []int32) ([]int32, error)

CompressIDs maps raw vocabulary token IDs to their compressed canonical IDs.

type EPLBConfig

type EPLBConfig struct {
	NumRoutedExperts   int
	NumPhysicalExperts int
	EPSize             int
	Decay              float64
}

EPLBConfig configures the Expert Parallelism Load Balancer (EPLB).

type EPLBPlacement

type EPLBPlacement struct {
	PhysicalToLogical  []int32
	LogicalToPhysical  [][]int32
	ExpertReplicaCount []int32
	RankLoads          []float64
}

EPLBPlacement holds the bidirectional mapping between physical expert slots and logical routed experts across EP ranks.

func RebalanceExpertsGlobal

func RebalanceExpertsGlobal(loads []float64, cfg EPLBConfig) (EPLBPlacement, error)

RebalanceExpertsGlobal implements the two-phase global EPLB algorithm:

  1. Greedy replica assignment allocating redundant physical slots to logical experts with maximal load-per-replica (ties broken by lowest logical ID).
  2. Min-peak greedy rank packing sorting physical instances by descending effective weight (ties broken by lowest logical ID) and assigning each to the non-full rank with minimum cumulative load (ties broken by lowest rank index) while spreading replicas of the same logical expert across distinct ranks whenever possible.
Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	numPhys, err := nnmoe.ResolveNumPhysicalExperts(4, 2, 2)
	if err != nil {
		panic(err)
	}
	placement, err := nnmoe.RebalanceExpertsGlobal(
		[]float64{90, 30, 20, 10},
		nnmoe.EPLBConfig{
			NumRoutedExperts:   4,
			NumPhysicalExperts: numPhys,
			EPSize:             2,
		},
	)
	if err != nil {
		panic(err)
	}
	fmt.Printf("physical=%d replicas=%v rankLoads=[%.0f %.0f]\n",
		len(placement.PhysicalToLogical),
		placement.ExpertReplicaCount,
		placement.RankLoads[0],
		placement.RankLoads[1],
	)
}
Output:
physical=6 replicas=[3 1 1 1] rankLoads=[80 70]

type EPLBPolicy

type EPLBPolicy struct {
	Config EPLBConfig
}

EPLBPolicy wraps EPLBConfig and provides stateful or stateless expert load rebalancing across EP ranks.

func (EPLBPolicy) Rebalance

func (p EPLBPolicy) Rebalance(loads []float64) (EPLBPlacement, error)

Rebalance computes a new EPLBPlacement for loads using p.Config.

type EngramSpec

type EngramSpec struct {
	MaxNgramSize     int
	NumHeadsPerNgram int
	EmbedDimPerHead  int
	LayerID          int
	PadID            int32
	Seed             int64
	TablePrimes      [][]int64
	Multipliers      []int64
}

EngramSpec configures multi-order causal n-gram hash lookup.

type ExpertCacheManager

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

ExpertCacheManager manages hot in-memory experts and spills cold experts to NVMe SSD.

func NewExpertCacheManager

func NewExpertCacheManager(dir string, maxHot int) (*ExpertCacheManager, error)

NewExpertCacheManager creates an expert offloader and memory manager.

func (*ExpertCacheManager) Close

func (m *ExpertCacheManager) Close() error

Close releases resources.

func (*ExpertCacheManager) EvictColdExpert

func (m *ExpertCacheManager) EvictColdExpert(expertID int) error

EvictColdExpert spills an in-memory expert to secondary SSD storage.

func (*ExpertCacheManager) GetExpert

func (m *ExpertCacheManager) GetExpert(ctx context.Context, expertID int) ([]byte, error)

GetExpert retrieves an expert weight buffer, paging in from SSD if cold.

func (*ExpertCacheManager) RegisterExpert

func (m *ExpertCacheManager) RegisterExpert(expertID int, weights []byte)

RegisterExpert registers an expert's weight buffer into the cache.

type ExpertShufflePlan

type ExpertShufflePlan struct {
	LocalCopies    []LocalCopyOp
	P2PWaves       [][]P2PTransferStep
	ReplicaFills   []LocalCopyOp
	UpdatedMapping []int32
}

ExpertShufflePlan describes a zero-allocation expert weight shuffle across three ordered phases: intra-rank local copies, contention-free cross-rank P2P transfer waves, and intra-rank duplicate replica fills.

func PlanExpertShuffle

func PlanExpertShuffle(oldPhysicalToLogical []int32, newPhysicalToLogical []int32, epSize int) (ExpertShufflePlan, error)

PlanExpertShuffle computes the zero-allocation transition plan from oldPhysicalToLogical to newPhysicalToLogical across epSize ranks:

  1. Intra-rank local reuse where a logical expert already exists on the rank.
  2. Cross-rank P2P wave scheduling using circle-method round-robin pairing so every wave consists of disjoint rank pairs with zero contention.
  3. Final local replica fill for any duplicate slots on the same rank.
Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	oldMap := []int32{0, 1, 2, 3}
	newMap := []int32{1, 2, 2, 0}
	plan, err := nnmoe.PlanExpertShuffle(oldMap, newMap, 2)
	if err != nil {
		panic(err)
	}
	fmt.Printf("local=%d waves=%d fills=%d updated=%v\n",
		len(plan.LocalCopies),
		len(plan.P2PWaves),
		len(plan.ReplicaFills),
		plan.UpdatedMapping,
	)
}
Output:
local=1 waves=1 fills=0 updated=[1 2 2 0]

type ExpertTileAssignment

type ExpertTileAssignment struct {
	ExpertID    int32
	StartOffset int32
	TokenCount  int32
}

ExpertTileAssignment describes a contiguous slice of routed token-slot pairs assigned to a single expert execution tile in CompactWorklist.

type GatherCandidate

type GatherCandidate struct {
	Name        string
	Tile        int
	Grid, Block [3]uint32
	Layouts     [3]tilelayout.Tile
}

GatherCandidate describes one gather schedule. Layouts are expert data, output and routes in ABI pointer order. Data and output are row-major float32; routes are int32. Tile is zero for the scalar baseline and 16 or 32 for a vectorized tile. Each candidate needs separate, nonoverlapping buffers. Compiled resource requirements must be obtained from its artifact.

func GatherCandidates

func GatherCandidates(tokens, width, experts int) ([]GatherCandidate, error)

GatherCandidates returns scalar, tile16 and tile32 alternatives with checked launch geometry and buffer footprints. Routes must contain tokens indices in [0,experts); validation of their actual contents belongs to the caller. The kernels leave invalid routes untouched. Candidate order is not a performance ranking. Schedules exceeding the grid limit are omitted; valid scalar or smaller-tile alternatives remain available. This function allocates no tensor storage and performs no CUDA calls.

Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	candidates, err := nnmoe.GatherCandidates(5, 33, 3)
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, c := range candidates {
		fmt.Println(c.Name, c.Grid)
	}
}
Output:
gather_scalar [2 1 1]
gather16 [2 1 1]
gather32 [3 1 1]

type GroupedPsumGEMMConfig

type GroupedPsumGEMMConfig struct {
	Groups         int
	M              []int
	N              int
	K              int
	AccumulatePsum bool
	ScaleD         float32
}

GroupedPsumGEMMConfig configures per-expert grouped matrix multiplication with optional chained partial-sum (psum) accumulation.

type GroupedTopKRouter

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

GroupedTopKRouter computes bias-balanced grouped top-K routing.

Selection ranks experts by gate logit plus a per-expert load-balancing bias, but the returned weights are the softmax of the unbiased logits, so the bias steers which experts run without distorting how much each contributes.

func NewGroupedTopKRouter

func NewGroupedTopKRouter(cfg MoEConfig) (*GroupedTopKRouter, error)

NewGroupedTopKRouter creates a new MoE router. It requires at least one routed expert, 0 < TopK <= NumRoutedExperts, and NumSharedExperts >= 0, and it rejects sizes whose routing slices would exceed 1<<31 - 1 bytes.

func (*GroupedTopKRouter) Biases

func (r *GroupedTopKRouter) Biases() []float32

Biases returns a copy of the per-expert routing biases.

func (*GroupedTopKRouter) Route

func (r *GroupedTopKRouter) Route(gateLogits []float32) (RoutingDecision, error)

Route computes top-K expert selection with softmax weights. Experts with equal scores are ordered by index, so routing is reproducible across runs. len(gateLogits) must equal NumRoutedExperts, and every logit and bias must be finite. The router must come from NewGroupedTopKRouter; Route on the zero value returns an error.

func (*GroupedTopKRouter) SetBiases

func (r *GroupedTopKRouter) SetBiases(biases []float32) error

SetBiases replaces the per-expert routing biases. Balancing schemes nudge these between steps to spread load across experts. len(biases) must equal NumRoutedExperts.

type LocalCopyOp

type LocalCopyOp struct {
	Rank          int
	SrcLocalIdx   int
	DstLocalIdx   int
	LogicalExpert int32
}

LocalCopyOp describes an intra-rank expert weight copy between local slots.

type MoEConfig

type MoEConfig struct {
	NumRoutedExperts int // e.g. 256 for DeepSeek-V3, 64 for Qwen
	TopK             int // e.g. 8 routed experts
	NumSharedExperts int // e.g. 1 shared expert
	HiddenDim        int
	IntermediateDim  int
}

MoEConfig defines dimensional configuration for DeepSeek-V3 and Qwen MoE architectures.

type MoEWeightBorrowed

type MoEWeightBorrowed struct {
	Descriptor              MoEWeightDescriptor
	Shape                   MoEWeightShape
	WeightBytes, ScaleBytes uint64
}

MoEWeightBorrowed records the actual owner metadata accompanying a borrowed ready range. Shape.ActiveLayers is copied. Slab bytes are admitted allocation extents, not driver allocation granularity or peak memory. Metadata copies do not extend lifetime; the release callback returned by Borrow owns the pin.

type MoEWeightConsumer

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

MoEWeightConsumer owns a loaded ordinary kernel. Its zero value is closed. Execute and Wait are serialized; failed or canceled waits retain all read leases. Keep the device and stream live until Close succeeds.

func LoadMoEWeightConsumer

func LoadMoEWeightConsumer(dev *cuda.Device, kind MoEWeightConsumerKind, artifact *cudakernel.Artifact) (*MoEWeightConsumer, error)

LoadMoEWeightConsumer loads a trusted compilation artifact of MoEWeightSource. Its exact ABI, entry and tracked cudamoe_weight_storage.cu source digest must match. Receipt checks associate source; they do not authenticate a compiler or establish arbitrary machine-code semantics. The immutable descriptor is captured by value. Close every nonnil error result.

func (*MoEWeightConsumer) Close

func (c *MoEWeightConsumer) Close() error

Close drains pending work before unloading the owner module. Cleanup errors retain the remaining module or work for retry. Caller allocations are not freed.

func (*MoEWeightConsumer) Execute

func (c *MoEWeightConsumer) Execute(ctx context.Context, stream *cuda.Stream, view *MoEWeightView, input, output cuda.Slice[float32]) error

Execute reads one retained layer/expert using the specified consumer's addressing mode. Input has Hidden FP32 elements and output has Intermediate FP32 elements; their active ranges must be disjoint from each other and both slabs. Callers must exclude mutation, Free and other uses until Wait succeeds. A canceled or failed wait is incomplete work, not an admitted output.

func (*MoEWeightConsumer) Wait

func (c *MoEWeightConsumer) Wait(ctx context.Context) error

Wait retries a pending actual stream drain. A successful return releases consumer leases; cancellation or failure retains them for another attempt. After retry, callers must independently validate any device output.

Example
package main

import (
	"context"
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	var consumer *nnmoe.MoEWeightConsumer
	fmt.Println(consumer.Wait(context.Background()))
	fmt.Println(consumer.Close())
}
Output:
<nil>
<nil>

type MoEWeightConsumerKind

type MoEWeightConsumerKind int

MoEWeightConsumerKind distinguishes a retained range pointer from global slab addressing. Both kernels compute SiLU(gate matvec) times up matvec in FP32. Decoding E4M3FN storage is manual; neither path uses Tensor Cores.

const (
	MoEWeightViewConsumer MoEWeightConsumerKind = iota + 1
	MoEWeightSlabConsumer
)

type MoEWeightDescriptor

type MoEWeightDescriptor struct {
	Device                              *cuda.Device
	WeightBase, ScaleBase               driver.DevicePtr
	WeightOffsetBytes, ScaleOffsetBytes uint64
	Layer, Expert, Intermediate, Hidden int
	Generation                          uint64
	Format                              string
}

MoEWeightDescriptor describes a retained device range. It is metadata, not an ownership transfer: keep its originating view live through every actual read. Format is e4m3fn-gate-up-interleave8-v1 with FP32 scales and global indices.

type MoEWeightShape

type MoEWeightShape struct {
	Layers, Experts, Intermediate, Hidden int
	ActiveLayers                          []int
}

MoEWeightShape describes a global-layer-indexed E4M3FN up-projection slab. Each expert has Intermediate gate rows followed by Intermediate up rows in its logical input. Storage interleaves eight gate rows with eight up rows; the same permutation applies to its FP32 per-row scales. ActiveLayers lists readable global layer indices. Other layers reserve space but are unreadable.

type MoEWeightStorage

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

MoEWeightStorage owns exactly two device allocations: one E4M3FN weight slab and one FP32 scale slab. It must not be copied. Its zero value is closed. The device must stay live until Close succeeds. Views retain both allocations; Close refuses while any view or asynchronous consumer retains them.

func NewMoEWeightStorage

func NewMoEWeightStorage(dev *cuda.Device, shape MoEWeightShape) (*MoEWeightStorage, error)

NewMoEWeightStorage allocates the two slabs without loading any readable ranges. Even an error may return an owner retaining an allocation; callers must Close every nonnil result. Shape metadata is copied. No BF16 placeholder, per-layer device allocation or per-session copy is made.

func (*MoEWeightStorage) Close

func (s *MoEWeightStorage) Close() error

Close frees each base allocation through cudamem after all retained readers are released. Failure preserves unfinished allocations for a later retry.

func (*MoEWeightStorage) Load

func (s *MoEWeightStorage) Load(layer, expert int, weights, scales io.Reader) error

Load fills one active global layer/expert from logical half-split weights and little-endian FP32 scales. Each reader supplies exactly the declared range; subsequent bytes are not consumed. Both payloads are staged and validated before copying. Only completion of both synchronous copies publishes readiness. Any failed load invalidates its generation. Retained ranges cannot be rewritten.

func (*MoEWeightStorage) Stats

Stats returns the cumulative base allocation ledger, including partial construction. AllocatedBytes counts requests with a nonnil allocation owner, not a queried driver allocation granularity or the current live-byte count.

Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	var storage *nnmoe.MoEWeightStorage
	fmt.Println(storage.Stats())
	fmt.Println(storage.Close())
}
Output:
{0 0 0}
<nil>

func (*MoEWeightStorage) View

func (s *MoEWeightStorage) View(layer, expert int) (*MoEWeightView, error)

View acquires a ready range without copying or allocating any base weights. Padded layers and ranges whose loading generation failed are refused.

type MoEWeightStorageStats

type MoEWeightStorageStats struct {
	RequestedBytes, AllocatedBytes uint64
	BaseAllocations                int
}

MoEWeightStorageStats records this owner's base allocation requests and admitted bytes. It excludes host loading buffers, CUDA allocation granularity, consumer outputs and allocator peak RSS. Creating views changes none of it.

type MoEWeightView

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

MoEWeightView retains an immutable, ready layer/expert range. Its zero value is closed. Copies of the pointer share the same lifetime. Close releases only this retention; it never frees either base allocation.

func (*MoEWeightView) Borrow

func (v *MoEWeightView) Borrow(dev *cuda.Device) (MoEWeightBorrowed, func(), error)

Borrow retains this view's ready generation for a consumer on dev. The returned descriptor is copied, and release is safe to call more than once. Closing the public view does not release this independent retention. Call release only after the consumer's actual device work has completed.

Example
package main

import (
	"fmt"
	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	var view *nnmoe.MoEWeightView
	_, release, err := view.Borrow(nil)
	fmt.Println(release == nil, err != nil)
}
Output:
true true

func (*MoEWeightView) Close

func (v *MoEWeightView) Close() error

Close releases this view's retention once. Consumer retentions are independent and must remain held until their real device completion, even after this call.

func (*MoEWeightView) Descriptor

func (v *MoEWeightView) Descriptor() (MoEWeightDescriptor, error)

Descriptor returns copied metadata while this view retains its range.

type NoAuxTCGateConfig

type NoAuxTCGateConfig struct {
	NumExperts          int
	NumGroups           int
	TopKGroup           int
	TopK                int
	ScoringFunc         string
	RoutedScalingFactor float32
	UseBiasVL           bool
}

NoAuxTCGateConfig configures the auxiliary-loss-free token-choice MoE gate.

type P2PTransferStep

type P2PTransferStep struct {
	RankA         int
	SlotA         int
	ExpertA       int32
	RankB         int
	SlotB         int
	ExpertB       int32
	Bidirectional bool
}

P2PTransferStep describes a cross-rank point-to-point expert weight transfer within a contention-free communication wave.

type ProjTopKResult

type ProjTopKResult struct {
	TokenIDs []int32
	Values   []float32
}

ProjTopKResult holds the top-K vocabulary token IDs and their corresponding projection logits for a single token row from ProjTopKEpilogueBF16.

func ProjTopKEpilogueBF16

func ProjTopKEpilogueBF16(xBF16, wVocabBF16 []uint16, m, vocabSize, k, topK int) ([]ProjTopKResult, error)

ProjTopKEpilogueBF16 computes the vocabulary projection X * W_vocab^T for xBF16 ([m, k]) and wVocabBF16 ([vocabSize, k]) and maintains a per-row bounded top-K candidate buffer online without materializing a dense [m, vocabSize] logit matrix.

Returned candidates for each row are ordered by descending logit, breaking ties in favor of the lowest vocabulary token ID.

Example
package main

import (
	"fmt"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	x := []uint16{
		nnmoe.EncodeBF16(1), nnmoe.EncodeBF16(2),
	}
	wVocab := []uint16{
		nnmoe.EncodeBF16(1), nnmoe.EncodeBF16(1),
		nnmoe.EncodeBF16(2), nnmoe.EncodeBF16(1),
		nnmoe.EncodeBF16(0), nnmoe.EncodeBF16(2),
	}
	res, err := nnmoe.ProjTopKEpilogueBF16(x, wVocab, 1, 3, 2, 2)
	if err != nil {
		panic(err)
	}
	fmt.Printf("ids=%v vals=%v\n", res[0].TokenIDs, res[0].Values)
}
Output:
ids=[1 2] vals=[4 4]

type RepeatedDispatchDecision

type RepeatedDispatchDecision struct {
	UseCandidate     bool
	Trials           int
	BaselineMedian   time.Duration
	CandidateMedian  time.Duration
	Speedup          float64
	CandidateWins    int
	BoundaryIDsMatch bool
	Reason           string
}

RepeatedDispatchDecision summarizes a repeated-measure enclosing-boundary dispatch evaluation produced by SelectRepeatedMeasuredDispatch.

func SelectRepeatedMeasuredDispatch

func SelectRepeatedMeasuredDispatch(
	baselineSamples, candidateSamples []time.Duration,
	wantIDs, gotIDs []int32,
	maxLogitDiff, maxLogitTol float32,
) RepeatedDispatchDecision

SelectRepeatedMeasuredDispatch evaluates whether a candidate fused/epilogue kernel path should replace a baseline path across an enclosing decode or prefill boundary.

UseCandidate is true only when wantIDs and gotIDs are non-empty and identical at every position, maxLogitDiff <= maxLogitTol, at least 3 paired timing trials are provided with positive durations, CandidateMedian < BaselineMedian, and the candidate wins a strict majority of paired trials (CandidateWins > Trials/2).

Example
package main

import (
	"fmt"
	"time"

	nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
)

func main() {
	baseline := []time.Duration{120 * time.Microsecond, 118 * time.Microsecond, 122 * time.Microsecond}
	candidate := []time.Duration{95 * time.Microsecond, 96 * time.Microsecond, 94 * time.Microsecond}
	wantIDs := []int32{42, 7, 19}
	gotIDs := []int32{42, 7, 19}

	dec := nnmoe.SelectRepeatedMeasuredDispatch(baseline, candidate, wantIDs, gotIDs, 1e-4, 1e-3)
	fmt.Printf("use=%v wins=%d/%d match=%v\n", dec.UseCandidate, dec.CandidateWins, dec.Trials, dec.BoundaryIDsMatch)
}
Output:
use=true wins=3/3 match=true

type RoutingDecision

type RoutingDecision struct {
	SelectedExperts []int
	Weights         []float32
	HasShared       bool
}

RoutingDecision holds selected expert indices and normalized softmax weights for a single token.

type TBOWarpgroupRole

type TBOWarpgroupRole uint8

TBOWarpgroupRole identifies the specialization of a CTA or warpgroup inside a Two-Batch Overlap (TBO) persistent MoE megakernel.

const (
	// WarpgroupRoleCompute runs Microbatch A's grouped NVFP4 Expert
	// (W13+SwiGLU+W2) and Shared GEMMs on Tensor Cores.
	WarpgroupRoleCompute TBOWarpgroupRole = iota

	// WarpgroupRoleFabricDispatch runs Microbatch B's Route, Layout, and
	// All-to-All Dispatch over NVLink / RDMA fabric.
	WarpgroupRoleFabricDispatch

	// WarpgroupRoleFabricCombine runs Microbatch A-1's All-to-All Combine,
	// weighted expert accumulation, and shared-expert residual fusion.
	WarpgroupRoleFabricCombine

	// WarpgroupRoleC2CDoorbell signals and polls the Grace/Vera coherent
	// NVLink-C2C doorbell for cold local experts whose routed token count
	// falls in 1..ColdTokenCrossover.
	WarpgroupRoleC2CDoorbell
)

func (TBOWarpgroupRole) String

func (r TBOWarpgroupRole) String() string

Directories

Path Synopsis
Package ep implements a single-host and loopback Mixture-of-Experts (MoE) expert-parallel router with rank-deduped all-to-all dispatch and combine, capacity-factor overflow policies, and live Expert Parallelism Load Balancer (EPLB) weight shuffling.
Package ep implements a single-host and loopback Mixture-of-Experts (MoE) expert-parallel router with rank-deduped all-to-all dispatch and combine, capacity-factor overflow policies, and live Expert Parallelism Load Balancer (EPLB) weight shuffling.
Package mxfp8gemm multiplies MXFP8 matrices group by group, as a mixture-of-experts layer does, on the tensor cores of sm_100a and sm_103a: each group of rows of x, the tokens routed to one expert, by that expert's weights.
Package mxfp8gemm multiplies MXFP8 matrices group by group, as a mixture-of-experts layer does, on the tensor cores of sm_100a and sm_103a: each group of rows of x, the tokens routed to one expert, by that expert's weights.

Jump to

Keyboard shortcuts

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