spec

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: 26 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 spec provides speculative decoding verification, draft-tree mask construction, multi-token prediction (MTP) paged attention, EAGLE-3/MCTS reasoning trees, early-exit confidence probes, and adaptive flight buckets.

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

Example
package main

import (
	"fmt"

	nnspec "github.com/tmc/lib/nvidia/x/nn/spec"
)

func main() {
	drafter := nnspec.NewNgramDrafter(3)

	// Ingest past prompt/system context
	drafter.Feed([]int32{100, 200, 300, 400, 500, 600})

	// Current context ends with [200, 300, 400]
	draft := drafter.Draft([]int32{200, 300, 400}, 2)
	fmt.Printf("Draft tokens: %v\n", draft)

	// Target model verifies candidate sequence in one batched forward pass
	targetVerification := []int32{500, 600, 700}
	res := nnspec.VerifyGreedy(targetVerification, draft)

	fmt.Printf("Accepted: %v, Bonus: %d, Emitted Count: %d\n", res.AcceptedTokens, res.BonusToken, res.TotalEmitted)

}
Output:
Draft tokens: [500 600]
Accepted: [500 600], Bonus: 700, Emitted Count: 3

Index

Examples

Constants

View Source
const (
	// MaxWindowSize is the maximum number of runtime observations retained per tier
	// in ForwardRuntimeEstimator (matching csrc/engine/mtp_varlen.hpp).
	MaxWindowSize = 5000

	// MinSamplesForReliableEstimate is the minimum sample count required in a bucket
	// before its median latency estimate is treated as calibrated.
	MinSamplesForReliableEstimate = 10

	// SamplerMedianWindowSize is the sliding window length for SamplerRuntimeEstimator.
	SamplerMedianWindowSize = 9
)
View Source
const VerifyNegInfPrelude = `#ifndef INFINITY
#define INFINITY __int_as_float(0x7f800000)
#endif
`

VerifyNegInfPrelude returns the portable negative-infinity constant definition emitted ahead of speculative verification megakernel stages.

Variables

View Source
var (
	ErrInvalidBranchID      = errors.New("cudaspec: invalid branch identity")
	ErrBranchAlreadyExists  = errors.New("cudaspec: branch identity already exists")
	ErrBranchNotFound       = errors.New("cudaspec: branch not found")
	ErrBranchNotActive      = errors.New("cudaspec: branch is not active")
	ErrIncorrectTokenAccept = errors.New("cudaspec: cannot accept mismatched or invalid token")
	ErrCacheKeyMismatch     = errors.New("cudaspec: cache key mismatch or invalidated")
	ErrKVHoldersConflict    = errors.New("cudaspec: KV block retains holders conflict")
	ErrNilKVAllocator       = errors.New("cudaspec: nil KV block allocator")
	ErrDraftDigestRequired  = errors.New("cudaspec: cache key without draft digest")
)

Common errors for branch and cache operations.

View Source
var (
	// ErrInvalidVarlenConfig indicates invalid VarlenScheduleConfig parameters.
	ErrInvalidVarlenConfig = errors.New("cudamtp: invalid varlen schedule config")

	// ErrEmptySequenceBatch indicates an empty sequence slice passed to Schedule.
	ErrEmptySequenceBatch = errors.New("cudamtp: empty sequence batch")
)
View Source
var ErrInvalidConfidenceSpec = errors.New("cudamtp: invalid confidence head specification")

ErrInvalidConfidenceSpec indicates an invalid ConfidenceHeadSpec or mismatched tensor dimensions.

View Source
var ErrInvalidVarlenSpec = errors.New("cudaspec: invalid varlen confidence schedule parameters")

ErrInvalidVarlenSpec indicates invalid parameters passed to ComputeSeqlensQByConfidenceCPU or VarlenSeqlensKernelSource.

View Source
var ErrMTPConfig = errors.New("cudamtp: invalid MTP configuration")

ErrMTPConfig indicates an invalid configuration for MTP operations.

Functions

func CausalDraftMask

func CausalDraftMask(qTokens int) []uint64

CausalDraftMask returns a bitpacked causal draft mask of length qTokens where bit j <= i is set for row i (0 <= i < qTokens).

func ComputeSeqlensQByConfidenceCPU

func ComputeSeqlensQByConfidenceCPU(
	prob [][]float32,
	remap []int32,
	targetTotalBsz int,
	maxStep int,
) (seqlensQ []int32, cuSeqlensQ []int32, err error)

ComputeSeqlensQByConfidenceCPU computes the exact CPU reference for DeepInfer's _compute_seqlens_q_by_conf_kernel (deepinfer/kernels/schedule_mtp_varlen.py):

  1. Each sequence b in [0, bsz) starts with base query length 1 (the verified/bonus token), and extraBudget is clamped to [0, bsz * maxStep] from targetTotalBsz - bsz.
  2. For each sequence b, srcRow = remap[b] (or b when remap == nil; -1 yields 0.0 cumulative probabilities for newly admitted sequences), and cumulative products c[b, s] = prod_{k=0..s} prob[srcRow][k] are computed for s in [0, maxStep).
  3. Across all bsz*maxStep flattened entries, global rank[i] counts how many entries j satisfy (m_j > m_i) || (m_j == m_i && j < i) (deterministic flat-index tie-breaking).
  4. Entries with rank < extraBudget are allocated to their sequence, yielding seqlensQ[b] and prefix sums cuSeqlensQ of length bsz + 1 (with cuSeqlensQ[0] = 0).
Example
package main

import (
	"fmt"

	nnspec "github.com/tmc/lib/nvidia/x/nn/spec"
)

func main() {
	prob := [][]float32{
		{0.9, 0.8, 0.5},
		{0.8, 0.5, 0.5},
		{0.7, 0.2, 0.1},
	}
	seqlensQ, cuSeqlensQ, err := nnspec.ComputeSeqlensQByConfidenceCPU(prob, nil, 6, 3)
	if err != nil {
		panic(err)
	}
	fmt.Printf("seqlensQ=%v cuSeqlensQ=%v\n", seqlensQ, cuSeqlensQ)
}
Output:
seqlensQ=[3 2 1] cuSeqlensQ=[0 3 5 6]

func ConfidenceReferenceCPU

func ConfidenceReferenceCPU(
	hidden []float32,
	rmsW []float32,
	wProj []float32,
	markovMatrix []float32,
	tokenIDs []int32,
	spec ConfidenceHeadSpec,
) (stepProbs [][]float32, cumProbs [][]float32, err error)

ConfidenceReferenceCPU computes the CPU mathematical reference for the MTP confidence head:

  1. RMSNorm on hidden using rmsW and spec.Eps.
  2. Linear projection via wProj.
  3. Optional Markov bigram logit bias from markovMatrix[prevToken % V, curToken % V].
  4. Per-step temperature scaling logits / StepTemperatures[s].
  5. Sigmoid p_s = 1 / (1 + exp(-logit)) and cumulative product cumProbs[i][s] = prod_{k <= s} p_k.

func DenseReferenceMask

func DenseReferenceMask(numPrefixTokens int, tree *DraftTree, fullyMaskedNodes []int) [][]bool

DenseReferenceMask computes the dense reference mask for prefix/tree/glue operations. Given numPrefixTokens prefix tokens and draftTree of N nodes, the resulting mask is [numPrefixTokens + N, numPrefixTokens + N] boolean matrix where: - Prefix tokens attend to earlier prefix tokens (causal). - Tree node i (offset by numPrefixTokens) attends to all prefix tokens. - Tree node i attends to tree node j iff node j is an ancestor of node i in the draft tree. - If fullyMaskedNodes contains a node index, its entire row is false (fully masked row).

func EmitToolCallTrapDoorCUDA

func EmitToolCallTrapDoorCUDA(delimiterTokens []int32) string

EmitToolCallTrapDoorCUDA generates the `eg_grammar_trap_door` device epilogue function that inspects newly accepted / generated tokens for a completed tool-call or structured JSON delimiter token in delimiterTokens and signals a zero-copy mapped host doorbell ring buffer via system-scope release store (`st.release.sys.global.u64` / `st.release.sys.global.b32`) so the host can immediately dispatch the tool call without polling or tearing down the persistent megakernel.

func EmitVerifyStageDeviceFunc

func EmitVerifyStageDeviceFunc(cfg VerifyStageSourceConfig) string

EmitVerifyStageDeviceFunc emits the EG_DEV speculative tree-verification and grammar-masked Philox sampling stage device function(s).

func FormatFusedVerifyMegakernelEntry

func FormatFusedVerifyMegakernelEntry(name string, numStages, totalBlocks, readyWords int, lineInfo bool, params []string, entryBody string) string

FormatFusedVerifyMegakernelEntry formats the persistent fused verify+sample megakernel entry header and splices entryBody.

func GenerateConfidenceCudaSource

func GenerateConfidenceCudaSource(spec ConfidenceHeadSpec) (string, error)

GenerateConfidenceCudaSource generates the NVRTC CUDA C++ source for mtp_confidence_head_kernel matching ConfidenceReferenceCPU.

func GenerateMTPCudaSource

func GenerateMTPCudaSource(cfg MTPConfig) string

GenerateMTPCudaSource generates a fused CUDA C++ kernel that computes N speculative draft heads simultaneously within a single grid launch across cooperative thread blocks.

func MTPReference

func MTPReference(hTrunk []float32, wDraftProj []float32, wLMHeads []float32, cfg MTPConfig) ([]float32, error)

MTPReference performs host-based CPU reference forward prediction for multi-draft heads. Given hidden trunk representation [dim], draft projections [numDraftHeads, dim, dim], and LM heads [numDraftHeads, dim, vocabSize], it computes draft logits [numDraftHeads, vocabSize].

