sample

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: 9 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 sample provides GPU token-sampling kernels including argmax, temperature scaling, top-k, top-p (nucleus), min-p, and Philox Gumbel-max.

SampleArgmaxCPU selects a token from host logits without loading CUDA. It ignores NaNs, selects the first maximum on ties, and returns -1 when no value exceeds negative infinity.

Compile uses NVRTC to compile ArgmaxKernelTemplate for a specified compute capability. It returns a compiled artifact; callers must load it into their CUDA context and launch ArgmaxLogits themselves. The kernel takes a float32 logits pointer, an int32 output pointer, and an int32 vocabulary size. Launch ArgmaxBlocks blocks of ArgmaxBlockDim threads, keep both buffers alive through completion, and synchronize before reading the output on the host. The blocks combine their results through scratch in the loaded module, so launches of one module must not overlap; a launch is one kernel node and can be captured in a CUDA graph.

CompileArgmax compiles ArgmaxSource for an ArgmaxConfig. With Fault set, ArgmaxLogits takes an int32 fault word as a fourth argument and sets kernel.FaultNonFinite in it when a logit is NaN or ±Inf; the token it writes is unchanged. With Rows set, the kernel is ArgmaxLogitsRows, which takes a batch of rows, one per grid row, and writes a token for each. The zero config is ArgmaxKernelTemplate.

Sampling

CompileSampler compiles SamplerKernelSource, whose SampleRows kernel draws one token for each row of a batch whose SampleRowParams has a temperature above 0, and leaves the other rows' tokens as the argmax wrote them. It runs as SamplePasses launches of a grid of SampleBlocks(vocab) by rows blocks, with every parameter in device memory, so the launches can be captured in a CUDA graph once and replayed for any mix of parameters. SampleSeededCPU is its reference.

For row r, with value v_i = logit_i (times x_scale[r]*w_scale[i] when the FP8 scales are given), NaNs and negative infinities excluded, the probability of token i is proportional to exp((v_i - max v)/T) over the tokens that pass three filters, each applied to the whole distribution:

  • top_k > 0 keeps the tokens with fewer than top_k tokens of larger value;
  • 0 < top_p < 1 keeps the tokens whose larger-valued tokens hold at most top_p of the probability;
  • min_p > 0 keeps the tokens of probability at least min_p times the largest.

Each filter is a threshold on the value, so tokens of equal value pass or fail together: ties at a boundary are kept. The top token always passes. This is SGLang's joint top-k/top-p rule, except that SGLang breaks boundary ties by sort order.

The draw is the Gumbel-max trick: the token of largest (v_i - max v)/T - log(-log(u_i)), lowest index on ties, where u_i is PhiloxUniformFloat32(seed, step, i). The kernel finds the thresholds by an exact radix select whose probability masses are integers in units of 2^-40 of the top token's, so they sum to the same totals in any order.

Determinism

A row's token is a function of its logits, its scales and its (seed, step, T, top_k, top_p, min_p) only. It does not depend on the row's position in the batch, on the other rows, or on the order in which blocks run, and the same inputs give the same token on every run. Two requests with the same seed draw the same tokens from the same logits. The logits themselves can change with batch composition, since a projection's kernel and summation order can depend on the batch size; so same seed and same batch composition give the same tokens.

The kernel and SampleSeededCPU agree token for token except where the last bit of an exp or log decides a near tie in the Gumbel scores or a top-p boundary; the device's expf and logf may round differently from the host's.

SampleSeededCPU, SampleBatchSeededCPU, and VerifySpeculativeSeededCPU also provide CPU sampling with a grammar bitmask and speculative rejection verification keyed by (SeqSeed, StepOffset) via Philox4x32_10.

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 (
	// SampleThreads is the block width SampleRows must be launched with.
	SampleThreads = 256
	// SampleTile is the number of tokens each block of a row covers.
	SampleTile = 4096
	// SamplePasses is the number of launches, pass 0 through
	// SamplePasses-1, that draw one token per row.
	SamplePasses = 6
	// SampleScratchWords is the number of 32-bit scratch words per row.
	SampleScratchWords = 1088
	// SampleStatWords is the number of 32-bit words SampleRows writes
	// per sampled row to its optional stats buffer.
	SampleStatWords = 4
)

Launch geometry and scratch layout of SampleRows.

