Documentation
¶
Overview ¶
Package batch provides continuous token-level batch scheduling, RadixAttention prefix KV trees, and speculative batch verification cycles.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Index ¶
- Variables
- func ApplyZOSRemapCPU(prevTokens []int32, bonusTokens []int32, prevSeqlensK []int32, ...) (nextInputIDs []int32, nextSeqlensK []int32, err error)
- func MTPDraftDigest(c cudaspec.MTPConfig, projection, heads []float32) ([32]byte, error)
- func MatchContinuationBlocks(matchedTokens int, blockTable []int, blockSize int) (reusedBlocks []int, reusedTokenCount int)
- func PrefixHash(tokens []int) [32]byte
- func SpliceContinuation(tokenizer ExactSuffixTokenizer, existingTokens []int32, ...) (reusedTokens []int32, deltaTokens []int32, err error)
- func ZOSRemapKernelSource() (string, error)
- type BatchCycleRequest
- type BatchCycleResult
- type BatchDraftProducer
- type BatchDraftStep
- type BatchMetadata
- type BatchRowBinding
- type BatchScheduler
- func (s *BatchScheduler) BindIteration(iter *ScheduledIteration, bucket ShapeBucket) (*BatchMetadata, error)
- func (s *BatchScheduler) Cancel(id string) error
- func (s *BatchScheduler) CompleteStep(iter *ScheduledIteration, generatedTokens map[string]int32, ...) error
- func (s *BatchScheduler) RegisterResourceRelease(seqID string, cb func())
- func (s *BatchScheduler) Request(id string) (*Request, bool)
- func (s *BatchScheduler) Schedule() (*ScheduledIteration, error)
- func (s *BatchScheduler) Submit(req *Request) error
- type BatchVerifier
- type ContinuationTracker
- type ContinuationVisibility
- type ContinuousBatchScheduler
- func (s *ContinuousBatchScheduler) Admit(seq *InFlightSequence) error
- func (s *ContinuousBatchScheduler) Check() error
- func (s *ContinuousBatchScheduler) Complete(seqID string) error
- func (s *ContinuousBatchScheduler) ScheduleStep(ctx context.Context) (*ScheduledBatchStep, error)
- func (s *ContinuousBatchScheduler) SelectMinimalBucket(activeM int) (*specdecode.BucketMegakernelEntry, int, error)
- type DraftLogitsEngine
- type DraftLogitsFunc
- type ExactSuffixTokenizer
- type ExecutionEngine
- type ExecutionStep
- type FairnessPolicy
- type HostDeterministicEngine
- type InFlightSequence
- type MemoryBudgetTracker
- func (t *MemoryBudgetTracker) AllocSequence(seqID int64, shared []int, promptTokens int) ([]int, error)
- func (t *MemoryBudgetTracker) AppendToken(seqID int64) error
- func (t *MemoryBudgetTracker) CanAdmit(promptTokens int, sharedBlocks []int) bool
- func (t *MemoryBudgetTracker) FreeSequence(seqID int64)
- func (t *MemoryBudgetTracker) ReleasePrefix(blocks []int) error
- func (t *MemoryBudgetTracker) RetainPrefix(seqID int64, tokens int) ([]int, error)
- type PackedRow
- type PendingForwardError
- type PlanBindingFunc
- type PlanEngine
- func (e *PlanEngine) Close() error
- func (e *PlanEngine) Drain(ctx context.Context) error
- func (e *PlanEngine) ExecuteForward(ctx context.Context, step *ExecutionStep) (map[string]int32, map[string]error, error)
- func (e *PlanEngine) StepDone(id int64) bool
- func (e *PlanEngine) WaitStep(ctx context.Context, id int64) error
- type PlanSampleFunc
- type RadixKVTree
- func (t *RadixKVTree) CacheHits() int
- func (t *RadixKVTree) EvictLRU(neededPages int) (int, error)
- func (t *RadixKVTree) FreePages() int
- func (t *RadixKVTree) InsertPrefix(tokens, pages []int) (*cudakv.RadixNode, error)
- func (t *RadixKVTree) MatchPrefix(tokens []int) (matchedTokens int, pageIDs []int, node *cudakv.RadixNode)
- func (t *RadixKVTree) PageSize() int
- func (t *RadixKVTree) Release(node *cudakv.RadixNode)
- func (t *RadixKVTree) UsedPages() int
- type Request
- type RequestState
- type ScheduledBatchStep
- type ScheduledIteration
- type SchedulerConfig
- type SequencePhase
- type SessionContinuation
- type ShapeBucket
- type ZOSRemapPlan
- type ZOSRemapSpec
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrRequestNotFound = errors.New("cudabatch: request not found") ErrRequestAlreadyExists = errors.New("cudabatch: request already exists") ErrInvalidRequest = errors.New("cudabatch: invalid request parameters") ErrCapacityExhausted = errors.New("cudabatch: batch capacity or memory exhausted") ErrCorruptBlockTable = errors.New("cudabatch: corrupted block table") ErrRowBoundsViolation = errors.New("cudabatch: row bounds or shape violation") ErrExecutionInFlight = errors.New("cudabatch: execution step in flight") ErrWaitingTimeout = errors.New("cudabatch: request waiting timeout") )
Common errors returned by batch scheduling, admission, and binding.
var ErrInvalidZOSPlan = errors.New("cudabatch: invalid ZOS remap parameters")
ErrInvalidZOSPlan indicates invalid parameters or mismatched slice lengths in ZOS remap planning.
Functions ¶
func ApplyZOSRemapCPU ¶
func ApplyZOSRemapCPU( prevTokens []int32, bonusTokens []int32, prevSeqlensK []int32, acceptedCounts []int32, plan ZOSRemapPlan, ) (nextInputIDs []int32, nextSeqlensK []int32, err error)
ApplyZOSRemapCPU gathers compacted step N input token IDs and updates per-sequence KV cache lengths (nextSeqlensK) according to plan without host synchronization.
func MTPDraftDigest ¶
MTPDraftDigest hashes bounded draft weights with their shape and float32 bits. It does not assert that these weights belong to a caller's target model.
func MatchContinuationBlocks ¶
func MatchContinuationBlocks(matchedTokens int, blockTable []int, blockSize int) (reusedBlocks []int, reusedTokenCount int)
MatchContinuationBlocks checks how many whole blocks of existingTokens can be reused given blockSize.
func PrefixHash ¶
PrefixHash computes a deterministic SHA-256 digest over a token prefix.
func SpliceContinuation ¶
func SpliceContinuation(tokenizer ExactSuffixTokenizer, existingTokens []int32, existingText, newTurnText string, maxRollback int) (reusedTokens []int32, deltaTokens []int32, err error)
SpliceContinuation computes the tokens to append when continuing a conversation. To prevent BPE token boundary corruption (e.g. whitespace merging or subword changes across boundaries), it tokenizes the combined text and compares it with existingTokens. If the boundary merges a subword token, it rolls back the boundary by up to maxRollback tokens so that the continuation tokens cleanly align with the BPE vocabulary. If more than maxRollback trailing tokens of existingTokens differ, it reuses nothing: reusedTokens is nil and deltaTokens is the whole combined tokenization. In every case reusedTokens followed by deltaTokens is the tokenization of existingText+newTurnText. A negative maxRollback is an error.
func ZOSRemapKernelSource ¶
ZOSRemapKernelSource generates the NVRTC CUDA C++ source for zos_remap_and_pack_kernel, which computes device-side ZOS remap indices, compacted input token IDs, token positions, batch indices, and updated KV lengths.
Types ¶
type BatchCycleRequest ¶
type BatchCycleRequest struct {
// DraftDigest pins exact draft projection and head weights, including shape.
DraftDigest [32]byte
Key, ExpectedKey cudaspec.SpeculationCacheKey
Prefix []int32
PrefixSequence, Sequence int64
Hidden, DraftWeights, HeadWeights []float32
MTP cudaspec.MTPConfig
// DraftProducer optionally computes synchronous MTP draft logits for this
// admitted request. When nil, ExecuteBatchCycle uses cudaspec.MTPReference.
DraftProducer *BatchDraftProducer
}
BatchCycleRequest describes one bounded deterministic MTP speculation cycle. Key and ExpectedKey bind the admitted model, prefix, branch, position, numerical mode, and process/model generation. These are caller declarations, not independently measured model or device identity. Key and ExpectedKey must be equal; their DraftDigest is either zero or equal to DraftDigest.
type BatchCycleResult ¶
type BatchCycleResult struct {
// Key identifies the cycle's outcome for caching. Its DraftDigest is
// the verified digest of the request's draft weights.
Key cudaspec.SpeculationCacheKey
Outcome cudaspec.CycleOutcome
BranchID cudaspec.BranchID
KV *cudaspec.BranchKV
DraftOwner io.Closer
}
BatchCycleResult contains workload results and the branch's KV lease. A fully accepted branch stays live until the caller closes KV after use. Rejected branches are closed. Without independent Done proof, a drain error leaves KV or DraftOwner live even though the cycle failed; the owner must establish quiescence before closing it.
func ExecuteBatchCycle ¶
func ExecuteBatchCycle(ctx context.Context, a *cudakv.BlockAllocator, req BatchCycleRequest, v BatchVerifier) (result *BatchCycleResult, retErr error)
ExecuteBatchCycle computes MTP drafts (via req.DraftProducer when configured or cudaspec.MTPReference by default) and verifies them through validated decode rows. It is a synchronous, single-branch integration slice; it does not claim sampled verification or asynchronous separate-device speculation, and device qualification requires separate native evidence. Allocator and inputs must not change during it. Callers that cache the outcome must key it by result.Key, which carries the verified draft weight digest; req.Key may not.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/nn/batch"
cudakv "github.com/tmc/lib/nvidia/x/nn/kv"
cudamtp "github.com/tmc/lib/nvidia/x/nn/spec"
)
func main() {
// Host-only fixture. An actual model engine needs separate native admission.
a := cudakv.NewBlockAllocator(2, 8)
if err := a.AllocSequence(10, nil, 2); err != nil {
fmt.Println(err)
return
}
req := batch.BatchCycleRequest{
Prefix: []int32{0, 1},
PrefixSequence: 10,
Sequence: 11,
Hidden: []float32{1},
DraftWeights: []float32{1, 1},
HeadWeights: []float32{0, 0, 2, 0, 0, 0, 0, 3},
MTP: cudamtp.MTPConfig{NumDraftHeads: 2, Dim: 1, VocabSize: 4},
}
var model [32]byte
model[0] = 1
req.Key = cudamtp.ComputeSpeculationKey(model[:], req.Prefix, 1, 2, 2, "fp32", 1)
req.ExpectedKey = req.Key
req.DraftDigest, _ = batch.MTPDraftDigest(req.MTP, req.DraftWeights, req.HeadWeights)
v := batch.BatchVerifier{
ReadOnlyPrefix: true,
Engine: batch.NewHostDeterministicEngine(0, []int32{2, 3, 1}),
Wait: func(*batch.ExecutionStep) error { return nil },
}
result, err := batch.ExecuteBatchCycle(context.Background(), a, req, v)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(result.Outcome.AcceptedTokens, result.Outcome.BonusToken, result.Outcome.Committed)
if err := result.KV.Close(); err != nil {
fmt.Println(err)
return
}
fmt.Println(a.NumFreeBlocks())
}
Output: [2 3] 1 true 7
type BatchDraftProducer ¶
type BatchDraftProducer struct {
Engine DraftLogitsEngine
Wait func(*BatchDraftStep) error
Done func(*BatchDraftStep) bool
// Owner, when non-nil, must have a comparable Go value. Equal Owner and
// error-closer values identify the same cleanup owner and are closed once;
// distinct values must own distinct cleanup obligations. A pointer to an
// owner supports this identity even when its fields are not comparable.
// A noncomparable Owner is refused before ProduceDraftLogits is called,
// leaving its ownership with the caller.
Owner io.Closer
}
BatchDraftProducer configures synchronous MTP draft-logit production for ExecuteBatchCycle.
Wait must establish that all producer work for the step is quiescent before logits are read or producer-owned resources are released, including when ProduceDraftLogits returns cancellation or failure. Wait receives no canceled context: cancellation alone cannot authorize releasing device buffers. Done optionally proves exact-step quiescence independently of a terminal error from Wait; a false result retains Owner (and any io.Closer error owner) in BatchCycleResult.DraftOwner for explicit caller recovery. A failed owner Close also retains a recovery owner; retries release only remaining resources and stop at failed prerequisites. The caller must establish quiescence before closing an owner retained after an incomplete step.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/nn/batch"
cudakv "github.com/tmc/lib/nvidia/x/nn/kv"
cudamtp "github.com/tmc/lib/nvidia/x/nn/spec"
)
func main() {
a := cudakv.NewBlockAllocator(2, 8)
if err := a.AllocSequence(10, nil, 2); err != nil {
fmt.Println(err)
return
}
req := batch.BatchCycleRequest{
Prefix: []int32{0, 1},
PrefixSequence: 10,
Sequence: 11,
Hidden: []float32{1},
DraftWeights: []float32{1, 1},
HeadWeights: []float32{0, 0, 2, 0, 0, 0, 0, 3},
MTP: cudamtp.MTPConfig{NumDraftHeads: 2, Dim: 1, VocabSize: 4},
}
var model [32]byte
model[0] = 1
req.Key = cudamtp.ComputeSpeculationKey(model[:], req.Prefix, 1, 2, 2, "fp32", 1)
req.ExpectedKey = req.Key
req.DraftDigest, _ = batch.MTPDraftDigest(req.MTP, req.DraftWeights, req.HeadWeights)
req.DraftProducer = &batch.BatchDraftProducer{
Engine: batch.DraftLogitsFunc(func(_ context.Context, step *batch.BatchDraftStep) ([]float32, error) {
return cudamtp.MTPReference(step.Hidden, step.DraftWeights, step.HeadWeights, step.MTP)
}),
Wait: func(*batch.BatchDraftStep) error { return nil },
}
v := batch.BatchVerifier{
ReadOnlyPrefix: true,
Engine: batch.NewHostDeterministicEngine(0, []int32{2, 3, 1}),
Wait: func(*batch.ExecutionStep) error { return nil },
}
result, err := batch.ExecuteBatchCycle(context.Background(), a, req, v)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(result.Outcome.DraftTokens, result.Outcome.AcceptedTokens, result.Outcome.BonusToken, result.Outcome.Committed)
_ = result.KV.Close()
}
Output: [2 3] [2 3] 1 true
type BatchDraftStep ¶
type BatchDraftStep struct {
StepID int64
Key cudaspec.SpeculationCacheKey
DraftDigest [32]byte
Hidden []float32
DraftWeights []float32
HeadWeights []float32
MTP cudaspec.MTPConfig
}
BatchDraftStep describes one admitted synchronous MTP draft-logit production step inside ExecuteBatchCycle.
ExecuteBatchCycle validates request bounds, speculation keys, finite inputs, and DraftDigest before constructing a BatchDraftStep.
type BatchMetadata ¶
type BatchMetadata struct {
BatchShape cudashape.Shape
TotalTokens int
MaxTokens int
BlockSize int
RowBindings []BatchRowBinding
SequenceLens []int
AttentionMask []float32 // Flattened [BatchSize, MaxSeqLen] prefix-validity mask, not per-query causal masking
BlockTableFlat []int32 // Flattened [BatchSize, MaxBlocksPerRow]
// contains filtered or unexported fields
}
BatchMetadata holds validated layout, attention mask, and sequence offsets for an iteration.
func BindAllocatedRows ¶
func BindAllocatedRows(rows []BatchRowBinding, bucket ShapeBucket, pool *cudakv.BlockAllocator, sequenceIDs []int64) (*BatchMetadata, error)
BindAllocatedRows validates rows against their actual pool allocations before constructing metadata. sequenceIDs maps rows to numeric allocator owners; it is not inferred from block indices or user-facing sequence names. The caller must serialize pool access and retain these allocations through execution. This checks pool bookkeeping, not the device storage or the model's KV ABI.
Example ¶
pool := cudakv.NewBlockAllocator(2, 1)
_ = pool.AllocSequence(7, nil, 1)
row := BatchRowBinding{SeqID: "a", Tokens: []int32{1}, SequenceLength: 1, BlockTable: pool.Table(7)}
m, err := BindAllocatedRows([]BatchRowBinding{row}, ShapeBucket{1, 2, 1}, pool, []int64{7})
fmt.Println(m.TotalTokens, err)
Output: 1 <nil>
Example ¶
package main
import (
"errors"
"fmt"
cudabatch "github.com/tmc/lib/nvidia/x/nn/batch"
cudakv "github.com/tmc/lib/nvidia/x/nn/kv"
)
func main() {
pool := cudakv.NewBlockAllocator(2, 2)
_ = pool.AllocSequence(11, nil, 3)
row := cudabatch.BatchRowBinding{
RowIndex: 0,
SeqID: "req-1",
IsPrefill: true,
Tokens: []int32{10, 20, 30},
SequenceLength: 3,
BlockTable: pool.Table(11),
}
bucket := cudabatch.ShapeBucket{BatchSize: 1, MaxSeqLen: 4, MaxTokens: 3}
meta, err := cudabatch.BindAllocatedRows([]cudabatch.BatchRowBinding{row}, bucket, pool, []int64{11})
_, errOwner := cudabatch.BindAllocatedRows([]cudabatch.BatchRowBinding{row}, bucket, pool, []int64{99})
fmt.Println(err, meta.TotalTokens, meta.SequenceLens, meta.BlockTableFlat, errors.Is(errOwner, cudabatch.ErrCorruptBlockTable))
}
Output: <nil> 3 [3] [1 0] true
func ValidateAndBindRows ¶
func ValidateAndBindRows(rows []BatchRowBinding, bucket ShapeBucket, blockSize int) (*BatchMetadata, error)
ValidateAndBindRows validates a nonempty batch before allocating its metadata. Rows must have distinct nonempty sequence IDs, consecutive row indices, and exactly SequenceLength-StartPos tokens (one token for decode). Returned token and block-table slices are detached from the caller.
AttentionMask marks each row's valid prefix; the consumer must separately enforce per-query causal attention. Block indices must fit int32. This function has no KV pool ownership or capacity information and cannot prove that a positive block index belongs to a sequence or a physical allocation.
Example ¶
package main
import (
"fmt"
cudabatch "github.com/tmc/lib/nvidia/x/nn/batch"
)
func main() {
rows := []cudabatch.BatchRowBinding{
{RowIndex: 0, SeqID: "prefill", IsPrefill: true, Tokens: []int32{7, 8}, SequenceLength: 2, BlockTable: []int{1}},
{RowIndex: 1, SeqID: "decode", Tokens: []int32{9}, StartPos: 2, SequenceLength: 3, BlockTable: []int{2, 3}},
}
metadata, err := cudabatch.ValidateAndBindRows(rows, cudabatch.ShapeBucket{BatchSize: 3, MaxSeqLen: 5, MaxTokens: 3}, 2)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(metadata.TotalTokens, metadata.SequenceLens)
// This is one prefix-validity mask per row, not a per-query causal mask.
fmt.Println(metadata.AttentionMask)
}
Output: 3 [2 3 0] [1 1 0 0 0 1 1 1 0 0 0 0 0 0 0]
type BatchRowBinding ¶
type BatchRowBinding struct {
RowIndex int
SeqID string
IsPrefill bool
IsLastPrefill bool // Final prompt chunk: its logits supply the first generated token
Tokens []int32 // Input tokens for this iteration (chunk tokens for prefill, 1 token for decode)
StartPos int // Offset within full sequence
SequenceLength int // Total active length (StartPos + len(Tokens))
BlockTable []int // Physical block indices in KV pool
ContinuationVis ContinuationVisibility
}
BatchRowBinding binds a single sequence row in a batched forward pass to validated tensor shapes, attention masks, sequence lengths, and physical KV block tables.
type BatchScheduler ¶
type BatchScheduler struct {
// contains filtered or unexported fields
}
BatchScheduler coordinates request admission, continuous batching iteration scheduling, prefill chunking, and deterministic state transitions.
Example ¶
package main
import (
"fmt"
cudabatch "github.com/tmc/lib/nvidia/x/nn/batch"
)
func main() {
sched := cudabatch.NewBatchScheduler(cudabatch.SchedulerConfig{
MaxBatchSize: 4,
MaxBudgetTokens: 64,
ChunkSize: 16,
}, nil)
req := &cudabatch.Request{
ID: "req-1",
PromptTokens: []int32{10, 20, 30, 40},
MaxTokens: 2,
}
if err := sched.Submit(req); err != nil {
panic(err)
}
iter, err := sched.Schedule()
if err != nil {
panic(err)
}
fmt.Printf("Scheduled %d prefill chunks, %d total tokens\n", len(iter.PrefillChunks), iter.TotalTokens)
// Complete prefill with the first token sampled from its final logits.
_ = sched.CompleteStep(iter, map[string]int32{"req-1": 41}, nil)
r, _ := sched.Request("req-1")
fmt.Printf("Request state after prefill: %v\n", r.State)
}
Output: Scheduled 1 prefill chunks, 4 total tokens Request state after prefill: decoding
func NewBatchScheduler ¶
func NewBatchScheduler(cfg SchedulerConfig, kvTracker *MemoryBudgetTracker) *BatchScheduler
NewBatchScheduler constructs a continuous batch scheduler with config and optional KV tracker.
func (*BatchScheduler) BindIteration ¶
func (s *BatchScheduler) BindIteration(iter *ScheduledIteration, bucket ShapeBucket) (*BatchMetadata, error)
BindIteration validates the exact outstanding iteration against the tracker’s actual block allocator. Shape-only metadata cannot authorize a PlanEngine. The scheduler and tracker must exclusively own pool mutation during execution.
Example ¶
package main
import (
"errors"
"fmt"
cudabatch "github.com/tmc/lib/nvidia/x/nn/batch"
cudakv "github.com/tmc/lib/nvidia/x/nn/kv"
)
func main() {
pool := cudakv.NewBlockAllocator(2, 4)
sched := cudabatch.NewBatchScheduler(cudabatch.SchedulerConfig{
MaxBatchSize: 2,
MaxBudgetTokens: 8,
ChunkSize: 4,
}, cudabatch.NewMemoryBudgetTracker(pool))
_ = sched.Submit(&cudabatch.Request{ID: "req-1", PromptTokens: []int32{10, 20, 30}, MaxTokens: 2})
iter, _ := sched.Schedule()
bucket := cudabatch.ShapeBucket{BatchSize: 1, MaxSeqLen: 4, MaxTokens: 4}
meta, err := sched.BindIteration(iter, bucket)
iter.AllocatedRows[0].BlockTable[0] = 99
_, errTampered := sched.BindIteration(iter, bucket)
fmt.Println(err, meta.TotalTokens, meta.SequenceLens, errors.Is(errTampered, cudabatch.ErrInvalidRequest))
}
Output: <nil> 3 [3] true
Example ¶
s := NewBatchScheduler(SchedulerConfig{}, NewMemoryBudgetTracker(cudakv.NewBlockAllocator(2, 1)))
_ = s.Submit(&Request{ID: "a", PromptTokens: []int32{1}, MaxTokens: 1})
iteration, _ := s.Schedule()
m, err := s.BindIteration(iteration, ShapeBucket{1, 2, 1})
fmt.Println(m.TotalTokens, err)
Output: 1 <nil>
func (*BatchScheduler) Cancel ¶
func (s *BatchScheduler) Cancel(id string) error
Cancel requests cancellation of an active or queued request. If the request is currently in an active GPU/host step, its KV blocks and output buffers are retained until CompleteStep is called.
func (*BatchScheduler) CompleteStep ¶
func (s *BatchScheduler) CompleteStep(iter *ScheduledIteration, generatedTokens map[string]int32, rowErrors map[string]error) error
CompleteStep updates request states after iteration execution completes. It applies newly generated tokens, transitions completed prefills to decodes, processes cancellations, and releases retained KV memory only after invocation is finished. The caller must wait for execution to finish before calling CompleteStep. Final prefill and decode rows need a token or row error; intermediate prefills need no token. Invalid results leave the step outstanding for corrected completion.
func (*BatchScheduler) RegisterResourceRelease ¶
func (s *BatchScheduler) RegisterResourceRelease(seqID string, cb func())
RegisterResourceRelease registers a cleanup callback (e.g. output buffer release or KV handle) to be executed only when the current request completely finishes and execution has completed. Unknown or retired IDs release immediately; callbacks cannot attach to a future admission reusing the same ID.
func (*BatchScheduler) Request ¶
func (s *BatchScheduler) Request(id string) (*Request, bool)
Request returns a detached status snapshot. Finished snapshots are retained up to MaxFinishedRequests; retired IDs may be submitted as new admissions.
func (*BatchScheduler) Schedule ¶
func (s *BatchScheduler) Schedule() (*ScheduledIteration, error)
Schedule selects requests for the next forward pass iteration according to token budgets, memory availability, and fairness policies. It returns ErrExecutionInFlight until the previous nonempty iteration has been completed.
func (*BatchScheduler) Submit ¶
func (s *BatchScheduler) Submit(req *Request) error
Submit copies a fresh request and its prompt. MaxTokens must be positive. Caller mutations after return cannot change scheduler state. CreatedAt is descriptive; arbitration and waiting timeout use scheduler admission order and time. A full waiting queue returns ErrCapacityExhausted before admission.
type BatchVerifier ¶
type BatchVerifier struct {
// ReadOnlyPrefix requires verification that never writes borrowed prefix KV.
// Writes to private branch blocks are permitted. Engines that overwrite
// prefix blocks are unsupported without a copy-on-write adapter.
ReadOnlyPrefix bool
Engine ExecutionEngine
Wait func(*ExecutionStep) error
// Done optionally proves exact-step quiescence independently of a terminal
// execution error from Wait. A false result retains the KV lease.
Done func(*ExecutionStep) bool
}
BatchVerifier verifies target tokens through the existing batch row contract. Wait must establish that all work for the step is quiescent, including when ExecuteForward returns cancellation or failure. Wait receives no canceled context: cancellation alone cannot authorize releasing borrowed device KV. It must have its own bounded native drain policy. A failed Wait without independent Done proof retains KV in the returned result for explicit owner recovery, rather than guessing.
type ContinuationTracker ¶
type ContinuationTracker struct {
// contains filtered or unexported fields
}
ContinuationTracker tracks conversation session state, multi-turn continuations, and KV block reuse for protocols like /v1/responses and /v1/messages. It ensures that tool calls and reasoning (thinking) tokens are preserved without re-prefill and without token boundary corruption.
func NewContinuationTracker ¶
func NewContinuationTracker() *ContinuationTracker
NewContinuationTracker initializes a continuation tracker.
func (*ContinuationTracker) DropSession ¶
func (ct *ContinuationTracker) DropSession(sessionID string)
DropSession removes a session when finished or expired.
func (*ContinuationTracker) GetSession ¶
func (ct *ContinuationTracker) GetSession(sessionID string) (*SessionContinuation, bool)
GetSession returns a copy of the stored session continuation, if present.
func (*ContinuationTracker) StoreSession ¶
func (ct *ContinuationTracker) StoreSession(sessionID string, tokens []int32, blockTable []int, vis ContinuationVisibility, fullText string)
StoreSession updates or records the session's active KV blocks and token sequence.
type ContinuationVisibility ¶
type ContinuationVisibility int
ContinuationVisibility defines how tokens are preserved for multi-turn protocols.
const ( // VisibilityDefault indicates standard public user/assistant context. VisibilityDefault ContinuationVisibility = iota // VisibilityResponsesVisible preserves intermediate tool call responses and hidden outputs. VisibilityResponsesVisible // VisibilityThinkingVisible preserves chain-of-thought reasoning tokens across turns. VisibilityThinkingVisible )
func (ContinuationVisibility) String ¶
func (v ContinuationVisibility) String() string
type ContinuousBatchScheduler ¶
type ContinuousBatchScheduler struct {
// contains filtered or unexported fields
}
ContinuousBatchScheduler packs heterogeneous in-flight sequences (chunked prefill, single-token decode, and speculative draft trees) into an active token step of size M_active, routes M_active to the minimal padded bucket B in {1, 2, 4, 8} (B >= M_active) in a specdecode.MultiBucketMegakernelTable, and masks padded rows so they cannot write to physical KV pages.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/ir/plan"
"github.com/tmc/lib/nvidia/x/nn/batch"
)
func main() {
ctx := context.Background()
tree, err := batch.NewRadixKVTree(32, 4)
if err != nil {
fmt.Println(err)
return
}
table, err := plan.NewMultiBucketMegakernelTable(plan.MultiBucketTableConfig{
Arch: "sm_121a",
})
if err != nil {
fmt.Println(err)
return
}
sched, err := batch.NewContinuousBatchScheduler(tree, table, 8)
if err != nil {
fmt.Println(err)
return
}
if err := sched.Admit(&batch.InFlightSequence{
ID: "req_decode",
Phase: batch.PhaseDecode,
PromptTokens: []int{10, 11, 12, 13},
DecodeToken: 101,
}); err != nil {
fmt.Println(err)
return
}
if err := sched.Admit(&batch.InFlightSequence{
ID: "req_prefill",
Phase: batch.PhaseChunkedPrefill,
PromptTokens: []int{10, 11, 12, 13, 20, 21},
ChunkBudget: 2,
DecodeToken: 202,
}); err != nil {
fmt.Println(err)
return
}
step, err := sched.ScheduleStep(ctx)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("active=%d bucket=%d padded=%d mask=%04b prefix_hits=%d row3_write_kv=%v\n",
step.ActiveTokens,
step.BucketM,
step.PaddedRows,
step.ActiveRowMask,
step.PrefixCacheHits,
step.Rows[3].WriteKV)
}
Output: active=3 bucket=4 padded=1 mask=0111 prefix_hits=1 row3_write_kv=false
func NewContinuousBatchScheduler ¶
func NewContinuousBatchScheduler( tree *RadixKVTree, table *specdecode.MultiBucketMegakernelTable, maxStepTokens int, ) (*ContinuousBatchScheduler, error)
NewContinuousBatchScheduler constructs a ContinuousBatchScheduler backed by tree and table. When maxStepTokens <= 0, it defaults to the largest bucket M in table (typically 8).
func (*ContinuousBatchScheduler) Admit ¶
func (s *ContinuousBatchScheduler) Admit(seq *InFlightSequence) error
Admit registers seq in the scheduler, resolving its prompt tokens through the RadixKVTree to reuse shared prefix KV pages and allocate pages for any uncached suffix. Only whole pages whose KV has been written, or whose writes an earlier step scheduled, are shared, and a prefilling sequence never shares the page holding its last prompt token. Shared pages are read-only: ContinuousBatchScheduler.ScheduleStep refuses to write them.
func (*ContinuousBatchScheduler) Check ¶
func (s *ContinuousBatchScheduler) Check() error
Check verifies the scheduler's page ownership: the page allocator's invariants hold (see cudakv.BlockAllocator.Check), each sequence's PageIDs is its page table, and every page is held exactly once by each radix tree node and each sequence that has it, so no page leaks and none is freed while in use.
func (*ContinuousBatchScheduler) Complete ¶
func (s *ContinuousBatchScheduler) Complete(seqID string) error
Complete finishes seqID, unpinning its prefix-cache path so its KV pages can be shared by future prefixes or evicted under memory pressure.
func (*ContinuousBatchScheduler) ScheduleStep ¶
func (s *ContinuousBatchScheduler) ScheduleStep(ctx context.Context) (*ScheduledBatchStep, error)
ScheduleStep packs active sequences into an execution step of size M_active, routes M_active through the specdecode.MultiBucketMegakernelTable to select the minimal padded bucket B >= M_active, and populates the active-row mask so padded rows [M_active, B) have WriteKV=false and KVPageID=-1.
func (*ContinuousBatchScheduler) SelectMinimalBucket ¶
func (s *ContinuousBatchScheduler) SelectMinimalBucket(activeM int) (*specdecode.BucketMegakernelEntry, int, error)
SelectMinimalBucket returns the smallest bucket B in {1, 2, 4, 8} (or from the table's configured buckets) satisfying B >= activeM.
type DraftLogitsEngine ¶
type DraftLogitsEngine interface {
ProduceDraftLogits(ctx context.Context, step *BatchDraftStep) ([]float32, error)
}
DraftLogitsEngine computes MTP draft logits shaped [NumDraftHeads, VocabSize] for an admitted BatchDraftStep.
type DraftLogitsFunc ¶
type DraftLogitsFunc func(ctx context.Context, step *BatchDraftStep) ([]float32, error)
DraftLogitsFunc adapts a function to DraftLogitsEngine.
func (DraftLogitsFunc) ProduceDraftLogits ¶
func (f DraftLogitsFunc) ProduceDraftLogits(ctx context.Context, step *BatchDraftStep) ([]float32, error)
ProduceDraftLogits calls f(ctx, step).
type ExactSuffixTokenizer ¶
type ExactSuffixTokenizer interface {
Encode(text string) ([]int32, error)
Decode(tokens []int32) (string, error)
}
ExactSuffixTokenizer specifies the tokenizer interface needed to verify boundary-safe suffix tokenization without re-tokenizing previous turns.
type ExecutionEngine ¶
type ExecutionEngine interface {
// ExecuteForward executes a forward pass on the scheduled batch.
// On success execution is complete, with one sampled token or row error
// for each decode or IsLastPrefill row. Intermediate prefill rows
// must not produce tokens. An error retaining execution ownership must
// be settled before the caller completes the scheduler step.
//
// ctx bounds the whole step, so it must be scoped to the batch, never
// a request's context: a request leaves the batch by cancelling its
// rows in the scheduler, which keeps the other rows running.
ExecuteForward(ctx context.Context, step *ExecutionStep) (generatedTokens map[string]int32, rowErrors map[string]error, err error)
}
ExecutionEngine models the low-level model forward execution (host test double or device plan).
type ExecutionStep ¶
type ExecutionStep struct {
StepID int64
Iteration *ScheduledIteration
Metadata *BatchMetadata
// CancelWait, when closed, stops the wait for the step's completion.
// The step fails for every row, so it must be scoped to the batch,
// closed only by its owner, such as engine shutdown, and never derive
// from one request's cancellation or deadline.
CancelWait <-chan struct{}
ReleaseHook func() // Releases temporary output/step buffers
}
ExecutionStep represents a scheduled batched forward step ready for execution.
type FairnessPolicy ¶
type FairnessPolicy int
FairnessPolicy controls request arbitration among waiting and prefilling sequences.
const ( // PolicyFCFS serves requests in order of arrival time. PolicyFCFS FairnessPolicy = iota PolicyFairShare // PolicyPriorityDecode prioritizes decode latency while reserving one token // and one row for admitted prefill work. Waiting prefill still needs KV // capacity and bounded admission space before it can make progress. PolicyPriorityDecode )
type HostDeterministicEngine ¶
type HostDeterministicEngine struct {
// contains filtered or unexported fields
}
HostDeterministicEngine is a deterministic host-only test engine for testing continuous batching, prefill chunking, decode loops, and cancellation without a GPU.
func NewHostDeterministicEngine ¶
func NewHostDeterministicEngine(delay time.Duration, outputSequence []int32) *HostDeterministicEngine
NewHostDeterministicEngine creates a host test engine with optional artificial delay.
func (*HostDeterministicEngine) ExecuteForward ¶
func (e *HostDeterministicEngine) ExecuteForward(ctx context.Context, step *ExecutionStep) (map[string]int32, map[string]error, error)
ExecuteForward simulates executing a continuous batch iteration on host.
type InFlightSequence ¶
type InFlightSequence struct {
ID string
Phase SequencePhase
PromptTokens []int
PrefillOffset int
ChunkBudget int
DecodeToken int
DraftTokens []int
AcceptanceRate float64
PageIDs []int
CachedPages int
// RadixNode is the end of the prefix-cache path the sequence pins:
// the pages it shares, then those it has published.
RadixNode *cudakv.RadixNode
// contains filtered or unexported fields
}
InFlightSequence describes a single active request managed by ContinuousBatchScheduler.
type MemoryBudgetTracker ¶
type MemoryBudgetTracker struct {
// contains filtered or unexported fields
}
MemoryBudgetTracker tracks admission and allocation limits against KV pool blocks.
func NewMemoryBudgetTracker ¶
func NewMemoryBudgetTracker(pool *cudakv.BlockAllocator) *MemoryBudgetTracker
NewMemoryBudgetTracker returns a tracker of pool. A tracker of a nil pool refuses admission and binding rather than inventing pool ownership.
func (*MemoryBudgetTracker) AllocSequence ¶
func (t *MemoryBudgetTracker) AllocSequence(seqID int64, shared []int, promptTokens int) ([]int, error)
AllocSequence allocates initial physical KV blocks for seqID.
func (*MemoryBudgetTracker) AppendToken ¶
func (t *MemoryBudgetTracker) AppendToken(seqID int64) error
AppendToken reserves room for an additional generated token.
func (*MemoryBudgetTracker) CanAdmit ¶
func (t *MemoryBudgetTracker) CanAdmit(promptTokens int, sharedBlocks []int) bool
CanAdmit checks if the block manager has sufficient free blocks to admit a request with promptTokens tokens and shared prefix blocks.
func (*MemoryBudgetTracker) FreeSequence ¶
func (t *MemoryBudgetTracker) FreeSequence(seqID int64)
FreeSequence frees sequence blocks when all execution holders complete.
func (*MemoryBudgetTracker) ReleasePrefix ¶
func (t *MemoryBudgetTracker) ReleasePrefix(blocks []int) error
ReleasePrefix releases blocks returned by RetainPrefix.
func (*MemoryBudgetTracker) RetainPrefix ¶
func (t *MemoryBudgetTracker) RetainPrefix(seqID int64, tokens int) ([]int, error)
RetainPrefix keeps the blocks holding the first tokens tokens of seqID alive past the sequence, for a continuation to share, and returns them. Only whole blocks are retained (see cudakv.BlockAllocator.Share): a partly filled block stays the sequence's own, since it may still write the rest of it. Release the blocks with ReleasePrefix.
type PackedRow ¶
type PackedRow struct {
RowIndex int
Valid bool
SeqID string
Phase SequencePhase
Token int
TokenPos int
KVPageID int
WriteKV bool
}
PackedRow represents one token slot inside a scheduled megakernel batch step. Padded rows (`RowIndex >= ActiveTokens`) have `Valid == false`, `WriteKV == false`, and `KVPageID == -1` so padded rows never corrupt physical KV cache pages.
type PendingForwardError ¶
type PendingForwardError struct {
// contains filtered or unexported fields
}
PendingForwardError transfers completion recovery to the caller. Do not call CompleteStep while Done is false. A completion cleanup error can coexist with Done being true; Drain must finish cleanup before executing another step.
func (*PendingForwardError) Done ¶
func (p *PendingForwardError) Done() bool
Done reports native completion and finished storage release callbacks.
func (*PendingForwardError) Error ¶
func (p *PendingForwardError) Error() string
func (*PendingForwardError) Unwrap ¶
func (p *PendingForwardError) Unwrap() error
Unwrap returns the original execution or wait error, even after recovery.
type PlanBindingFunc ¶
PlanBindingFunc binds actual model inputs, outputs and KV storage. release must retain all that storage until called, including after partial submission. The engine calls release once after completion and sampling, or on binding failure. A non-nil release returned with an error is still called. The model ABI and physical KV allocation mapping are supplied by the caller.
type PlanEngine ¶
type PlanEngine struct {
// contains filtered or unexported fields
}
PlanEngine executes an ordinary cudaplan plan. It permits one outstanding step and starts no background drain. The engine owns the plan; the caller owns its stream and device. Its zero value is unusable. No model or KV ABI is inferred.
func CompilePlanEngine ¶
func CompilePlanEngine(source *cudair.Snapshot, stream *cuda.Stream, bind PlanBindingFunc, sample PlanSampleFunc, opts ...cudaplan.PlanOption) (*PlanEngine, error)
CompilePlanEngine compiles and owns a plan. A non-nil engine returned with an error retains failed compilation cleanup: retry Close before releasing the device. The stream remains owned by the caller. Options specify actual kernels and the device contract; this adapter does not compile a model automatically.
Example ¶
package main
import (
"context"
"fmt"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"
cudabatch "github.com/tmc/lib/nvidia/x/nn/batch"
)
func main() {
graph := cudair.NewGraph()
input := graph.AddInput("x", []int{1, 1}, cudair.Float32)
output := graph.AddMatMul(input, input)
if err := graph.SetOutputs(output); err != nil {
return
}
snapshot, err := graph.Snapshot()
if err != nil {
return
}
bind := func(context.Context, *cudabatch.ExecutionStep) (*cudaplan.Bindings, func(), error) {
// A real binder sets typed inputs and outputs and retains their allocations.
return cudaplan.NewBindings(), nil, nil
}
sample := func(context.Context, *cudabatch.ExecutionStep) (map[string]int32, map[string]error, error) {
return nil, nil, nil
}
engine, err := cudabatch.CompilePlanEngine(snapshot, nil, bind, sample)
if err != nil {
return
}
defer engine.Close()
fmt.Println(engine.StepDone(1))
fmt.Println(engine.WaitStep(context.Background(), 1))
}
Output: false cudabatch: unknown execution step
func NewPlanEngine ¶
func NewPlanEngine(plan *cudaplan.ExecutablePlan, stream *cuda.Stream, bind PlanBindingFunc, sample PlanSampleFunc) (*PlanEngine, error)
NewPlanEngine takes ownership of plan. bind and sample must describe its actual tensor and output ABI. Execution requires a live stream for the plan's device. A nil stream permits construction for inspection; execution refuses it.
func (*PlanEngine) Close ¶
func (e *PlanEngine) Close() error
Close closes the owned plan. Pending completion must first be drained with an explicit recovery context. Failed plan cleanup can be retried.
func (*PlanEngine) Drain ¶
func (e *PlanEngine) Drain(ctx context.Context) error
Drain retries outstanding completion and cleanup. It reports recovery errors; original execution errors remain in PendingForwardError and WaitStep.
func (*PlanEngine) ExecuteForward ¶
func (e *PlanEngine) ExecuteForward(ctx context.Context, step *ExecutionStep) (map[string]int32, map[string]error, error)
ExecuteForward validates, binds, submits, waits and samples the plan. Pending completion is returned as PendingForwardError with storage still retained. Metadata must come from BindAllocatedRows or BatchScheduler.BindIteration; shape-only metadata does not establish allocation ownership. The pool must remain unchanged through execution and completion.
ctx and step.CancelWait bound the wait for completion, and a cancelled wait fails every row of the step. Both must be scoped to the batch and cancelled only by its owner, such as engine shutdown, never by one request's cancellation or deadline; a request leaves the batch through the scheduler, which removes only its rows.
func (*PlanEngine) StepDone ¶
func (e *PlanEngine) StepDone(id int64) bool
StepDone reports ended storage ownership for the exact last attempted step. Unknown, future and replaced IDs return false.
type PlanSampleFunc ¶
type PlanSampleFunc func(context.Context, *ExecutionStep) (map[string]int32, map[string]error, error)
PlanSampleFunc reads completed outputs. Each decode or IsLastPrefill row must have one token or row error. Intermediate prefill rows may have errors but must not have generated tokens. Sampling must not release the storage retained by PlanBindingFunc.
type RadixKVTree ¶
type RadixKVTree struct {
// contains filtered or unexported fields
}
RadixKVTree is a pool of physical KV pages with a prefix cache over them: a cudakv.BlockAllocator that owns the pages and a cudakv.RadixTree that maps token prefixes to the pages holding their KV, and evicts the least recently matched segments when pages are needed.
Each sequence of a ContinuousBatchScheduler holds the pages of its table, and the tree holds each page it records, so a page returns to the pool when the last of them lets go. A page held by more than one is read-only. A sequence pins the tree path covering the pages it holds, so eviction drops only segments whose pages no sequence holds.
func NewRadixKVTree ¶
func NewRadixKVTree(totalPages, pageSize int) (*RadixKVTree, error)
NewRadixKVTree creates a RadixKVTree managing totalPages physical KV pages with pageSize tokens per page.
func (*RadixKVTree) CacheHits ¶
func (t *RadixKVTree) CacheHits() int
CacheHits returns the cumulative count of prefix KV pages reused by sequences admitted to a ContinuousBatchScheduler.
func (*RadixKVTree) EvictLRU ¶
func (t *RadixKVTree) EvictLRU(neededPages int) (int, error)
EvictLRU evicts unpinned segments in least-recently-matched order until at least neededPages physical KV pages have been returned to the free pool. It returns the number of pages freed.
func (*RadixKVTree) FreePages ¶
func (t *RadixKVTree) FreePages() int
FreePages returns the number of unallocated physical KV pages in the pool.
func (*RadixKVTree) InsertPrefix ¶
func (t *RadixKVTree) InsertPrefix(tokens, pages []int) (*cudakv.RadixNode, error)
InsertPrefix records that pages hold the KV of tokens, one page for each page of tokens, and returns the node that ends the recorded prefix. Only whole pages are recorded: a trailing partial page stays with its writer. Pages for a prefix the tree already records are ignored.
The KV must already be written, or its writes scheduled ahead of any reader: RadixKVTree.MatchPrefix hands the pages to other sequences, which read them and never write them. The tree holds each page it records until it evicts the segment. The returned node is not pinned.
func (*RadixKVTree) MatchPrefix ¶
func (t *RadixKVTree) MatchPrefix(tokens []int) (matchedTokens int, pageIDs []int, node *cudakv.RadixNode)
MatchPrefix returns the longest recorded whole-page prefix of tokens: the number of tokens matched, the pages holding them, and the node the match ends at. It pins nothing.
func (*RadixKVTree) PageSize ¶
func (t *RadixKVTree) PageSize() int
PageSize returns the number of tokens stored per physical KV page.
func (*RadixKVTree) Release ¶
func (t *RadixKVTree) Release(node *cudakv.RadixNode)
Release unpins node, a node a sequence pinned. Releasing nil does nothing.
func (*RadixKVTree) UsedPages ¶
func (t *RadixKVTree) UsedPages() int
UsedPages returns the number of physical KV pages held by the prefix cache or by sequences.
type Request ¶
type Request struct {
ID string
PromptTokens []int32
MaxTokens int
CreatedAt time.Time
Visibility ContinuationVisibility
SessionID string // Associated multi-turn conversation or session ID
// OnFinish, if non-nil, receives one detached terminal snapshot before
// history retirement. It runs synchronously and must not call the scheduler.
OnFinish func(*Request)
// Dynamic lifecycle state
State RequestState
PrefilledTokens int
GeneratedTokens []int32
BlockTable []int // Physical KV block indices allocated to this request
PromptBlockCount int // Number of prefix blocks retained
// contains filtered or unexported fields
}
Request represents a single user sequence submitted to the batch scheduler.
func (*Request) ContextTokens ¶
ContextTokens returns the number of input tokens consumed by successful steps. The newest generated token is pending input for the next decode; it is not included. Reserved KV capacity and failed or incomplete steps do not count.
func (*Request) Err ¶
Err returns the terminal cancellation, timeout or execution error, if any.
Example ¶
s := NewBatchScheduler(SchedulerConfig{}, nil)
_ = s.Submit(&Request{ID: "a", PromptTokens: []int32{1}, MaxTokens: 1})
_ = s.Cancel("a")
r, _ := s.Request("a")
fmt.Println(r.Err())
Output: context canceled
Example ¶
package main
import (
"fmt"
cudabatch "github.com/tmc/lib/nvidia/x/nn/batch"
)
func main() {
sched := cudabatch.NewBatchScheduler(cudabatch.SchedulerConfig{}, nil)
var finished *cudabatch.Request
req := &cudabatch.Request{
ID: "req-1",
PromptTokens: []int32{10, 20},
MaxTokens: 2,
OnFinish: func(r *cudabatch.Request) { finished = r },
}
_ = sched.Submit(req)
req.PromptTokens[0] = 99
_ = sched.Cancel("req-1")
snap, _ := sched.Request("req-1")
fmt.Println(snap.State, snap.Err(), finished.Err(), snap.PromptTokens[0])
}
Output: canceled context canceled context canceled 10
func (*Request) IsFinished ¶
IsFinished reports whether the request has reached a terminal state.
func (*Request) TotalTokens ¶
TotalTokens returns the total prompt plus generated tokens so far.
func (*Request) TotalTokensSlice ¶
TotalTokensSlice returns a newly allocated slice containing all prompt and generated tokens.
type RequestState ¶
type RequestState int
RequestState defines deterministic lifecycle states of an inference request.
const ( StateWaiting RequestState = iota StatePrefilling StateDecoding StateCompleted StateCanceled )
func (RequestState) String ¶
func (s RequestState) String() string
type ScheduledBatchStep ¶
type ScheduledBatchStep struct {
ActiveTokens int
BucketM int
PaddedRows int
ActiveRowMask uint64
Rows []PackedRow
BucketEntry *specdecode.BucketMegakernelEntry
Transition nnspec.BucketTransition
PrefixCacheHits int
}
ScheduledBatchStep records the packed token rows, active-row bitmask, padded bucket selection, and megakernel table entry for one continuous-batching step.
func (*ScheduledBatchStep) RowIsActive ¶
func (s *ScheduledBatchStep) RowIsActive(idx int) bool
RowIsActive reports whether row idx is masked active in s.ActiveRowMask.
type ScheduledIteration ¶
type ScheduledIteration struct {
StepID int64
PrefillChunks []cudakv.PrefillChunk
DecodeSeqIDs []string
TotalTokens int
AllocatedRows []BatchRowBinding
}
ScheduledIteration contains the selected rows and their action in the current step.
type SchedulerConfig ¶
type SchedulerConfig struct {
MaxBatchSize int // Maximum active concurrent rows (e.g. 64)
MaxBudgetTokens int // Combined batch token budget per step (e.g. 2048)
ChunkSize int // Maximum prefill chunk tokens per request per step (e.g. 512)
MaxWaitingTimeout time.Duration
FairnessPolicy FairnessPolicy
// MaxWaitingRequests and MaxFinishedRequests bound queued work and terminal
// status history. Zero selects 1024 for each. Negative limits are invalid.
// Retiring history removes only finished requests, never an outstanding step.
MaxWaitingRequests int
MaxFinishedRequests int
}
SchedulerConfig configures batch scheduler limits, chunking, and fairness.
type SequencePhase ¶
type SequencePhase string
SequencePhase identifies the execution regime of an in-flight sequence in ContinuousBatchScheduler.
const ( // PhaseChunkedPrefill indicates a sequence processing a slice of its prompt // tokens within the step budget. PhaseChunkedPrefill SequencePhase = "chunked_prefill" // PhaseDecode indicates a sequence generating a single autoregressive token. PhaseDecode SequencePhase = "decode" // PhaseSpeculativeVerify indicates a sequence verifying a speculative draft // token tree alongside its root/bonus token. PhaseSpeculativeVerify SequencePhase = "speculative_verify" )
type SessionContinuation ¶
type SessionContinuation struct {
SessionID string
Tokens []int32
BlockTable []int
Visibility ContinuationVisibility
FullText string // Cumulative text for suffix tokenization verification
}
SessionContinuation stores the historical token sequence, block table, and visibility for an ongoing multi-turn session.
type ShapeBucket ¶
type ShapeBucket struct {
BatchSize int // Number of rows in bucket
MaxSeqLen int // Maximum sequence length dimension
MaxTokens int // Maximum tokens flattened
}
ShapeBucket defines a discretized batch shape to reuse compiled plans.
func SelectBucket ¶
func SelectBucket(batchSize, maxSeqLen int, buckets []ShapeBucket) (ShapeBucket, error)
SelectBucket picks the smallest ShapeBucket capable of containing batchSize and maxSeqLen.
type ZOSRemapPlan ¶
type ZOSRemapPlan struct {
Remap []int32
SeqlensQ []int32
CuSeqlensQ []int32
Positions []int32
OutToIn []int32
TotalDraftTokens int
}
ZOSRemapPlan describes the device-side Zero-Overhead Speculation (ZOS) token compaction and position schedule between decode step N-1 and decode step N.
func BuildZOSRemapPlan ¶
func BuildZOSRemapPlan( prevCuSeqlensQ []int32, acceptedCounts []int32, nextSeqlensQ []int32, basePositions []int32, ) (ZOSRemapPlan, error)
BuildZOSRemapPlan computes the device-side Zero-Overhead Speculation (ZOS) token compaction and position schedule between step N-1 and step N:
- Remap[b] = prevCuSeqlensQ[b] + acceptedCounts[b] - 1 (points to the last accepted token slot in step N-1's flattened output so step N's hidden state and logits can be gathered without a host round-trip).
- CuSeqlensQ is the prefix sum of nextSeqlensQ of length bsz + 1.
- Positions and OutToIn hold the flattened token positions and batch indices for all TotalDraftTokens tokens in step N.
Example ¶
package main
import (
"fmt"
cudabatch "github.com/tmc/lib/nvidia/x/nn/batch"
)
func main() {
plan, err := cudabatch.BuildZOSRemapPlan(
[]int32{0, 4, 7},
[]int32{3, 2},
[]int32{2, 3},
[]int32{10, 20},
)
if err != nil {
panic(err)
}
fmt.Printf("remap=%v cuSeqlensQ=%v positions=%v outToIn=%v total=%d\n",
plan.Remap, plan.CuSeqlensQ, plan.Positions, plan.OutToIn, plan.TotalDraftTokens)
}
Output: remap=[2 5] cuSeqlensQ=[0 2 5] positions=[13 14 22 23 24] outToIn=[0 0 1 1 1] total=5
type ZOSRemapSpec ¶
ZOSRemapSpec configures device-side Zero-Overhead Speculation (ZOS) remap kernel generation.