func Philox4x32

func Philox4x32(ctr [4]uint32, key [2]uint32) [4]uint32

Philox4x32 is the Philox-4x32-10 counter-based generator of Salmon et al. (SC'11), the generator behind curand's Philox engine. It maps a 128-bit counter and a 64-bit key to four 32-bit words, so a kernel and a host reference that agree on the counter draw the same numbers with no state.

func PhiloxUniform

func PhiloxUniform(word uint32) float32

PhiloxUniform returns a float32 in [0, 1) with 24 random bits from word.

func PruneReasoningBranchesOnDevice

func PruneReasoningBranchesOnDevice(branchScores []float32, minPRMThreshold float32, maxSurviving int) (survivingIndices []int, prefixTileReuseFactor float64)

PruneReasoningBranchesOnDevice evaluates Process Reward Model (PRM) value-head scores across K parallel reasoning branches, filters out branches with score < minPRMThreshold (or NaN), selects up to maxSurviving highest-scoring branches (ties broken by lower branch index; if all branches fall below minPRMThreshold and maxSurviving >= 1, the single highest-scoring branch is kept as a fallback so decoding never stalls), and returns survivingIndices along with prefixTileReuseFactor (the effective shared prompt prefix tile reuse multiplier across the surviving reasoning branches).

func SampleTokenFused

func SampleTokenFused(logits []float32, mask GrammarBitmask, seen []uint32, params SamplingParams, step uint64) (tokenID int32, logProb float32, err error)

SampleTokenFused samples one token from logits under mask and params, as GrammarSampler with 256 threads does on the device. step selects the noise: equal (Seed, step) pairs give equal tokens. logProb is the token's log-probability after steps 1-4 of the pipeline, before top-k/top-p truncation; it is 0 when Temperature is 0.

Example
// The grammar allows only tokens 2 and 5; greedy decoding picks the
// larger of their logits even though token 0's is larger still.
logits := []float32{9, 1, 3, 0, 0, 4, 0, 0}
mask := NewGrammarBitmask(8)
mask.Allow(2)
mask.Allow(5)
tok, _, err := SampleTokenFused(logits, mask, nil, SamplingParams{VocabSize: 8}, 0)
if err != nil {
	panic(err)
}
fmt.Println(tok)
Output:
5

func SpecPhiloxDevicePrelude

func SpecPhiloxDevicePrelude() string

SpecPhiloxDevicePrelude returns the device Philox-4x32-10 RNG helper source.

func TreeDraftMask

func TreeDraftMask(parent []int) ([]uint64, error)

TreeDraftMask builds a bitpacked speculative draft tree mask from parent, where parent[0] == -1 is the root and parent[i] < i (-1 <= parent[i] < i) is the parent of draft node i. Bit j in row i is set iff node j is an ancestor of node i (or j == i).

func TreeMaskToBitmasks

func TreeMaskToBitmasks(mask [][]bool) ([]uint64, error)

TreeMaskToBitmasks converts a 2D boolean tree attention mask [N, N] to uint64 row bitmasks.

func TreeSpecNodeKV

func TreeSpecNodeKV(step, seq, node, w int) uint32

TreeSpecNodeKV is the KV word w that the emulated target forward pass of TreeSpecVerify.RunEmulatedLoop writes for node of sequence seq at step.

func TreeSpecPrefixKV

func TreeSpecPrefixKV(seq, pos, w int) uint32

TreeSpecPrefixKV is the KV word w that the tests and fixtures store for prefix position pos of sequence seq.

func VarlenSeqlensKernelSource

func VarlenSeqlensKernelSource(maxBsz int, maxStep int) (string, error)

VarlenSeqlensKernelSource generates NVRTC CUDA C++ source implementing compute_seqlens_q_by_conf_kernel with shared-memory cumulative products, parallel rank counting with flat-index tie-breaking, and prefix scan for cu_seqlens_q.

func VerifyTreeAttentionOutputs

func VerifyTreeAttentionOutputs(q, k, v []float32, mask [][]bool, numNodes, numHeads, headDim int, scale float32) error

VerifyTreeAttentionOutputs runs dense reference attention and compares against sparse tree reference attention.

Types

type AdaptiveBucketConfig

type AdaptiveBucketConfig struct {
	// Buckets lists the available dynamic M buckets. When empty,
	// [DefaultBucketSpecs] is used.
	Buckets []BucketSpec

	// EMAAlpha is the exponential moving average smoothing factor in (0, 1] for
	// live draft acceptance-rate tracking (defaults to 0.25).
	EMAAlpha float64

	// HysteresisSteps is the number of consecutive steps that must recommend the
	// same new target bucket before triggering a hot-swap (defaults to 3).
	HysteresisSteps int

	// LowAcceptanceThreshold is the acceptance-rate EMA threshold below which
	// draft tree depth collapses to M=1..2 [RegimeSkinnyDecode] (defaults to 0.30).
	LowAcceptanceThreshold float64

	// HighAcceptanceThreshold is the acceptance-rate EMA threshold at or above
	// which draft tree depth expands to M=4..8 [RegimeMTPTreeVerify], or M>=16
	// [RegimeTilePrefill] when ActiveBatch * QTokensPerSeq >= 16 (defaults to 0.65).
	HighAcceptanceThreshold float64

	// InitialAcceptanceRate optionally seeds the acceptance-rate EMA before the
	// first [AdaptiveBucketController.RecordStep] call when in (0, 1].
	InitialAcceptanceRate float64

	// InitialBucketM optionally selects the starting bucket by BucketM.
	InitialBucketM int

	// Service is the optional [cudahotswap.Service] used to perform live bucket
	// kernel and 3D launch geometry switches.
	Service *hotswap.Service

	// KernelName is the registered kernel name in Service (defaults to
	// "specdecode_bucket_kernel" when Service is non-nil).
	KernelName string

	// Checker is an optional post-publication check installed on Service for Push.
	Checker hotswap.Checker
}

AdaptiveBucketConfig configures an AdaptiveBucketController.

func (AdaptiveBucketConfig) Norm

Norm validates c and populates default parameters and normalized buckets.

type AdaptiveBucketController

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

AdaptiveBucketController tracks the live speculative draft acceptance-rate EMA, recommends dynamic M buckets and speculative draft tree shapes across RegimeSkinnyDecode, RegimeMTPTreeVerify, and RegimeTilePrefill, applies hysteresis anti-thrashing, and performs atomic hot-swaps and rollbacks through a [cudahotswap.Service].

func NewAdaptiveBucketController

func NewAdaptiveBucketController(cfg AdaptiveBucketConfig) (*AdaptiveBucketController, error)

NewAdaptiveBucketController creates an AdaptiveBucketController from cfg. When cfg.Service is non-nil, the initial bucket is bound to cfg.KernelName and its 3D launch geometry is configured on the service.

func (*AdaptiveBucketController) AcceptanceRate

func (c *AdaptiveBucketController) AcceptanceRate() float64

AcceptanceRate returns the current exponentially smoothed draft token acceptance rate in [0, 1].

func (*AdaptiveBucketController) BindService

func (c *AdaptiveBucketController) BindService(ctx context.Context, svc *hotswap.Service, kernelName string) (hotswap.State, error)

BindService binds ctrl to kernelName in svc, registering the current bucket's kernel if kernelName is not yet registered, applying its 3D launch geometry, and seeding the rollback history.

func (*AdaptiveBucketController) Buckets

func (c *AdaptiveBucketController) Buckets() []BucketSpec

Buckets returns a copy of the configured BucketSpec table.

func (*AdaptiveBucketController) CurrentBucket

func (c *AdaptiveBucketController) CurrentBucket() BucketSpec

CurrentBucket returns the currently active BucketSpec.

func (*AdaptiveBucketController) CurrentGeometry

func (c *AdaptiveBucketController) CurrentGeometry() hotswap.LaunchGeometry

CurrentGeometry returns the currently active 3D [cudahotswap.LaunchGeometry].

func (*AdaptiveBucketController) CurrentState

func (c *AdaptiveBucketController) CurrentState() hotswap.State

CurrentState returns the last observed [cudahotswap.State] from the service.

func (*AdaptiveBucketController) History

History returns a copy of the promoted bucket snapshot stack from oldest to current.

func (*AdaptiveBucketController) LastError

func (c *AdaptiveBucketController) LastError() error

LastError returns the most recent error encountered during an automatic hot-swap in AdaptiveBucketController.RecordStep, if any.

func (*AdaptiveBucketController) ObserveStep

func (c *AdaptiveBucketController) ObserveStep(ctx context.Context, activeTokens int, acceptanceRate float64) (BucketTransition, error)

(1 bonus token + draftTokens) and acceptanceRate in [0, 1], selects the target bucket for the verification step, and switches buckets when the hysteresis gate is satisfied. The selected bucket always holds activeTokens: a current bucket too small for the step is replaced without waiting for hysteresis, and ObserveStep fails if no bucket is large enough.

func (*AdaptiveBucketController) PendingBucket

func (c *AdaptiveBucketController) PendingBucket() (bucketM, consecutiveSteps int)

PendingBucket returns the candidate BucketM currently accumulating hysteresis steps and the number of consecutive steps observed so far.

func (*AdaptiveBucketController) RecommendBucket

func (c *AdaptiveBucketController) RecommendBucket(batchSize int) BucketSpec

RecommendBucket computes the recommended BucketSpec (including its BucketRegime, DraftTreeTopology, MTPPagedAttention, and 3D launch geometry) for batchSize active sequences and the current acceptance-rate EMA.

func (*AdaptiveBucketController) RecordStep

func (c *AdaptiveBucketController) RecordStep(batchSize, draftedTokens, acceptedTokens int) float64

RecordStep updates the live acceptance-rate EMA from a verification step with batchSize active sequences, draftedTokens proposed draft tokens, and acceptedTokens accepted draft tokens. When the recommended bucket differs from the current bucket for HysteresisSteps consecutive steps, RecordStep triggers an atomic bucket transition (and hot-swaps the bound [cudahotswap.Service] when configured). It returns the updated EMA.

func (*AdaptiveBucketController) RestorePrevious

func (c *AdaptiveBucketController) RestorePrevious(ctx context.Context) (hotswap.State, error)

RestorePrevious rolls the bound [cudahotswap.Service] and controller state back to the immediate prior bucket snapshot in History, restoring both the prior kernel version via [cudahotswap.Service.Select] and its exact 3D [cudahotswap.LaunchGeometry] via [cudahotswap.Service.SetGeometry].

func (*AdaptiveBucketController) RollbackBucket

RollbackBucket rolls the controller and bound [cudahotswap.Service] back to the immediate prior bucket on the promotion stack (via RestorePrevious semantics), restoring the exact prior BucketSpec, kernel version, and 3D launch geometry.

func (*AdaptiveBucketController) Step

func (c *AdaptiveBucketController) Step(ctx context.Context, batchSize, draftedTokens, acceptedTokens int) (BucketTransition, error)

Step updates the live acceptance-rate EMA, evaluates AdaptiveBucketController.RecommendBucket, applies the hysteresis anti-thrashing gate, and switches buckets when HysteresisSteps consecutive steps agree on a new target bucket.

func (*AdaptiveBucketController) SwitchBucket

func (c *AdaptiveBucketController) SwitchBucket(ctx context.Context, target BucketSpec) (BucketTransition, error)

SwitchBucket atomically switches the controller to target. When a [cudahotswap.Service] is bound, SwitchBucket calls SetGeometry followed by Select (when target's compiled version is already retained in the service) or Push (when target's kernel has not yet been compiled and loaded), and records the transition on the rollback stack.

func (*AdaptiveBucketController) Transitions

func (c *AdaptiveBucketController) Transitions() int

Transitions returns the total number of completed bucket hot-swaps.

func (*AdaptiveBucketController) UpdateBucketSpec

func (c *AdaptiveBucketController) UpdateBucketSpec(index int, spec BucketSpec)

UpdateBucketSpec replaces the configured BucketSpec at index and refreshes the active bucket geometry if spec.BucketM is currently active.

func (*AdaptiveBucketController) VerifyAndRollbackIfFailed

func (c *AdaptiveBucketController) VerifyAndRollbackIfFailed(ctx context.Context, fn func() error) (rolledBack bool, err error)

VerifyAndRollbackIfFailed executes post-switch verification fn (such as a latency guard or greedy token verification check) and, if fn returns a non-nil error, automatically calls AdaptiveBucketController.RollbackBucket to restore the immediate prior bucket and 3D launch geometry.

type Branch

type Branch struct {
	ID           BranchID
	ParentBranch BranchID // -1 for root
	Tokens       []int32  // Candidate tokens in this branch
	NodeIDs      []int    // Node IDs corresponding to tokens in DraftTree
	State        ProposalState
	KVBlocks     []int // Physical KV blocks owned specifically by this branch
	SharedPrefix []int // Physical KV blocks shared with parent/prefix
	SequenceID   int64 // Sequence ID in cudakv if allocated
}

Branch represents a speculative candidate branch with explicit token sequence, tree node mappings, KV block tracking, and proposal lifecycle state.

type BranchID

type BranchID int64

BranchID uniquely identifies a speculative branch in a proposal tree.

type BranchKV

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

BranchKV holds a speculative sequence and its share of an existing prefix. The allocator must be exclusively owned by this consumer; BlockAllocator is not safe for unrelated concurrent mutation. Close releases only this sequence. The zero value is closed. Do not close while a device still reads its table.

func NewBranchKV

func NewBranchKV(a *nnkv.BlockAllocator, prefixSequence, sequence int64, prefixTokens, draftTokens int) (*BranchKV, error)

NewBranchKV shares a full-block prefix and reserves space for draft tokens. Partial prefix blocks are refused because sharing them for writes would modify another sequence's KV. Native KV contents are not copied here.

func (*BranchKV) Close

func (b *BranchKV) Close() error

Close releases the branch's private blocks and its prefix references. The original prefix sequence and other borrowers remain live.

func (*BranchKV) PrivateBlocks

func (b *BranchKV) PrivateBlocks() []int

PrivateBlocks returns a copy of the branch's private block indices.

func (*BranchKV) Release

func (b *BranchKV) Release(blocks []int) error

Release implements KVBlockReleaser. It refuses borrowed-prefix or foreign blocks and drops the sequence's references through the allocator exactly once.

func (*BranchKV) Table

func (b *BranchKV) Table() ([]int, error)

Table returns a copy of the live branch's block table.

type BranchTree

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

BranchTree coordinates speculative branches, explicit tree masks, verification, and KV-block reference counting during commit and rollback cycles.

func NewBranchTree

func NewBranchTree(rootSeqID int64, sharedPrefix []int, rootToken int32) *BranchTree

NewBranchTree creates a branch coordinator rooted on sharedPrefix KV blocks.

func (*BranchTree) ActiveBranch

func (bt *BranchTree) ActiveBranch() BranchID

ActiveBranch returns the currently active committed branch ID.

func (*BranchTree) CommitBranch

func (bt *BranchTree) CommitBranch(acceptedID BranchID, expectedTokens []int32, releaser KVBlockReleaser) error

CommitBranch marks the branch as accepted/committed and rolls back all competing sibling branches under the same parent. If releaser is supplied, private KV blocks of rejected branches are released, while shared prefix blocks remain held.

func (*BranchTree) DraftTree

func (bt *BranchTree) DraftTree() *DraftTree

DraftTree returns the underlying DraftTree.

func (*BranchTree) GetBranch

func (bt *BranchTree) GetBranch(id BranchID) (*Branch, error)

GetBranch retrieves a branch by ID.

func (*BranchTree) PathTokens

func (bt *BranchTree) PathTokens(id BranchID) ([]int32, error)

PathTokens returns the full sequence of tokens from root to the given branch.

func (*BranchTree) ProposeBranch

func (bt *BranchTree) ProposeBranch(parentID BranchID, tokens []int32, kvBlocks []int) (*Branch, error)

ProposeBranch attaches a new speculative candidate branch to parentID.

func (*BranchTree) RollbackBranch

func (bt *BranchTree) RollbackBranch(id BranchID, releaser KVBlockReleaser) error

RollbackBranch rolls back a branch and its proposed descendants, releasing descendant private blocks before ancestor blocks. Release errors preserve the failing branch's state and blocks for retry; completed releases are not repeated. Committed branches and ancestors of committed branches cannot be rolled back; accepted KV teardown belongs to the explicit sequence owner.

type BucketCandidate

type BucketCandidate = Candidate

BucketCandidate is an alias for Candidate.

type BucketRegime

type BucketRegime string

BucketRegime identifies the execution schedule regime for a dynamic M bucket.

const (
	// RegimeSkinnyDecode targets low-acceptance or single-token decode (M = 1..2)
	// using a skinny split-K / vector GEMV schedule with collapsed draft depth.
	RegimeSkinnyDecode BucketRegime = "skinny_decode"

	// RegimeMTPTreeVerify targets medium-to-high acceptance speculative tree
	// verification (M = 4..8) using [DraftTreeTopology] ancestor masks and
	// [MTPPagedAttention].
	RegimeMTPTreeVerify BucketRegime = "mtp_tree_verify"

	// RegimeTilePrefill targets large effective token batches (M >= 16, where
	// ActiveBatch * QTokensPerSeq >= 16) using tensor-core TileGEMM / WGMMA tiles.
	RegimeTilePrefill BucketRegime = "tile_prefill"
)

type BucketSnapshot

type BucketSnapshot struct {
	Step          int
	Bucket        BucketSpec
	State         hotswap.State
	Geometry      hotswap.LaunchGeometry
	AcceptanceEMA float64
}

BucketSnapshot records a promoted bucket, its [cudahotswap.State], and its 3D [cudahotswap.LaunchGeometry] on the controller's rollback stack.

type BucketSpec

type BucketSpec struct {
	BucketM           int
	Regime            BucketRegime
	DraftDepth        int
	DraftBranchFactor int
	Topology          *DraftTreeTopology
	MTPAttention      *MTPPagedAttention
	Candidate         Candidate
}

BucketSpec defines the speculative draft tree shape, attention kernel configuration, schedule regime, and hot-swap candidate for one dynamic M bucket (e.g., M in {1, 2, 4, 8, 16, 64}).

func DefaultBucketSpecs

func DefaultBucketSpecs() ([]BucketSpec, error)

DefaultBucketSpecs returns the canonical dynamic M bucket table spanning RegimeSkinnyDecode (M=1, 2), RegimeMTPTreeVerify (M=4, 8), and RegimeTilePrefill (M=16, 64).

func (BucketSpec) LaunchGeometry

func (b BucketSpec) LaunchGeometry() hotswap.LaunchGeometry

LaunchGeometry returns the 3D [cudahotswap.LaunchGeometry] for b.

func (BucketSpec) QTokensPerSeq

func (b BucketSpec) QTokensPerSeq() int

QTokensPerSeq returns the number of query/draft tokens verified per sequence in a single step for b.

type BucketTransition

type BucketTransition struct {
	Swapped     bool
	PriorBucket BucketSpec
	NewBucket   BucketSpec
	State       hotswap.State
	Geometry    hotswap.LaunchGeometry
	UsedSelect  bool
	PushResult  *hotswap.PushResult
}

BucketTransition reports the outcome of a step or explicit bucket switch.

func (BucketTransition) Changed

func (t BucketTransition) Changed() bool

Changed reports whether the step resulted in a bucket transition.

func (BucketTransition) From

func (t BucketTransition) From() BucketSpec

From returns the bucket active prior to the step.

func (BucketTransition) To

To returns the bucket active after the step.

type Candidate

type Candidate struct {
	Name        string
	Source      hotswap.Source
	Grid        [3]int
	Block       [3]int
	SharedBytes int
	Version     uint64
}

Candidate packages a compiled or compilable kernel source and its 3D launch geometry for hot-swapping a CUDA graph node across dynamic M buckets via [cudahotswap.Service].

func (Candidate) LaunchGeometry

func (c Candidate) LaunchGeometry() hotswap.LaunchGeometry

LaunchGeometry converts c's 3D Grid, Block, and SharedBytes into a [cudahotswap.LaunchGeometry].

type ConfidenceHeadSpec

type ConfidenceHeadSpec struct {
	HiddenDim        int
	MarkovVocabSize  int
	StepTemperatures []float32
	Eps              float32
}

ConfidenceHeadSpec configures the lightweight MTP confidence prediction head from DeepInfer (deepinfer/models/mtp.py and tilelang_ops/dflash.py).

type CycleConfig

type CycleConfig struct {
	NumHeads      int
	HeadDim       int
	Scale         float32
	VocabSize     int
	NumDraftHeads int
	ModelDigest   [32]byte
	NumericalMode string
}

CycleConfig configures an end-to-end speculative decoding cycle.

type CycleOutcome

type CycleOutcome struct {
	DraftTokens    []int32
	AcceptedTokens []int32
	BonusToken     int32
	TotalEmitted   int
	DiscardedCount int
	AcceptedRatio  float64
	Committed      bool
}

CycleOutcome reports acceptance statistics and emitted tokens from a speculative cycle.

func ExecuteSpeculativeCycle

func ExecuteSpeculativeCycle(
	cfg CycleConfig,
	bt *BranchTree,
	parentBranchID BranchID,
	draftTokens []int32,
	allocatedKVBlocks []int,
	releaser KVBlockReleaser,
	targetOracle func(contextTokens []int32) int32,
) (*CycleOutcome, error)

ExecuteSpeculativeCycle runs a deterministic propose, attention-reference-verify, and commit-or-rollback cycle using explicit branch state and KV release tracking.

type DraftTree

type DraftTree struct {
	Nodes []*TreeNode
	Root  *TreeNode
}

DraftTree holds a non-linear tree of candidate draft paths and its causal attention mask.

func NewDraftTree

func NewDraftTree(rootToken int32) *DraftTree

NewDraftTree creates a new DraftTree rooted at rootToken.

func (*DraftTree) AddNode

func (t *DraftTree) AddNode(parentID int, token int32) *TreeNode

AddNode attaches a child candidate token to a parent node in the tree.

func (*DraftTree) BuildCausalTreeMask

func (t *DraftTree) BuildCausalTreeMask() [][]bool

BuildCausalTreeMask generates the N x N causal 2D attention mask for single-pass verification. An element mask[i][j] is true (attendable) iff node j is an ancestor of node i or j == i.

type DraftTreeTopology

type DraftTreeTopology struct {
	ParentIdx    []int    // ParentIdx[0] == -1; 0 <= ParentIdx[i] < i for i > 0
	AncestorMask []uint64 // bit j of AncestorMask[i] is set iff j is i or an ancestor of i
	Depth        []int    // Depth[0] == 0
}

A DraftTreeTopology is a speculative draft tree of at most 64 nodes in topological order. Node 0 is the root: the token the previous step emitted, which the target model has not yet seen. Every other node is a draft token whose parent precedes it.

func BuildDraftTreeTopology

func BuildDraftTreeTopology(parentIdx []int) (DraftTreeTopology, error)

BuildDraftTreeTopology validates parentIdx and computes the ancestor masks that MTPPagedAttention takes as its draft mask. Unlike TreeDraftMask it requires a single tree: only node 0 may have parent -1.

func BuildRegularDraftTree

func BuildRegularDraftTree(depth, branchFactor, maxNodes int) (DraftTreeTopology, error)

BuildRegularDraftTree constructs a topological DraftTreeTopology with root node 0, tree depth up to depth, branching factor branchFactor, and at most maxNodes total nodes (1..64).

func (DraftTreeTopology) NumNodes

func (t DraftTreeTopology) NumNodes() int

NumNodes returns the number of nodes in t.

type EarlyExitConfig

type EarlyExitConfig struct {
	Name            string
	Tokens          int // tokens in the batch, 1..1<<20
	Dim             int // floats per token read by the probe, 1..8192
	NumLayers       int
	CheckpointStep  int // test every CheckpointStep layers from MinLayer (0 means 1)
	MinLayer        int // earliest layer after which a token may exit
	Criterion       ExitCriterion
	Threshold       float32
	TileM           int  // rows per tile, a multiple of 4 (0 means 128)
	PropagateSkipKV bool // copy exited tokens' h into later layers' KV
	CLC             bool // persistent Name_tiles with clusterlaunchcontrol
}

EarlyExitConfig configures token-adaptive depth (CALM / SkipDecode style early exit) decided on the device inside a CUDA graph conditional WHILE loop over layers. Each iteration runs two emitted kernels:

Name_tiles  run layer l for the active tokens, TileM rows per tile
Name_probe  test the tokens that ran layer l at checkpoints, propagate
            the KV of exited tokens, compact the survivors into
            active_idx and set the loop condition

Name_tiles calls a device function the caller defines,

__device__ void Name_row(void* ctx, int layer, int32_t token);

for every active token of every active tile. It is launched over the static grid of all tiles. With CLC it is persistent: a resident CTA claims further tiles with clusterlaunchcontrol.try_cancel and stops at the first tile past the active count, so the tiles freed by early exit are cancelled before they launch. Without CLC every CTA of the static grid starts and returns at once if its tile is inactive.

Name_probe runs as one block. It compacts with vote.sync.ballot and popc in token order, so active_idx is a stable, order-preserving list whose padding up to whole tiles is -1; read four at a time it is the index list of TMA .gather4 row loads.

The probe reads Dim floats per token from h (and, for ExitHiddenCosine, from hprev). For the probe-head criteria, h holds the probe logits. With PropagateSkipKV, the probe copies an exited token's h row into kv for each later layer, so later tokens never attend to an unwritten KV slot; the copy stands in for a learned projection.

The kernels were run on the host emulator only. The CLC path needs sm_100 or later and uses the helpers of package tcgen05; the plain path uses no sm_90+ instructions.

func (EarlyExitConfig) CUDA

func (c EarlyExitConfig) CUDA() (string, error)

CUDA returns Name_probe and Name_tiles (without nvrtc.Prelude). Buffers: h and hprev [Tokens][Dim]; kv [NumLayers][Tokens][Dim]; exit_layer [Tokens], NumLayers while active; active_idx [StaticTiles*TileM]; ctrl {next layer, active tokens, active tiles}, initially {0, Tokens, StaticTiles} with active_idx the identity padded with -1; tiles_run counts tiles run.

func (EarlyExitConfig) Checkpoint

func (c EarlyExitConfig) Checkpoint(layer int) bool

Checkpoint reports whether tokens may exit after layer.

func (EarlyExitConfig) Launcher

func (c EarlyExitConfig) Launcher() (string, error)

Launcher returns host functions Name_probe_launch and Name_tiles_launch taking the kernel parameters followed by a cudaStream_t. The tiles launcher launches the static grid of StaticTiles blocks.

func (EarlyExitConfig) Probe

func (c EarlyExitConfig) Probe(curr, prev []float32) (score float64, exit bool)

Probe returns the criterion's score for one token, computed in float64, and whether it lets the token exit. prev is used only by ExitHiddenCosine.

func (EarlyExitConfig) Source

func (c EarlyExitConfig) Source() (string, error)

Source returns nvrtc.Prelude, the kernels and their launchers. The caller appends the definition of Name_row.

func (EarlyExitConfig) StaticTiles

func (c EarlyExitConfig) StaticTiles() int

StaticTiles returns the number of TileM-row tiles covering all tokens.

type ExitCriterion

type ExitCriterion uint8

An ExitCriterion selects the per-token test that lets a token leave the layer stack early.

const (
	// ExitHiddenCosine exits when cos(h⁽ˡ⁾, h⁽ˡ⁻¹⁾) >= Threshold: the layer
	// barely changed the hidden state.
	ExitHiddenCosine ExitCriterion = iota
	// ExitProbeEntropy exits when the entropy, in nats, of the softmax of a
	// probe head's logits is <= Threshold.
	ExitProbeEntropy
	// ExitTop2Margin exits when the largest probe logit exceeds the second
	// largest by >= Threshold.
	ExitTop2Margin
)

func (ExitCriterion) String

func (c ExitCriterion) String() string

type ForwardRuntimeEstimator

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

ForwardRuntimeEstimator estimates forward pass latency as a function of total query tokens (seqlensQ) and total KV cache tokens (seqlensK). It uses a two-tier (recent + old) sliding window of size MaxWindowSize, per-bucket MedianTrackers, and a dynamically estimated kvCacheSlope (dt / d_seqlens_k).

func NewForwardRuntimeEstimator

func NewForwardRuntimeEstimator(buckets []int) *ForwardRuntimeEstimator

NewForwardRuntimeEstimator constructs a ForwardRuntimeEstimator for the given CUDA graph token buckets.

func (*ForwardRuntimeEstimator) Estimate

func (e *ForwardRuntimeEstimator) Estimate(seqlensQ int, seqlensK int) float64

Estimate returns the estimated forward pass duration in milliseconds for seqlensQ total query tokens and seqlensK total KV cache tokens, linearly interpolating between calibrated bucket medians and adding kvCacheSlope * seqlensK.

func (*ForwardRuntimeEstimator) KVCacheSlope

func (e *ForwardRuntimeEstimator) KVCacheSlope() float64

KVCacheSlope returns the estimated latency slope (ms per KV token).

func (*ForwardRuntimeEstimator) Record

func (e *ForwardRuntimeEstimator) Record(pt PerfPoint)

Record adds a runtime observation to the recent window, rotating recent to old when recentCount reaches MaxWindowSize.

func (*ForwardRuntimeEstimator) Update

func (e *ForwardRuntimeEstimator) Update(pt PerfPoint)

Update is an alias for Record.

type GrammarBitmask

type GrammarBitmask struct {
	VocabSize int
	Words     []uint32
}

A GrammarBitmask is the set of tokens a structured-output grammar allows in its current state, packed as XGrammar and llguidance pack it: bit v%32 of Words[v/32] is set iff token v is allowed.

func AllowAllGrammar

func AllowAllGrammar(vocabSize int) GrammarBitmask

AllowAllGrammar returns a bitmask over vocabSize tokens that allows all.

func NewGrammarBitmask

func NewGrammarBitmask(vocabSize int) GrammarBitmask

NewGrammarBitmask returns a bitmask over vocabSize tokens that allows none.

func (GrammarBitmask) Allow

func (m GrammarBitmask) Allow(v int)

Allow adds token v to m.

func (GrammarBitmask) Allowed

func (m GrammarBitmask) Allowed(v int) bool

Allowed reports whether m allows token v.

type GrammarSampler

type GrammarSampler struct {
	Name    string
	Params  SamplingParams
	Threads int // threads per block, a power of two in 32..1024 (0 means 256)
}

GrammarSampler configures a kernel that samples one token per row of logits under a grammar bitmask without writing any vocabulary-sized buffer: each block reads its row of logits, bitmask and seen-token bitmask a few times and writes only the token and its log-probability.

Sampling uses the Gumbel-max trick: the token maximizing logit/T + G_v, with G_v = -ln(-ln U_v) and U_v from Philox4x32, is a sample from softmax(logit/T). Disallowed tokens never enter the maximum. Top-k and top-p are applied by rejection, as FlashInfer's samplers do: a candidate whose rank or preceding probability mass puts it outside the kept set is rejected, and the next round, with fresh noise, samples only among tokens ranked above it. Every round shrinks the candidate set and the top-ranked token is always kept, so the loop ends, and conditioning on acceptance leaves exactly the kept set's distribution. A round costs two passes over the row.

The logarithms use lg2.approx.ftz.f32 scaled by ln 2. Each block reduces in a fixed order, which GrammarSampler.Sample reproduces on the host, so the two agree except where float rounding of exp and log differs at a near tie.

The kernel reads logits from global memory; fusing it into the epilogue of the LM-head GEMM, so that logits never reach memory at all, is not done here. It uses no sm_90+ instructions and was run on the host emulator; the CUDA_EGRAPH_HOPPER_NATIVE tests run it on the GPU.

func (GrammarSampler) CUDA

func (g GrammarSampler) CUDA() (string, error)

CUDA returns the kernel (without nvrtc.Prelude). Its parameters are row-major logits [rows][VocabSize], mask and seen [rows][(VocabSize+31)/32] (seen may be null), steps [rows], and the outputs tokens and logprobs [rows]. A row whose grammar allows no token gets token -1.

func (GrammarSampler) Grid

func (g GrammarSampler) Grid(rows int) (grid, block [3]int)

Grid returns the launch shape for rows rows: one block per row.

func (GrammarSampler) Launcher

func (g GrammarSampler) Launcher() (string, error)

Launcher returns a host function

void Name_launch(int rows, <kernel params...>, cudaStream_t stream)

func (GrammarSampler) Sample

func (g GrammarSampler) Sample(logits []float32, mask GrammarBitmask, seen []uint32, step uint64) (int32, float32, error)

Sample runs the kernel's algorithm for one row on the host, in float32, with the kernel's per-thread partition and reduction order. It returns an error, not token -1, when the grammar allows no token.

func (GrammarSampler) Source

func (g GrammarSampler) Source() (string, error)

Source returns nvrtc.Prelude, the kernel and its launcher.

type KVBlockReleaser

type KVBlockReleaser interface {
	Release(blocks []int) error
}

KVBlockReleaser releases branch-owned private blocks. PagedCache and BlockAllocator in cudakv implement this interface. Release must wait for any outstanding GPU use before freeing blocks. On error it must leave ownership unchanged so the branch operation can be retried.

type LayerCompactionState

type LayerCompactionState struct {
	Layer          int
	ActiveTokenIdx []int32    // tokens still running, in token order
	ExitedAtLayer  []int      // per token: the layer after which it exited, or NumLayers
	Gather4Quads   [][4]int32 // ActiveTokenIdx in fours, the last padded with -1
	ActiveTiles    int        // TileM-row tiles the next layer runs
	CancelledTiles int        // static tiles the next layer skips
}

LayerCompactionState is the active set after one layer's exit test.

func SimulateAdaptiveDepthLayer

func SimulateAdaptiveDepthLayer(hCurr, hPrev [][]float32, prevExited []int, layer int, cfg EarlyExitConfig) (LayerCompactionState, error)

SimulateAdaptiveDepthLayer is the host reference for Name_probe at layer: tokens with prevExited[t] == NumLayers ran the layer and, at a checkpoint, exit if cfg's criterion holds on hCurr[t] (and hPrev[t]). The survivors are compacted in token order.

Example
cfg := EarlyExitConfig{Tokens: 6, Dim: 2, NumLayers: 4, MinLayer: 1, Criterion: ExitHiddenCosine, Threshold: 0.99, TileM: 4}
prev := [][]float32{{1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}}
// Tokens 1, 2 and 4 turned; the others kept their direction.
curr := [][]float32{{2, 0}, {0, 1}, {1, 1}, {3, 0}, {-1, 0}, {1, 0}}
st, err := SimulateAdaptiveDepthLayer(curr, prev, []int{4, 4, 4, 4, 4, 4}, 1, cfg)
if err != nil {
	panic(err)
}
fmt.Println(st.ActiveTokenIdx, st.Gather4Quads, st.ActiveTiles, st.CancelledTiles)
fmt.Println(st.ExitedAtLayer)
Output:
[1 2 4] [[1 2 4 -1]] 1 1
[1 4 4 1 4 1]

type MTPConfig

type MTPConfig struct {
	NumDraftHeads int // Number of speculative future tokens to predict in parallel (e.g. 2, 4)
	Dim           int
	VocabSize     int
}

MTPConfig configures Multi-Token Prediction (MTP) speculative draft heads for CUDA execution.

func (MTPConfig) Validate

func (cfg MTPConfig) Validate() error

Validate verifies the parameters of MTPConfig.

type MTPPagedAttention

type MTPPagedAttention struct {
	Name          string
	NumHeads      int     // total query heads (H_q = KVHeads * G)
	KVHeads       int     // KV heads
	HeadDim       int     // D (e.g., 64, 128)
	PageSize      int     // tokens per page (e.g., 16, 64)
	MaxPages      int     // stride of page_table per batch row
	QTokensPerSeq int     // number of query/draft tokens per sequence (1..64, e.g., 4 or 8)
	Scale         float32 // softmax scale (defaults to 1/sqrt(HeadDim))
	Softcap       float32 // optional logit softcap (>0 applies cap*tanh(s/cap))
	KVFP8         bool    // E4M3 KV cache with float k_scale, v_scale
	Gate          bool    // fuse sigmoid(Gate) multiply on output
	Swizzle       bool    // XOR shared-memory swizzle for K/V tiles (128B for WGMMA)
	WGMMA         bool    // warpgroup m64n64k32 FP8 WGMMA when G*QTokensPerSeq >= 8 && HeadDim%32 == 0 && KVFP8
}

MTPPagedAttention configures a multi-token / speculative tree-verification paged attention kernel where QTokensPerSeq draft tokens per sequence share a single KV page-table walk and apply a bitpacked causal or tree attention mask.

func (MTPPagedAttention) CUDA

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

CUDA returns the device kernel source (without nvrtc.Prelude).

func (MTPPagedAttention) Grid

func (a MTPPagedAttention) Grid(batch int) (grid, block [3]int)

Grid returns the launch grid and block dimensions for batch sequences. One CTA of 128 threads serves one (sequence, KV head) pair and walks the KV page table once for all G * QTokensPerSeq query vectors.

func (MTPPagedAttention) Launcher

func (a MTPPagedAttention) Launcher() (string, error)

Launcher returns a host function

void Name_launch(int batch, <kernel params...>, cudaStream_t stream)

that raises the kernel's dynamic shared memory limit to MTPPagedAttention.SharedBytes and launches it.

func (MTPPagedAttention) Norm

Norm validates and fills defaults on a.

func (MTPPagedAttention) Reference

func (a MTPPagedAttention) Reference(q []uint16, c MTPPagedCache) ([]float64, error)

Reference computes the float64 reference output of MTPPagedAttention for BF16 queries q ([batch * QTokensPerSeq * NumHeads * HeadDim]).

func (MTPPagedAttention) SharedBytes

func (a MTPPagedAttention) SharedBytes() int

SharedBytes returns the dynamic shared memory size in bytes the kernel needs, or 0 if a is invalid.

func (MTPPagedAttention) Source

func (a MTPPagedAttention) Source() (string, error)

Source returns nvrtc.Prelude, the kernel and its launcher.

type MTPPagedCache

type MTPPagedCache struct {
	KBF16, VBF16 []uint16 // when !KVFP8: [totalPages * PageSize, KVHeads, HeadDim]
	KFP8, VFP8   []uint8  // when KVFP8:  [totalPages * PageSize, KVHeads, HeadDim]
	PageTable    []int32  // [batch, MaxPages]
	SeqLens      []int32  // [batch]
	DraftMask    []uint64 // nil (causal default) or [batch * QTokensPerSeq]
	KScale       float32  // when KVFP8 (0 defaults to 1)
	VScale       float32  // when KVFP8 (0 defaults to 1)
	Gate         []uint16 // when Gate: BF16 [batch * QTokensPerSeq * NumHeads * HeadDim]
}

MTPPagedCache holds the inputs for MTPPagedAttention.Reference.

type MedianTracker

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

MedianTracker maintains an online running median using a max-heap (lo) for the lower half of samples and a min-heap (hi) for the upper half, matching the two-partition MedianTracker in DeepInfer's csrc/engine/mtp_varlen.hpp.

Example
package main

import (
	"fmt"

	nnspec "github.com/tmc/lib/nvidia/x/nn/spec"
)

func main() {
	mt := nnspec.NewMedianTracker()
	for _, v := range []float64{1.8, 1.2, 2.4, 1.5, 1.9} {
		mt.Update(v)
	}
	fmt.Printf("count=%d median=%.1f\n", mt.Count(), mt.Median())
}
Output:
count=5 median=1.8

func NewMedianTracker

func NewMedianTracker() *MedianTracker

NewMedianTracker returns an initialized MedianTracker. The zero value of MedianTracker is also ready to use.

func (*MedianTracker) Clear

func (m *MedianTracker) Clear()

Clear removes all samples from the tracker.

func (*MedianTracker) Count

func (m *MedianTracker) Count() int

Count returns the total number of samples currently in the tracker.

func (*MedianTracker) Median

func (m *MedianTracker) Median() float64

Median returns the exact median of all observed values, or 0 if empty.

func (*MedianTracker) Update

func (m *MedianTracker) Update(x float64)

Update inserts x into the two-heap tracker and rebalances the heaps so that len(lo) == len(hi) or len(lo) == len(hi)+1.

type NgramDrafter

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

NgramDrafter drafts candidate tokens by matching recent sequence context against an n-gram table.

func NewNgramDrafter

func NewNgramDrafter(n int) *NgramDrafter

NewNgramDrafter creates an n-gram drafter with context window size n (typically 2..4).

func (*NgramDrafter) Draft

func (d *NgramDrafter) Draft(context []int32, maxDraft int) []int32

Draft predicts up to maxDraft next candidate tokens from the current context.

func (*NgramDrafter) Feed

func (d *NgramDrafter) Feed(tokens []int32)

Feed updates the internal n-gram index with new token observations.

type PerfPoint

type PerfPoint struct {
	TotalSeqlensQ int
	TotalSeqlensK int
	DurationMS    float64
}

PerfPoint records the observed latency of one forward decode step at a given total query token count and total KV cache token count.

type ProposalState

type ProposalState int

ProposalState tracks the lifecycle of a speculative proposal branch.

const (
	ProposalProposed ProposalState = iota
	ProposalCommitted
	ProposalRolledBack
)

func (ProposalState) String

func (s ProposalState) String() string

type ReasoningBranch

type ReasoningBranch struct {
	BranchID      int
	ParentID      int
	Depth         int
	TokenIDs      []int32
	PRMScore      float32
	CumulativeVal float32
	Active        bool
}

ReasoningBranch represents one candidate reasoning trajectory in a parallel test-time compute (Best-of-N / MCTS / Tree-of-Thoughts) rollout that shares the common prompt prefix KV cache tile.

type ReasoningMCTSTree

type ReasoningMCTSTree struct {
	Name            string
	PromptTokens    int     // Shared prompt prefix length in tokens
	PageSize        int     // KV cache tokens per page (default 16)
	NumBranches     int     // K parallel reasoning branches sharing the prompt prefix tile
	MaxSurviving    int     // Max branches surviving after PRM pruning
	MinPRMThreshold float32 // Minimum PRM value-head score to keep a branch alive
	ExplorationC    float32 // UCB1 / PUCT exploration constant (default 1.41421356)
	Branches        []ReasoningBranch
}

ReasoningMCTSTree models parallel test-time compute (Best-of-N / Monte Carlo Tree Search / Tree-of-Thoughts) over a shared prompt prefix KV tile across K active reasoning branches, with an in-megakernel Process Reward Model (PRM) value-head scoring and branch-pruning stage.

func NewReasoningMCTSTree

func NewReasoningMCTSTree(promptTokens, numBranches, maxSurviving int, minPRMThreshold float32) (*ReasoningMCTSTree, error)

NewReasoningMCTSTree constructs a ReasoningMCTSTree with numBranches initial candidate branches sharing a prompt prefix of promptTokens tokens.

func (*ReasoningMCTSTree) CUDA

func (t *ReasoningMCTSTree) CUDA() string

CUDA emits the in-megakernel Process Reward Model (PRM) value-head branch scoring and warp-ballot compaction device stage.

func (*ReasoningMCTSTree) Prune

func (t *ReasoningMCTSTree) Prune(branchScores []float32) (survivingIndices []int, prefixTileReuseFactor float64, err error)

Prune applies PruneReasoningBranchesOnDevice to branchScores and updates t.Branches in place, marking pruned branches inactive and returning the surviving branch indices and the shared prefix tile reuse factor.

func (*ReasoningMCTSTree) SharedPrefixPages

func (t *ReasoningMCTSTree) SharedPrefixPages() int

SharedPrefixPages returns the number of shared KV cache pages covering the common prompt prefix tile. All active reasoning branches read these pages once into shared memory / L2 instead of duplicating the prompt KV across K branches.

type SamplerRuntimeEstimator

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

SamplerRuntimeEstimator estimates token sampling latency using a 9-sample median filter for base overhead plus linear scaling in totalTokens.

func NewSamplerRuntimeEstimator

func NewSamplerRuntimeEstimator() *SamplerRuntimeEstimator

NewSamplerRuntimeEstimator constructs a 9-sample median filter estimator for sampler latency.

func (*SamplerRuntimeEstimator) Estimate

func (s *SamplerRuntimeEstimator) Estimate(totalTokens int) float64

Estimate returns the predicted sampler latency in milliseconds for totalTokens.

func (*SamplerRuntimeEstimator) Record

func (s *SamplerRuntimeEstimator) Record(totalTokens int, durationMS float64)

Record inserts a sampler runtime measurement for totalTokens into the 9-sample ring buffer.

func (*SamplerRuntimeEstimator) Update

func (s *SamplerRuntimeEstimator) Update(durationMS float64)

Update records a sampler latency observation with a default token count of 1.

type SamplingParams

type SamplingParams struct {
	VocabSize         int
	Temperature       float32
	TopK              int
	TopP              float32
	MinP              float32
	RepetitionPenalty float32
	Seed              uint64 // Philox4x32 key for the Gumbel noise
}

SamplingParams configures token sampling. The pipeline, applied to one row of logits, is

  1. drop tokens the grammar bitmask disallows;
  2. divide positive logits of already-seen tokens by RepetitionPenalty and multiply negative ones by it (the CTRL / Hugging Face rule);
  3. divide by Temperature (0 means greedy: emit the largest logit);
  4. drop tokens whose probability is below MinP times the largest;
  5. rank the rest by logit, ties to the lower token ID, and keep a token iff its rank is below TopK and the probability of the tokens ranked above it is below TopP (the joint top-k/top-p rule; both use the distribution after step 4);
  6. sample from the kept tokens in proportion to their probability.

A zero field disables its step, as do TopP >= 1 and RepetitionPenalty 1.

func (SamplingParams) Probs

func (p SamplingParams) Probs(logits []float32, mask GrammarBitmask, seen []uint32) ([]float64, error)

Probs returns the exact distribution of the sampling pipeline over the vocabulary, computed in float64 by sorting. It is the reference for SampleTokenFused and GrammarSampler. seen is a packed bitmask of tokens the penalty applies to, or nil.

type SequenceMTPState

type SequenceMTPState struct {
	SeqID       int64
	ContextLen  int
	AcceptProbs []float64
	EWMAProb    float64
	FixedLen    int
}

SequenceMTPState holds per-sequence state for confidence-scheduled variable-length MTP.

type SpeculationCache

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

SpeculationCache is a bounded cache for speculation outputs keyed by SpeculationCacheKey.

func NewSpeculationCache

func NewSpeculationCache(capacity int) *SpeculationCache

NewSpeculationCache creates a bounded speculation cache with maximum entries capacity.

func (*SpeculationCache) Get

Get returns a copy of the entry matching the exact key. Changing the returned entry does not change the cache.

func (*SpeculationCache) InvalidateGeneration

func (c *SpeculationCache) InvalidateGeneration(generation uint64) int

InvalidateGeneration purges entries matching a specific generation or earlier.

func (*SpeculationCache) InvalidateModel

func (c *SpeculationCache) InvalidateModel(activeModelDigest [32]byte) int

InvalidateModel purges all entries not matching the active modelDigest.

func (*SpeculationCache) Put

Put stores a copy of entry, replacing any entry with the same key. It evicts the oldest entry when the cache is full. If entry's key has a zero DraftDigest, Put returns ErrDraftDigestRequired and leaves the cache unchanged; any cached result, including a bonus token alone, depends on the draft weights.

type SpeculationCacheEntry

type SpeculationCacheEntry struct {
	Key        SpeculationCacheKey
	DraftPath  []int32
	Logits     [][]float32
	BonusToken int32
}

SpeculationCacheEntry stores cached draft proposals or verification logits.

type SpeculationCacheKey

type SpeculationCacheKey struct {
	ModelDigest   [32]byte
	DraftDigest   [32]byte
	PrefixHash    [32]byte
	BranchID      BranchID
	StartPosition int
	NumTokens     int
	NumericalMode string // e.g. "FP32", "FP16", "BF16"
	Generation    uint64
}

SpeculationCacheKey binds model and draft weight digests, prefix tokens, sequence positions, numerical mode, and generation number. A zero DraftDigest means the key does not identify draft weights, so SpeculationCache refuses it. BatchCycleResult.Key always sets it. DraftDigest is declared by the caller; the cache does not check it against any weights.

func ComputeSpeculationKey

func ComputeSpeculationKey(modelDigest []byte, prefixTokens []int32, branchID BranchID, startPos, numTokens int, numMode string, generation uint64) SpeculationCacheKey

ComputeSpeculationKey constructs a SpeculationCacheKey with a zero DraftDigest, which callers must set before using the key with SpeculationCache. A modelDigest of exactly 32 bytes is used as the model digest unchanged; any other length is an identity, such as "org/model@rev", that is hashed in full with SHA-256.

type SpeculativeDecodeController

type SpeculativeDecodeController struct {
	Name        string
	DraftTokens int // K: speculative draft tokens verified per step (1..64)
	MaxSteps    int // maximum conditional WHILE steps per burst (0 defaults to 64)
}

SpeculativeDecodeController configures a device-side speculative draft verification and KV state controller kernel designed to run as the tail node of a CUDA Conditional WHILE Graph (cudaGraphConditionalHandle).

In each conditional WHILE iteration, the kernel compares K speculative draft token IDs (draft_tokens[0..K-1]) against K+1 greedy/sampled token IDs produced by the target model (target_greedy_tokens[0..K]), appends the longest matching prefix of length a (0 <= a <= K) plus the bonus token target_greedy_tokens[a] (a + 1 tokens total) to output_tokens starting at *cur_seq_len, updates *cur_seq_len, accepted_per_step[*step_idx], and *step_idx in place on the device without a CPU round-trip, and calls cudaGraphSetConditional(cond_handle, keep_going ? 1u : 0u).

func (SpeculativeDecodeController) CUDA

CUDA returns the device kernel source (without nvrtc.Prelude).

func (SpeculativeDecodeController) Grid

func (c SpeculativeDecodeController) Grid() (grid, block [3]int)

Grid returns the single-CTA launch grid and 32-thread block dimensions for the device-side speculative decode controller.

func (SpeculativeDecodeController) Launcher

func (c SpeculativeDecodeController) Launcher() (string, error)

Launcher returns a host function

void Name_launch(<kernel params...>, cudaStream_t stream)

that launches the speculative decode conditional graph controller kernel.

func (SpeculativeDecodeController) Reference

Reference computes the exact host reference for a multi-step speculative decode conditional loop.

func (SpeculativeDecodeController) RunEmulatedLoop

RunEmulatedLoop executes the multi-step speculative decode conditional loop on the host emulator via nnhostemu.RunConditionalWhile with zero CPU round-trips between iterations.

func (SpeculativeDecodeController) Source

Source returns nvrtc.Prelude, the kernel, and its launcher.

type SpeculativeDecodeInput

type SpeculativeDecodeInput struct {
	InitialTokens []int32                 // initial prefix tokens in output_tokens[0..len(InitialTokens)-1]
	Steps         []SpeculativeDecodeStep // speculative verification steps
	EOSTokenID    int32                   // EOS token ID (< 0 disables early EOS termination)
	MaxSeqLen     int                     // capacity of output_tokens buffer
}

SpeculativeDecodeInput holds the initial sequence state and per-step draft and target tokens for SpeculativeDecodeController.Reference and SpeculativeDecodeController.RunEmulatedLoop.

type SpeculativeDecodeResult

type SpeculativeDecodeResult struct {
	OutputTokens    []int32  // output_tokens[:FinalSeqLen]
	FinalSeqLen     int      // final *cur_seq_len
	AcceptedPerStep []int32  // accepted_per_step[:StepsExecuted]
	StepsExecuted   int      // final *step_idx
	FinalCondition  uint32   // final condition value in cond_handle
	HandleUpdates   int      // number of cudaGraphSetConditional updates
	IterationTrace  []uint32 // condition value after each iteration
}

SpeculativeDecodeResult holds the final sequence and step state produced by SpeculativeDecodeController.Reference or SpeculativeDecodeController.RunEmulatedLoop.

type SpeculativeDecodeStep

type SpeculativeDecodeStep struct {
	Draft        []int32 // length K
	TargetGreedy []int32 // length K + 1
}

SpeculativeDecodeStep holds the device inputs for one speculative decode verification pass: Draft[0..K-1] are the K draft token IDs proposed for the step, and TargetGreedy[0..K] are the K+1 greedy/sampled token IDs produced by the target model across the root position and the K draft positions.

type TreeAccept

type TreeAccept struct {
	// Path lists the accepted nodes from the root: Path[0] == 0 and
	// Path[j+1] is a child of Path[j]. Its tokens are committed to the
	// sequence and their KV entries kept.
	Path []int
	// Bonus is the token the target model emits after the last node of
	// Path: its greedy choice there, or a sample from the residual
	// distribution. It becomes the root of the next tree.
	Bonus int32
}

A TreeAccept is the outcome of verifying one draft tree.

func AcceptDraftTreeGreedy

func AcceptDraftTreeGreedy(tree DraftTreeTopology, tokens, targetArgmax []int32) (TreeAccept, error)

AcceptDraftTreeGreedy verifies tree against greedy target decoding. tokens[i] is node i's token and targetArgmax[i] the target model's argmax next token after the root-to-i path. Starting from the root, it moves to the first child (in node order) whose token equals the target's argmax and stops when no child does, so Path is the longest root-to-node path that greedy decoding of the target would itself produce.

Example
// The root (node 0) has drafts 1 and 2; node 3 continues node 2.
tree, err := BuildDraftTreeTopology([]int{-1, 0, 0, 2})
if err != nil {
	panic(err)
}
tokens := []int32{7, 41, 42, 43}
// The target's argmax after each node's path.
argmax := []int32{42, 0, 43, 50}
a, err := AcceptDraftTreeGreedy(tree, tokens, argmax)
if err != nil {
	panic(err)
}
fmt.Printf("masks %b\n", tree.AncestorMask)
fmt.Println("path", a.Path, "bonus", a.Bonus)
Output:
masks [1 11 101 1101]
path [0 2 3] bonus 50

func AcceptDraftTreeSampled

func AcceptDraftTreeSampled(tree DraftTreeTopology, tokens []int32, draftProbs, targetProbs [][]float32, seed uint64, step, seq uint32) (TreeAccept, error)

AcceptDraftTreeSampled verifies tree by multi-candidate speculative sampling (SpecInfer, Miao et al. 2024). draftProbs[i] is the draft distribution node i's children were drawn from, independently, and targetProbs[i] the target's next-token distribution after the root-to-i path. At each node the children are tried in order: child x is accepted with probability min(1, r(x)/q(x)), where r starts as the target distribution and becomes norm(max(0, r-q)) after each rejection; if every child is rejected, or there are none, the bonus token is drawn from r. If each node's children were drawn independently from q, the emitted tokens are distributed exactly as target sampling.

The k-th uniform drawn in the walk is word 0 of Philox4x32({step, seq, k, 0}, {seed, seed>>32}), and the arithmetic is float32 in the order TreeSpecVerify's kernel uses, so the two agree bit for bit.

type TreeNode

type TreeNode struct {
	ID       int
	Token    int32
	ParentID int
	Children []*TreeNode
	Depth    int
}

TreeNode represents a candidate token node within a speculative candidate tree.

type TreeSpecInput

type TreeSpecInput struct {
	Prefix     [][]int32           // per sequence: committed tokens; KV for them is [TreeSpecPrefixKV]
	Roots      []int32             // per sequence: first root token
	Steps      [][]TreeSpecSeqStep // [step][sequence]
	TotalPages int                 // KV pool size in pages
	EOSTokenID int32               // < 0 disables EOS
	Seed       uint64              // sampled: Philox key
}

TreeSpecInput is the starting state and per-step trees for TreeSpecVerify.Reference and TreeSpecVerify.RunEmulatedLoop.

type TreeSpecSeqStep

type TreeSpecSeqStep struct {
	Parent       []int
	Tokens       []int32
	TargetArgmax []int32     // greedy
	DraftProbs   [][]float32 // sampled: per node
	TargetProbs  [][]float32 // sampled: per node
}

TreeSpecSeqStep is one sequence's draft tree for one step: what the draft model and the target forward pass hand the verifier. Tokens[0] is ignored; the root is the sequence's previous bonus token.

type TreeSpecState

type TreeSpecState struct {
	Tokens    [][]int32  // per sequence: committed tokens
	Roots     []int32    // per sequence: pending root token (-1 after EOS)
	Accepted  [][]int32  // [step][sequence]: tokens committed (0 if inactive)
	Steps     int        // iterations run
	PageTable [][]int32  // per sequence: pages in use
	FreePages []int32    // free stack, bottom first
	KV        [][]uint32 // per sequence: KVWords words per committed token, read through the page table
}

TreeSpecState is the device state after the loop ends.

type TreeSpecVerify

type TreeSpecVerify struct {
	Name      string
	Nodes     int  // tree nodes per sequence per step, 1..64
	Batch     int  // sequences, 1..32
	KVWords   int  // 32-bit words of K and V per token, all layers (1..4096)
	PageSize  int  // tokens per KV page
	MaxPages  int  // page_table stride per sequence
	MaxSteps  int  // WHILE iteration cap (0 means 64)
	Sampled   bool // speculative sampling instead of greedy verification
	VocabSize int  // with Sampled: distribution length
}

TreeSpecVerify configures the device-resident tree verification kernels that form the tail of a CUDA graph conditional WHILE loop. Each iteration of the loop runs

Name_reserve   pop free KV pages so every active sequence can hold a tree
(draft, target forward)  write the tree tokens, target outputs and tree KV
Name           walk each tree, compact the accepted KV, free the pages
               the accepted prefix no longer needs, set the condition

with no host round trip. Name_reserve and Name are emitted here; the draft and target forward passes are the caller's. The target forward writes node i's KV at sequence position seqlen+i, using the tree mask from BuildDraftTreeTopology in MTPPagedAttention.

Both kernels run as one warp; lane b handles sequence b and lane 0 updates the shared free-page stack in sequence order, so the page assignment is deterministic and matches TreeSpecVerify.Reference. The KV copy is plain 32-bit loads and stores, not TMA; this is a control kernel, not a bandwidth-tuned one.

The kernels use no sm_90+ instructions. The conditional is set through cudaGraphSetConditional (CUDA 12.4+). They were checked on the host emulator (TreeSpecVerify.RunEmulatedLoop); a native graph harness for sm_121a is in the CUDA_EGRAPH_HOPPER_NATIVE tests.

func (TreeSpecVerify) CUDA

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

CUDA returns both kernels (without nvrtc.Prelude).

func (TreeSpecVerify) Grid

func (s TreeSpecVerify) Grid() (grid, block [3]int)

Grid returns the launch shape of both kernels: one block of one warp.

func (TreeSpecVerify) Launcher

func (s TreeSpecVerify) Launcher() (string, error)

Launcher returns host functions Name_reserve_launch and Name_launch that launch the two kernels with their parameters followed by a cudaStream_t.

func (TreeSpecVerify) Reference

func (s TreeSpecVerify) Reference(in TreeSpecInput) (*TreeSpecState, error)

Reference runs the loop on the host: the same page pool, tree walk, KV compaction and rollback as the kernels, with the emulated target forward pass of TreeSpecVerify.RunEmulatedLoop writing TreeSpecNodeKV.

func (TreeSpecVerify) RunEmulatedLoop

func (s TreeSpecVerify) RunEmulatedLoop(ctx context.Context, in TreeSpecInput) (*TreeSpecState, error)

RunEmulatedLoop runs the loop on the host emulator through nnhostemu.RunConditionalWhile. Each iteration launches Name_reserve, a fixture kernel standing in for the draft and target forward passes (it copies the step's tree, sets node 0 to the root and writes TreeSpecNodeKV at positions seqlen..seqlen+Nodes-1), and Name.

func (TreeSpecVerify) Source

func (s TreeSpecVerify) Source() (string, error)

Source returns nvrtc.Prelude, the kernels and their launchers.

type TreeVerificationResult

type TreeVerificationResult struct {
	AcceptedPath []int32
	AcceptedIDs  []int
	NumAccepted  int
	BonusToken   int32
	BestPathLen  int
}

TreeVerificationResult returns the longest accepted path in the tree and bonus token.

func VerifyTree

func VerifyTree(tree *DraftTree, targetLogits [][]float32) TreeVerificationResult

VerifyTree evaluates all tree candidates against target logits in a single pass.

type VarlenScheduleConfig

type VarlenScheduleConfig struct {
	NumSpecSteps   int
	Buckets        []int
	EWMADecay      float64
	MinDynamicProb float64
	StepOverheadMS float64
}

VarlenScheduleConfig configures the dynamic variable-length MTP scheduler.

type VarlenScheduleDecision

type VarlenScheduleDecision struct {
	TargetTotalQ            int
	BucketBsz               int
	SeqlensQ                []int
	EstimatedForwardMS      float64
	EstimatedExpectedAccept float64
	ThroughputScore         float64
}

VarlenScheduleDecision reports the selected token budget, bucket size, per-sequence query lengths, and throughput metrics for one decode step.

type VarlenScheduler

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

VarlenScheduler dynamically schedules per-sequence speculative draft verification lengths to maximize expected accepted tokens per millisecond across CUDA graph buckets.

Example
package main

import (
	"fmt"

	nnspec "github.com/tmc/lib/nvidia/x/nn/spec"
)

func main() {
	sched, err := nnspec.NewVarlenScheduler(nnspec.VarlenScheduleConfig{
		NumSpecSteps:   2,
		Buckets:        []int{2, 4, 8},
		StepOverheadMS: 0.05,
	})
	if err != nil {
		panic(err)
	}
	for i := 0; i < nnspec.MinSamplesForReliableEstimate; i++ {
		sched.RecordStep(nnspec.PerfPoint{TotalSeqlensQ: 2, TotalSeqlensK: 256, DurationMS: 1.0})
		sched.RecordStep(nnspec.PerfPoint{TotalSeqlensQ: 4, TotalSeqlensK: 256, DurationMS: 1.1})
		sched.RecordStep(nnspec.PerfPoint{TotalSeqlensQ: 8, TotalSeqlensK: 256, DurationMS: 5.0})
	}
	decision, err := sched.Schedule([]nnspec.SequenceMTPState{
		{SeqID: 1, ContextLen: 128, AcceptProbs: []float64{0.9, 0.8}, EWMAProb: 0.85},
		{SeqID: 2, ContextLen: 128, AcceptProbs: []float64{0.4, 0.2}, EWMAProb: 0.60},
	})
	if err != nil {
		panic(err)
	}
	fmt.Printf("totalQ=%d bucket=%d seqlensQ=%v\n", decision.TargetTotalQ, decision.BucketBsz, decision.SeqlensQ)
}
Output:
totalQ=4 bucket=4 seqlensQ=[3 1]

func NewVarlenScheduler

func NewVarlenScheduler(cfg VarlenScheduleConfig) (*VarlenScheduler, error)

NewVarlenScheduler validates cfg, applies defaults (EWMADecay = 0.9, MinDynamicProb = 0.3), and returns an initialized VarlenScheduler.

func (*VarlenScheduler) EWMAProb

func (s *VarlenScheduler) EWMAProb(seqID int64) (float64, bool)

EWMAProb returns the tracked EWMA acceptance probability for seqID.

func (*VarlenScheduler) RecordSampler

func (s *VarlenScheduler) RecordSampler(totalTokens int, durationMS float64)

RecordSampler updates the internal SamplerRuntimeEstimator with a completed sampler observation.

func (*VarlenScheduler) RecordStep

func (s *VarlenScheduler) RecordStep(pt PerfPoint)

RecordStep updates the internal ForwardRuntimeEstimator with a completed step observation.

func (*VarlenScheduler) Schedule

Schedule evaluates candidate token budgets across CUDA graph buckets using each sequence's EWMAProb (step N-2 signal) to choose TargetTotalQ maximizing expected accepted tokens per millisecond, and greedily allocates SeqlensQ up to 1+NumSpecSteps using step N-1 marginal cumulative acceptance probabilities.

func (*VarlenScheduler) UpdateAcceptance

func (s *VarlenScheduler) UpdateAcceptance(seqID int64, draftLen int, accepted int)

UpdateAcceptance updates the per-sequence EWMA acceptance probability using ewma = decay*old + (1-decay)*(accepted/draftLen).

type VerificationResult

type VerificationResult struct {
	AcceptedTokens []int32
	BonusToken     int32
	TotalEmitted   int
	AcceptedCount  int
}

VerificationResult holds accepted candidate tokens and the final transition token.

func VerifyGreedy

func VerifyGreedy(targetPredictions []int32, draftTokens []int32) VerificationResult

VerifyGreedy performs greedy speculative verification against top predictions of target model. Supply one target prediction per draft token, plus an optional bonus prediction. Without a bonus prediction, an entirely accepted draft returns BonusToken -1 and TotalEmitted equal to AcceptedCount.

func VerifyStochastic

func VerifyStochastic(targetProbs [][]float32, draftProbs [][]float32, draftTokens []int32, rng *rand.Rand) VerificationResult

VerifyStochastic implements speculative sampling via rejection sampling.

Draft token i is accepted with probability min(1, p_target/p_draft). On rejection it samples the residual distribution max(0, p_target - p_draft), which is what makes the emitted sequence distributed exactly as the target model's own samples. Verification stops early at the first position not covered by both distributions.

type VerifyStageSourceConfig

type VerifyStageSourceConfig struct {
	VerifyStageName    string
	LogitsCType        string
	LogitsBF16         bool
	DraftNodes         int
	VocabSize          int
	BitmaskWords       int
	PerPositionBitmask bool
	HeadReadySlot      int
	HeadBlocks         int
}

VerifyStageSourceConfig configures EmitVerifyStageDeviceFunc.

Directories

Path Synopsis
Package dfly reads DFly2 drafter checkpoints and checks their compatibility with a paired DeepSeek V4.1 target before device execution.
Package dfly reads DFly2 drafter checkpoints and checks their compatibility with a paired DeepSeek V4.1 target before device execution.
Package paralleldraft implements the model-agnostic parts of parallel ("diffusion") speculative drafters such as DFlash, DSpark and DNeo.
Package paralleldraft implements the model-agnostic parts of parallel ("diffusion") speculative drafters such as DFlash, DSpark and DNeo.

Jump to

Keyboard shortcuts

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