View Source
const ArgmaxBlockDim = 256

ArgmaxBlockDim is the number of threads per block ArgmaxLogits is tuned for. Any multiple of 32 up to 1024 is correct.

View Source
const ArgmaxKernelTemplate = `` /* 3414-byte string literal not displayed */

ArgmaxKernelTemplate is the CUDA C++ source of ArgmaxLogits, the greedy argmax over a float32 logit vector.

Each block reduces tiles of 2048 logits, packs its best (value, index) into a 64-bit key whose unsigned order is the argmax order, and folds it into a module-scope key with atomicMax. The last block to finish, found by atomicInc on a module-scope counter, writes the token and resets the key; atomicInc wraps the counter back to zero. The scratch is zero at module load and after every launch, so the kernel is one graph node and needs no memset. Launches of one loaded module must not overlap in time.

View Source
const ArgmaxMaxRows = 65535

ArgmaxMaxRows is the largest ArgmaxConfig Rows: the maximum grid y dimension.

Variables

View Source
var SamplerKernelSource string

SamplerKernelSource is the CUDA C++ source of the SampleRows kernel.

Functions

func ArgmaxBlocks

func ArgmaxBlocks(vocabSize int) uint32

ArgmaxBlocks returns the grid size for ArgmaxLogits over vocabSize logits: one block per tile of 2048 logits, and at least one block. Any grid size is correct; this one gives each thread two float4 loads.

func ArgmaxSource

func ArgmaxSource(cfg ArgmaxConfig) (string, error)

ArgmaxSource returns the CUDA C++ source of ArgmaxLogits, or of ArgmaxLogitsRows, for cfg.

func Compile

func Compile(major, minor int) (*nvrtc.CompiledModule, error)

Compile compiles the JIT argmax sampling module.

func CompileArgmax

func CompileArgmax(cfg ArgmaxConfig, major, minor int) (*nvrtc.CompiledModule, error)

CompileArgmax compiles ArgmaxSource(cfg) for compute capability major.minor.

func CompileSampler

func CompileSampler(major, minor int) (*nvrtc.CompiledModule, error)

CompileSampler compiles SamplerKernelSource for compute capability major.minor.

func Philox4x32_10

func Philox4x32_10(seed uint64, offset uint64, subseq uint64) [4]uint32

Philox4x32_10 executes 10 rounds of the counter-based Philox-4x32 PRNG matching CUDA's curand_philox4x32_10. Output words depend strictly on (seed, offset, subseq) and are independent of batch size or row index.

func PhiloxUniformFloat32

func PhiloxUniformFloat32(seed uint64, offset uint64, vocabIdx int) float32

PhiloxUniformFloat32 maps (seed, offset, vocabIdx) to a deterministic uniform float32 strictly inside the open interval (0, 1) using Philox4x32_10: word vocabIdx%4 of the block at subsequence vocabIdx/4.

func SampleArgmaxCPU

func SampleArgmaxCPU(logits []float32) int32

SampleArgmaxCPU returns the index of the maximum logit using the same rules as ArgmaxLogits. NaNs are ignored, ties favor the lowest index, and empty or all-NaN/all-negative-infinity input returns -1.

Example
package main

import (
	"fmt"
	nnsample "github.com/tmc/lib/nvidia/x/nn/sample"
)

func main() {
	logits := []float32{-2, 4, 4, 1}
	fmt.Println(nnsample.SampleArgmaxCPU(logits))
	fmt.Println(nnsample.SampleArgmaxCPU(nil))
}
Output:
1
-1

func SampleBatchSeededCPU

func SampleBatchSeededCPU(batchLogits [][]float32, batchParams []SequenceSampleParams) ([]int32, error)

SampleBatchSeededCPU evaluates a batch of sequences with SampleSeededCPU. Because each sequence draws solely from (batchParams[b].SeqSeed, batchParams[b].StepOffset), any permutation or subset of the batch yields identical token IDs.

func SampleBlocks

func SampleBlocks(vocab int) int

SampleBlocks returns the grid width of SampleRows for vocab tokens.

func SampleSeededCPU

func SampleSeededCPU(logits []float32, params SequenceSampleParams) (tokenID int32, filteredProbs []float32, err error)

SampleSeededCPU draws one token from logits with the rules of the SampleRows kernel (see the package documentation), keyed by (params.SeqSeed, params.StepOffset). It is the reference the kernel is tested against.

Tokens masked by params.AllowedBitmask (when non-nil), NaN logits and negative infinities are excluded. With params.Temperature <= 0 it returns the lowest-index largest logit. filteredProbs holds the probabilities, renormalized over the tokens that pass the filters, that the token was drawn from.

Example
package main

import (
	"fmt"

	nnsample "github.com/tmc/lib/nvidia/x/nn/sample"
)

func main() {
	logits := []float32{0.1, 3.5, 2.0, -1.0}
	params := nnsample.SequenceSampleParams{
		SeqSeed:        42,
		StepOffset:     10,
		Temperature:    0.8,
		TopK:           2,
		TopP:           0.95,
		AllowedBitmask: []uint32{(1 << 0) | (1 << 2) | (1 << 3)}, // disallow token 1
	}
	tok, _, err := nnsample.SampleSeededCPU(logits, params)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("sampled token:", tok)
}
Output:
sampled token: 2
Example (TopK)
package main

import (
	"fmt"

	nnsample "github.com/tmc/lib/nvidia/x/nn/sample"
)

// kept returns the indices of the nonzero entries of probs.
func kept(probs []float32) []int {
	var out []int
	for i, p := range probs {
		if p != 0 {
			out = append(out, i)
		}
	}
	return out
}

func main() {
	logits := []float32{5, 3, 3, 1}
	// top_k 2 keeps token 0 and both tokens tied for second.
	_, probs, _ := nnsample.SampleSeededCPU(logits, nnsample.SequenceSampleParams{SeqSeed: 1, Temperature: 1, TopK: 2})
	fmt.Println(kept(probs))
}
Output:
[0 1 2]

func VerifySpeculativeSeededCPU

func VerifySpeculativeSeededCPU(
	targetProbs [][]float32,
	draftProbs [][]float32,
	draftTokens []int32,
	seqSeed uint64,
	baseStepOffset uint64,
) (acceptedTokens []int32, bonusToken int32, err error)

VerifySpeculativeSeededCPU performs deterministic speculative rejection sampling over draftTokens using (seqSeed, baseStepOffset + s) at draft step s. Draft token x_s is accepted when u_s < min(1, targetProbs[s][x_s] / draftProbs[s][x_s]). On the first rejection at step s, bonusToken is resampled from the normalized residual distribution max(0, targetProbs[s] - draftProbs[s]) keyed by (seqSeed, baseStepOffset + s). If all draft tokens are accepted, bonusToken is sampled from targetProbs[len(draftTokens)] (or targetProbs[len(draftTokens)-1] when len(targetProbs) == len(draftTokens)).

Example
package main

import (
	"fmt"

	nnsample "github.com/tmc/lib/nvidia/x/nn/sample"
)

func main() {
	targetProbs := [][]float32{
		{0.1, 0.8, 0.1},
		{0.0, 0.2, 0.8},
	}
	draftProbs := [][]float32{
		{0.2, 0.5, 0.3},
		{0.9, 0.1, 0.0},
	}
	draftTokens := []int32{1, 0}

	accepted, bonus, err := nnsample.VerifySpeculativeSeededCPU(targetProbs, draftProbs, draftTokens, 42, 0)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("accepted=%v bonus=%d\n", accepted, bonus)
}
Output:
accepted=[1] bonus=2

Types

type ArgmaxConfig

type ArgmaxConfig struct {
	// Fault adds an int* fault word after vocab_size, as described at
	// [kernel.Fault]. ArgmaxLogits sets [kernel.FaultNonFinite] in
	// it if any logit is NaN or ±Inf, and writes the same tokens as without
	// the word.
	Fault bool

	// FaultSite, if nonzero, refines Fault: the word is two ints, and the
	// kernel records the first fault in word[1] as FaultSite<<8|bit, as
	// described at [kernel.Fault] and decoded by
	// [kernel.FirstFault]. It needs Fault.
	FaultSite uint16

	// Rows, if nonzero, makes the kernel ArgmaxLogitsRows, which takes
	// up to Rows rows of vocab_size logits, row r at logits[r*vocab_size:],
	// and writes row r's token to out_token[r]. The grid's y dimension is
	// the number of rows; its x dimension is as for ArgmaxLogits, and
	// ArgmaxBlocks gives the tuned value. Each row has its own scratch in
	// the module, so the rows of a launch do not interact. A block whose
	// row is Rows or more writes nothing and, with Fault, sets
	// [kernel.FaultInvalidArgument]. Rows must be at most
	// [ArgmaxMaxRows].
	Rows int
}

ArgmaxConfig selects the variant of ArgmaxLogits that ArgmaxSource generates. The zero value is the kernel in ArgmaxKernelTemplate.

type LogProbMode

type LogProbMode string

A LogProbMode says which distribution a log-probability is taken from.

const (
	// LogProbRaw is the softmax of the logits at temperature 1 over every
	// token the sampler can see: the model's own distribution.
	LogProbRaw LogProbMode = "raw"
	// LogProbProcessed is the distribution the sampler draws from: the
	// softmax of the logits divided by the temperature, over the tokens
	// that pass top-k, top-p and min-p. A token outside that support has
	// log-probability -Inf. At temperature 0 the distribution is the
	// argmax token with probability 1.
	LogProbProcessed LogProbMode = "processed"
)

type RowLogProbs

type RowLogProbs struct {
	// VMax is the largest value.
	VMax float32
	// LogZRaw is log sum exp(v_i - VMax) over the candidate tokens.
	LogZRaw float64
	// Temperature, Threshold and MinP define the processed support: the
	// tokens with v_i >= Threshold and, when MinP > 0, exp((v_i-VMax)/T)
	// >= MinP in float32. Temperature is 0 for a greedy row.
	Temperature float32
	Threshold   float32
	MinP        float32
	// Kept is the number of tokens in the processed support.
	Kept int
	// LogZProcessed is log sum exp((v_i - VMax)/T) over the support; 0
	// for a greedy row.
	LogZProcessed float64
	// contains filtered or unexported fields
}

RowLogProbs is the log-normalizer of one row of logits under the rules of SampleSeededCPU: the same values (NaNs and negative infinities excluded, -0 as +0), the same filters and the same tie rule.

The log-normalizers are float64 sums taken in index order, so they are a function of the logits alone.

func LogProbsCPU

func LogProbsCPU(logits []float32, params SequenceSampleParams) (*RowLogProbs, error)

LogProbsCPU returns the log-normalizers of logits under params. The grammar bitmask is honored as in SampleSeededCPU. logits must hold exactly the logical vocabulary: padding columns past it would be counted as tokens.

func (*RowLogProbs) LogProb

func (r *RowLogProbs) LogProb(token int32, mode LogProbMode) (float64, error)

LogProb returns the log-probability of token in mode. It is -Inf for a token the sampler cannot draw: one that is NaN, -Inf or masked in raw mode, and one outside the support in processed mode.

type SampleRowParams

type SampleRowParams struct {
	Seed        uint64
	Step        uint64
	Temperature float32
	TopP        float32
	MinP        float32
	TopK        int32
}

SampleRowParams is the device layout of one row's sampling parameters, the struct SampleRowParams of SamplerKernelSource. A Temperature that is not above 0 leaves the row's token as the argmax wrote it.

type SampleStats

type SampleStats struct {
	// Written reports whether the kernel wrote the row; it does not
	// write greedy rows.
	Written bool
	// KeptArgmax reports a degenerate row (no finite value, or +Inf),
	// whose token is the argmax.
	KeptArgmax bool
	VMax       float32
	// Threshold is the smallest value the top-k and top-p filters keep,
	// -Inf when neither is on.
	Threshold float32
	// Kept is the number of tokens at or above Threshold that pass
	// min_p: the support of the draw.
	Kept int
}

SampleStats is what SampleRows reports about one sampled row in its stats buffer: the support it drew from. It is the device's side of RowLogProbs, whose Threshold and Kept it should equal.

func DecodeSampleStats

func DecodeSampleStats(w []uint32) SampleStats

DecodeSampleStats decodes the SampleStatWords words of one row.

type SequenceSampleParams

type SequenceSampleParams struct {
	SeqSeed        uint64
	StepOffset     uint64
	Temperature    float32
	TopK           int
	TopP           float32
	MinP           float32
	AllowedBitmask []uint32
}

SequenceSampleParams holds per-sequence deterministic sampling hyperparameters and optional packed grammar bitmask constraints.

Jump to

Keyboard shortcuts

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