kv

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: 27 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

SPDX-License-Identifier: Apache-2.0

Package kv provides paged, quantized, and rotated key-value cache layouts, block-table allocators, device C++ headers, and fused KV append kernels.

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"
	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	// Create a paged KV cache with 4 blocks of 2 tokens each.
	cache, err := nnkv.NewTestPagedCache(1, 1, 4, 2, 4)
	if err != nil {
		panic(err)
	}
	defer cache.Close()

	_ = cache.AllocSequence(1, 2)
	_ = cache.AllocSequence(2, 2)
	cache.FreeSequence(1)

	// Proactively compact the paged KV pool.
	plan, _ := cache.Defrag()
	fmt.Printf("Compacted %d blocks, frag index: %.2f\n", len(plan.Moves), cache.FragmentationIndex())
}
Output:
Compacted 1 blocks, frag index: 0.00

Index

Examples

Constants

View Source
const (
	MaxPages = 1<<31 - 1
	MaxSeqs  = 1<<24 - 1

	// MaxPageTokens bounds a page key, which the device builds on the stack.
	MaxPageTokens = 64
)

Limits on Config fields, from the widths of the packed words.

View Source
const (
	WordFreeCount   = iota // pages free and not reserved, as a two's-complement int64
	WordStep               // current step
	WordCause              // first cause code recorded, or CauseNone
	WordJournalHead        // events ever appended to the journal
	WordLimboLen           // pages in limbo
	WordAllocs             // pages allocated
	WordFrees              // pages whose last reference was dropped
	WordHits               // shared-page references taken
	WordMisses             // shared-page references refused (page freed or reused)
	WordPressure           // allocations refused for lack of free or evictable pages
	WordClock              // the CLOCK hand: pages examined for eviction
	WordEvictions          // cached pages evicted
	WordInserts            // pages entered in the hash table

)

Header words.

View Source
const (
	CauseNone         = 0
	CauseDoubleFree   = 1 // a page returned to the bitmap was already free
	CauseStateCorrupt = 2 // an atomic update saw a state no correct run produces
	CauseSeqTooLong   = 3 // a sequence needed more than MaxSeqPages pages
	CauseHashFull     = 4 // an insert found no free hash slot
)

Cause codes, written once to WordCause by the first failure. They are lane 69's KV causes.

View Source
const DefaultDefragThreshold = 0.35

DefaultDefragThreshold is the default fragmentation index (0.35) that triggers proactive VRAM defragmentation.

View Source
const DefaultPrefixBlockSize = 16

DefaultPrefixBlockSize is the token granularity of content-addressed prefix cache blocks used by paged KV prefill reuse.

View Source
const EmptyEntry = ^uint64(0)
View Source
const LargeAllocationThresholdBytes uint64 = 4 << 30

LargeAllocationThresholdBytes is the derived 4 GiB (32-bit byte-offset) boundary above which a single contiguous underlying buffer allocation is promoted to cudatma.AllocLarge rather than Small (PTX ISA 9.5 Section 9.7.10.29).

Variables

View Source
var (
	// ErrHostCommandBusy reports a batch refused because another batch on the
	// same consumer is in progress. Nothing was removed from the ring.
	ErrHostCommandBusy = errors.New("cudakv: host command consumer busy")

	// ErrHostCommandUnsupported reports a requested mode the host consumer
	// does not provide. No such request falls back to host execution.
	ErrHostCommandUnsupported = errors.New("cudakv: host command capability unsupported")

	// ErrHostCommandInvalid reports a descriptor removed from the ring and
	// refused without running: an unknown SeqID, nonzero Flags, or a
	// PromptToken outside [0, VocabSize).
	ErrHostCommandInvalid = errors.New("cudakv: invalid host command descriptor")
)
View Source
var ErrBlockAllocatorUninitialized = errors.New("cudakv: block allocator must be created with NewBlockAllocator")

ErrBlockAllocatorUninitialized is returned when an allocation method is called on a BlockAllocator that was not created with NewBlockAllocator.

View Source
var ErrPressure = errors.New("no free page")

ErrPressure reports that an allocation found no free page and no page to evict.

View Source
var ErrStaleBranch = errors.New("cudakv: stale branch version")

ErrStaleBranch reports a request whose branch version is older than the version the cache already holds. The cache is unchanged.

Functions

func AllocClassForPoolBytes

func AllocClassForPoolBytes(poolBytes uint64) layout.AllocClass

AllocClassForPoolBytes returns the PTX 9.5 .alloc_class qualifier for a single contiguous underlying KV buffer allocation of size poolBytes. Single allocations larger than the derived 4 GiB threshold (LargeAllocationThresholdBytes) return cudatma.AllocLarge; allocations of <= 4 GiB or unknown size return cudatma.AllocSame so an existing Large or Small descriptor encoded on the host is preserved instead of silently resetting to Small.

func CompileFusedIndexKVStore

func CompileFusedIndexKVStore(spec FusedIndexKVStoreSpec) (string, error)

CompileFusedIndexKVStore generates NVRTC CUDA C++ source for set_index_kv_paged_kernel.

func EmitTMABlockRetarget

func EmitTMABlockRetarget(desc, blockAddress string) (string, error)

EmitTMABlockRetarget emits a PTX 9.5 tensormap.replace.tile.global_address instruction (Section 9.7.10.29) for a paged KV block descriptor in .shared::cta state space using cudatma.AllocSame so >4 GiB KV buffer allocations do not silently reset their allocation class to Small.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	ptx, err := nnkv.EmitTMABlockRetarget("%rd1", "%rd2")
	if err != nil {
		panic(err)
	}
	fmt.Println(ptx)
}
Output:
tensormap.replace.tile.global_address.alloc_same.shared::cta.b1024.b64 [%rd1], %rd2;

func EmitTMABlockRetargetForPool

func EmitTMABlockRetargetForPool(desc, blockAddress string, poolBytes uint64) (string, error)

EmitTMABlockRetargetForPool emits a PTX 9.5 tensormap.replace.tile.global_address instruction for a paged KV block descriptor in .shared::cta state space, selecting cudatma.AllocLarge when the single underlying buffer allocation poolBytes exceeds the derived 4 GiB threshold and cudatma.AllocSame otherwise.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	ptxSmall, err := nnkv.EmitTMABlockRetargetForPool("%rd1", "%rd2", 1<<30)
	if err != nil {
		panic(err)
	}
	ptxLarge, err := nnkv.EmitTMABlockRetargetForPool("%rd1", "%rd2", 8<<30)
	if err != nil {
		panic(err)
	}
	fmt.Println(ptxSmall)
	fmt.Println(ptxLarge)
}
Output:
tensormap.replace.tile.global_address.alloc_same.shared::cta.b1024.b64 [%rd1], %rd2;
tensormap.replace.tile.global_address.alloc_large.shared::cta.b1024.b64 [%rd1], %rd2;

func FP4DecodeScratch

func FP4DecodeScratch(queries, parts int) (int, error)

FP4DecodeScratch returns the required float32 workspace for split decode.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	// Split the page table for 64 queries eight ways.
	n, _ := kv.FP4DecodeScratch(64, 8)
	fmt.Println(n)
}
Output:
66560

func Fragmentation

func Fragmentation(totalFree, largestFree int) float64

Fragmentation calculates the memory fragmentation ratio:

Fragmentation = 1.0 - (LargestContiguousFree / TotalFree)

A value of 0.0 indicates zero fragmentation (all free memory is in one contiguous block). A value approaching 1.0 indicates severe fragmentation (free memory is split into tiny disjoint islands).

func HashPrefixBlocks

func HashPrefixBlocks(tokens []int32, blockSize int) []uint64

HashPrefixBlocks partitions tokens into complete blocks of blockSize tokens and returns the cumulative hash chain H_0, H_1, ..., H_{B-1}. Trailing tokens that do not fill a complete block are ignored.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	tokens := make([]int32, 36)
	for i := range tokens {
		tokens[i] = int32(i + 1)
	}
	hashes := nnkv.HashPrefixBlocks(tokens, nnkv.DefaultPrefixBlockSize)
	h0 := nnkv.HashTokenBlock(0, tokens[:16])
	h1 := nnkv.HashTokenBlock(h0, tokens[16:32])
	fmt.Println(len(hashes), hashes[0] == h0, hashes[1] == h1)
}
Output:
2 true true

func HashTokenBlock

func HashTokenBlock(parent uint64, tokens []int32) uint64

HashTokenBlock returns the deterministic 64-bit cumulative hash H_b = Hash(parent, tokens) for a single token block. A zero parent represents the start of a sequence (block 0). The returned digest is never zero.

func InterpolateReturnAnchors

func InterpolateReturnAnchors(anchors [][2]float64, bins int) []float64

InterpolateReturnAnchors returns m for 1 s bins 0..bins-1 from (tau, m) anchors sorted by tau: linear between anchors, the last anchor's value after it, rounded to 0.1 s. This is interpolate_anchors of retention_order.py, lines 85-99.

func MaxPrefillPrefixBlocks

func MaxPrefillPrefixBlocks(promptTokens, blockSize int) int

MaxPrefillPrefixBlocks returns the maximum number of complete blockSize-token blocks B that may be reused from a prefix cache for a prompt of length promptTokens while maintaining the strict invariant B*blockSize < promptTokens.

func Source

func Source() string

Source returns the CUDA C++ device functions that operate on the metadata. They take a kvd_cfg, which Config.CSource initializes, and the metadata words, and follow Region's algorithm step for step.

Under cudahostemu, define KVD_YIELD to a seed to yield the host thread at random before atomic accesses, so emulated runs explore more interleavings. The emulator's fences are sequentially consistent, so such runs find logic races but not missing fences.

func StoreIndexKVPagedCPU

func StoreIndexKVPagedCPU(
	kQuant []byte,
	kScale []byte,
	pageTable []int32,
	seqPositions []int32,
	pagePool []byte,
	spec FusedIndexKVStoreSpec,
) error

StoreIndexKVPagedCPU scatters quantized indexer keys (68 B for FP4 or 132 B for MXFP8) into paged pagePool at (pageTable[seq, pos/PageBlockSize], pos%PageBlockSize) with data at [0..DataBytes) and scale at [ScaleOffset..ScaleOffset+ScaleBytes).

func TokenSlotOffsets

func TokenSlotOffsets(
	format KVPageTokenFormat,
	pageBaseOffset int64,
	pageBlockSize int,
	tokenInPage int,
) (nopeOffset, ropeOffset, scaleOffset int64, err error)

TokenSlotOffsets computes exact byte offsets within a paged KV block for a given token format.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	nopeOff, ropeOff, scaleOff, err := nnkv.TokenSlotOffsets(nnkv.FormatMLA_V41_FP8, 4096, 64, 2)
	if err != nil {
		panic(err)
	}
	fmt.Printf("nope=%d rope=%d scale=%d\n", nopeOff, ropeOff, scaleOff)
}
Output:
nope=5152 rope=5600 scale=5664

func TrackerFragmentation

func TrackerFragmentation(tracker *cuda.Tracker, totalCapacityBytes, largestFreeBytes uint64) float64

TrackerFragmentation computes the fragmentation index for a cudamem.Tracker-managed memory pool given the total pool capacity in bytes and the largest contiguous free bytes.

func WriteWords

func WriteWords(w io.Writer, c Config, words []uint64) error

WriteWords writes metadata words laid out for c to w.

Types

type BlockAllocator

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

BlockAllocator hands out the physical slots of a block pool and counts the holders of each. It owns no device storage, so PagedCache's bookkeeping can be tested without a device. Create a BlockAllocator with NewBlockAllocator; its zero value is not usable.

A block is free when nothing holds it. A sequence holds every block in its table; a prefix cache that keeps a block alive after the sequence that wrote it has finished holds it too, through retain. The block returns to the free list when the last holder lets go, whichever kind of holder that is. Two unconnected owners of the same block, one recycling it while the other still reads it, is the failure this exists to rule out.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	allocator := nnkv.NewBlockAllocator(2, 2)
	if err := allocator.AllocSequence(7, nil, 3); err != nil {
		fmt.Println(err)
		return
	}
	if err := allocator.AppendToken(7); err != nil {
		fmt.Println(err)
		return
	}
	length, _ := allocator.SequenceLength(7)
	fmt.Println(allocator.Table(7), length, allocator.NumFreeBlocks())
}
Output:
[1 0] 4 0

func NewBlockAllocator

func NewBlockAllocator(blockSize, totalBlocks int) *BlockAllocator

NewBlockAllocator creates a new allocator with totalBlocks physical slots of blockSize tokens. If blockSize is not positive, totalBlocks is negative, or the block storage size is not representable, the allocator has no slots and AllocSequence and AppendToken report the invalid arguments.

func (*BlockAllocator) AllocSequence

func (a *BlockAllocator) AllocSequence(seqID int64, shared []int, tokens int) error

AllocSequence gives seqID a block table covering tokens. The first len(shared) blocks are shared with whoever already holds them and are counted as full; the rest come from the free list. Each shared block may appear at most once.

func (*BlockAllocator) AllocationGeneration

func (a *BlockAllocator) AllocationGeneration(seqID int64) (uint64, bool)

AllocationGeneration identifies the current allocation of seqID. Freeing and reallocating an ID changes its generation even if the same blocks are reused. Like the allocator's other methods, calls must be externally serialized.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	pool := nnkv.NewBlockAllocator(2, 1)
	_ = pool.AllocSequence(7, nil, 2)
	gen1, ok1 := pool.AllocationGeneration(7)
	pool.FreeSequence(7)
	_, okFree := pool.AllocationGeneration(7)
	_ = pool.AllocSequence(7, nil, 2)
	gen2, ok2 := pool.AllocationGeneration(7)
	fmt.Println(ok1, okFree, ok2, gen2 > gen1)
}
Output:
true false true true
Example
a := NewBlockAllocator(2, 1)
_ = a.AllocSequence(7, nil, 1)
g, ok := a.AllocationGeneration(7)
fmt.Println(g > 0, ok)
Output:
true true

func (*BlockAllocator) AppendToken

func (a *BlockAllocator) AppendToken(seqID int64) error

AppendToken reserves room for one more token in seqID, taking a fresh block at each block boundary.

func (*BlockAllocator) ApplyCompaction

func (a *BlockAllocator) ApplyCompaction(plan CompactionPlan)

ApplyCompaction applies the relocations in plan to the allocator's internal tables, holders, and free block list. Active residency owners refuse the operation without mutation; this void API does not report success. Cache consumers must check residency ownership before issuing any corresponding physical copies.

func (*BlockAllocator) BlockSize

func (a *BlockAllocator) BlockSize() int

BlockSize returns the token capacity per block.

func (*BlockAllocator) Check

func (a *BlockAllocator) Check() error

Check verifies the allocator's ownership invariants and reports the first violation:

  • a block is on the free list exactly when nothing holds it;
  • each resident sequence's table covers its length, in distinct, held blocks;
  • each block's holders are the tables it appears in plus its Retains;
  • a block held more than once is full in every table it appears in, so no two holders can both be writing it.

func (*BlockAllocator) FragmentationIndex

func (a *BlockAllocator) FragmentationIndex() float64

FragmentationIndex returns the current fragmentation ratio (0.0 to 1.0).

func (*BlockAllocator) FragmentationStats

func (a *BlockAllocator) FragmentationStats() FragmentationStats

FragmentationStats returns current fragmentation statistics for the allocator.

func (*BlockAllocator) FreeSequence

func (a *BlockAllocator) FreeSequence(seqID int64)

FreeSequence drops seqID's hold on its blocks. Blocks nothing else holds return to the free list; shared ones stay with their other holders.

func (*BlockAllocator) Holders

func (a *BlockAllocator) Holders(b int) (int, error)

Holders reports how many sequences and retainers hold block b.

func (*BlockAllocator) NumFreeBlocks

func (a *BlockAllocator) NumFreeBlocks() int

NumFreeBlocks returns the count of currently unallocated blocks.

func (*BlockAllocator) PlanCompaction

func (a *BlockAllocator) PlanCompaction(maxMoves int) CompactionPlan

PlanCompaction computes the optimal set of block relocations to compact all active blocks into contiguous low-index slots [0..ActiveBlocks-1].

func (*BlockAllocator) Release

func (a *BlockAllocator) Release(blocks []int) error

Release undoes one Retain for each occurrence of a block, freeing those left with no holder. A sequence's hold on the blocks in its table is not a Retain; only FreeSequence ends it. If any block has fewer Retains than requested, Release returns an error without changing any block.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	a := nnkv.NewBlockAllocator(4, 1)
	if err := a.AllocSequence(1, nil, 1); err != nil {
		fmt.Println(err)
		return
	}
	b := a.Table(1)[0]
	if err := a.Retain([]int{b, b}); err != nil {
		fmt.Println(err)
		return
	}
	err := a.Release([]int{b, b})
	holders, _ := a.Holders(b)
	fmt.Println(err == nil, holders, a.NumFreeBlocks())
}
Output:
true 1 0

func (*BlockAllocator) Reserve

func (a *BlockAllocator) Reserve(seqID int64, pos int) (block, slot int, err error)

Reserve makes position pos of seqID ready to write and returns the block holding it and the slot within that block. pos may be any position the sequence already covers, or its length, in which case Reserve first extends it by one token as AppendToken does. The block must be writable by seqID: a block the sequence shares with another holder is read-only.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	pool := nnkv.NewBlockAllocator(4, 8)
	_ = pool.AllocSequence(1, nil, 6)
	prefix, _ := pool.Share(1, 6) // one whole block of 4
	_ = pool.AllocSequence(2, prefix, 4)

	_, _, err := pool.Reserve(2, 3)
	fmt.Println(err)
	block, slot, err := pool.Reserve(2, 4)
	fmt.Println(block, slot, err, pool.Writable(2, block))
	fmt.Println(pool.Check())
}
Output:
cudakv: sequence 2 cannot write position 3: block 7 is shared or not resident
5 0 <nil> true
<nil>

func (*BlockAllocator) Retain

func (a *BlockAllocator) Retain(blocks []int) error

Retain adds a holder to each block. Every block must already be held: a free block has no contents worth keeping, so retaining one is a caller bug.

func (*BlockAllocator) SequenceLength

func (a *BlockAllocator) SequenceLength(seqID int64) (int, bool)

SequenceLength returns the number of tokens allocated to seqID.

func (*BlockAllocator) Share

func (a *BlockAllocator) Share(seqID int64, tokens int) ([]int, error)

Share returns the blocks holding the first tokens tokens of seqID, rounded down to whole blocks: the blocks another sequence may start on with AllocSequence. A partly filled block is never shared, since its owner may still write the rest of it. Share does not add holders.

func (*BlockAllocator) Table

func (a *BlockAllocator) Table(seqID int64) []int

Table returns a copy of the block table for sequence seqID.

func (*BlockAllocator) TotalBlocks

func (a *BlockAllocator) TotalBlocks() int

TotalBlocks returns the total capacity of physical blocks in the pool.

func (*BlockAllocator) ValidateSequence

func (a *BlockAllocator) ValidateSequence(seqID int64, generation uint64, blocks []int, tokens int) error

ValidateSequence checks a complete physical table against this pool's live sequence allocation and token capacity. It changes no allocation or holder.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	pool := nnkv.NewBlockAllocator(2, 2)
	_ = pool.AllocSequence(7, nil, 3)
	gen, _ := pool.AllocationGeneration(7)
	table := pool.Table(7)
	errValid := pool.ValidateSequence(7, gen, table, 3)
	errCap := pool.ValidateSequence(7, gen, table, 4)
	pool.FreeSequence(7)
	_ = pool.AllocSequence(7, nil, 3)
	errStale := pool.ValidateSequence(7, gen, pool.Table(7), 3)
	fmt.Println(errValid)
	fmt.Println(errCap)
	fmt.Println(errStale)
}
Output:
<nil>
cudakv: sequence table or capacity mismatch
cudakv: sequence allocation changed
Example
a := NewBlockAllocator(2, 1)
_ = a.AllocSequence(7, nil, 1)
g, _ := a.AllocationGeneration(7)
fmt.Println(a.ValidateSequence(7, g, a.Table(7), 1))
Output:
<nil>

func (*BlockAllocator) VirtualPageTable

func (a *BlockAllocator) VirtualPageTable(seqID int64) (VirtualPageTable, bool)

VirtualPageTable returns the virtual-to-physical block table for seqID.

func (*BlockAllocator) VirtualPageTables

func (a *BlockAllocator) VirtualPageTables() []VirtualPageTable

VirtualPageTables returns virtual page tables for all sequences.

func (*BlockAllocator) Writable

func (a *BlockAllocator) Writable(seqID int64, block int) bool

Writable reports whether seqID may write block: the sequence is resident, block is in its table, and nothing else holds block.

type BlockCopier

type BlockCopier interface {
	CopyBlock(srcSlot, dstSlot int) error
}

BlockCopier copies physical block contents between pool slots.

type BlockMove

type BlockMove struct {
	SrcBlock int // original physical slot (scattered, high index)
	DstBlock int // target physical slot (contiguous, low index)
}

BlockMove describes a single physical block relocation from SrcBlock to DstBlock.

type BlockState

type BlockState struct {
	// LastUsed is the cache's access tick at the block's last match or
	// store. Ticks are distinct and increase with time.
	LastUsed uint64
	// Idle is the time since that access on the cache's clock (see
	// SetClock), or zero without a clock.
	Idle time.Duration
	// Refs is the number of live branches whose context contains the block.
	Refs int
}

A BlockState describes one resident block to an EvictionOrder.

type Branch

type Branch struct {
	ID      string
	Version uint64
}

A Branch names one agent trajectory and the version of its context. A fork or sub-agent is a new ID. A compaction, which rewrites the context, is a new Version of the same ID. A request without a Branch leaves the cache's counts alone.

type BranchLRUOrder

type BranchLRUOrder struct{}

BranchLRUOrder evicts by (Refs > 0, LastUsed): every block no live branch references goes first, in LRU order, then referenced blocks in LRU order. The magnitude of a positive count does not matter.

func (BranchLRUOrder) Before

func (BranchLRUOrder) Before(a, b BlockState) bool

type Cache

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

Cache manages static multi-layer KV memory buffers for single-sequence decoding.

func New

func New(dev *cuda.Device, numLayers, numKVHeads, headDim, maxSeqLen int) (*Cache, error)

New creates a new static KV-cache allocating per-layer K and V buffers on dev. A non-nil error-result cache must be closed before closing dev.

func NewTracked

func NewTracked(dev *cuda.Device, tracker *cuda.Tracker, numLayers, numKVHeads, headDim, maxSeqLen int) (*Cache, error)

NewTracked creates a cache whose device allocations are accounted by tracker. A non-nil error-result cache is closed to use but retains buffers for Close.

func (*Cache) Advance

func (c *Cache) Advance(n int) error

Advance advances the token sequence position by n.

func (*Cache) ClearBuffers

func (c *Cache) ClearBuffers() error

ClearBuffers zeros every K and V buffer and reads it back to check that each element is zero. It does not change the position; a caller clearing related caches rewinds after all of them are clear.

func (*Cache) Close

func (c *Cache) Close() error

Close releases all GPU memory buffers allocated for the cache. A failed release retains the remaining buffers for retry. Further use is refused.

func (*Cache) Layer

func (c *Cache) Layer(idx int) (LayerCache, error)

Layer returns the KV buffers for the specified layer index.

func (*Cache) Pos

func (c *Cache) Pos() int

Pos returns the current token sequence position.

func (*Cache) Reset

func (c *Cache) Reset()

Reset rewinds the token sequence position to zero.

type Chunk

type Chunk struct {
	Index      int
	StartToken int
	EndToken   int
	Tokens     []int32
}

Chunk represents a segment of a long prompt for chunked prefill.

func ChunkPrompt

func ChunkPrompt(prompt []int32, chunkSize int) []Chunk

ChunkPrompt splits a prompt of tokens into chunks of max chunkSize.

type Codec

type Codec uint8

A Codec is the encoding of one element of a KV cache.

const (
	FP32    Codec = iota + 1 // IEEE binary32
	BF16                     // bfloat16
	FP8E4M3                  // OCP FP8 E4M3, read back as code times a float32 scale
)

func (Codec) Size

func (c Codec) Size() int

Size returns the bytes one element takes, or 0 if c is not a known codec.

func (Codec) String

func (c Codec) String() string

type CompactionGraph

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

CompactionGraph represents a captured CUDA execution graph of compaction memory copies.

func (*CompactionGraph) AddDeviceUpdate

func (cg *CompactionGraph) AddDeviceUpdate(update cudagraph.KernelNodeUpdate)

AddDeviceUpdate registers a kernel node update for device-side update pointers.

func (*CompactionGraph) ApplyToCache

func (cg *CompactionGraph) ApplyToCache(pc *PagedCache, stream *cuda.Stream, tree ...*RadixTree) error

ApplyToCache applies the compaction plan to pc and tree after graph execution completes.

func (*CompactionGraph) Destroy

func (cg *CompactionGraph) Destroy() error

Destroy releases the captured graph and instantiated execution resources. Failed cleanup retains remaining resources for retry and forbids new launches. The caller must complete previously launched work before destruction.

func (*CompactionGraph) DeviceNodes

func (cg *CompactionGraph) DeviceNodes() []cudagraph.DeviceNode

DeviceNodes returns the list of device nodes associated with this compaction graph.

func (*CompactionGraph) DeviceUpdates

func (cg *CompactionGraph) DeviceUpdates() []cudagraph.DeviceKernelNodeUpdate

DeviceUpdates converts registered updates into C-ABI compliant DeviceKernelNodeUpdate structs.

func (*CompactionGraph) Launch

func (cg *CompactionGraph) Launch(stream *cuda.Stream) error

Launch replays the captured compaction copies on stream.

func (*CompactionGraph) Plan

func (cg *CompactionGraph) Plan() CompactionPlan

Plan returns the compaction plan captured in this graph.

type CompactionPlan

type CompactionPlan struct {
	Moves              []BlockMove
	Remappings         map[int]int // SrcBlock -> DstBlock
	InitialFragIndex   float64
	EstimatedFragIndex float64
	ActiveBlocks       int
	TotalBlocks        int
}

CompactionPlan details the relocations needed to eliminate or reduce pool fragmentation.

func (CompactionPlan) Empty

func (p CompactionPlan) Empty() bool

Empty reports whether the plan has no block moves.

type Compactor

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

Compactor orchestrates proactive VRAM defragmentation and paged KV pool compaction.

Example
package main

import (
	"fmt"
	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	// Create a pool of 5 blocks, 2 tokens per block.
	cache, err := nnkv.NewTestPagedCache(1, 1, 4, 2, 5)
	if err != nil {
		panic(err)
	}
	defer cache.Close()

	// Allocate 5 sequences filling all 5 blocks.
	for s := int64(1); s <= 5; s++ {
		_ = cache.AllocSequence(s, 2)
	}

	// Free sequences 2 and 4 to create interleaved holes.
	cache.FreeSequence(2)
	cache.FreeSequence(4)

	fmt.Printf("Before compaction: %.2f\n", cache.FragmentationIndex())

	compactor := nnkv.NewCompactor(nnkv.DefaultDefragPolicy())
	plan, err := compactor.Compact(cache)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Compacted moves: %d\n", len(plan.Moves))
	fmt.Printf("After compaction: %.2f\n", cache.FragmentationIndex())
	fmt.Printf("Seq 5 block table: %v\n", cache.BlockTable(5))

}
Output:
Before compaction: 0.50
Compacted moves: 1
After compaction: 0.00
Seq 5 block table: [0]

func NewCompactor

func NewCompactor(policy DefragPolicy) *Compactor

NewCompactor creates a compactor with the given defragmentation policy.

func (*Compactor) CaptureGraph

func (c *Compactor) CaptureGraph(pc *PagedCache, stream *cuda.Stream, plan CompactionPlan) (*CompactionGraph, error)

CaptureGraph captures the compaction block copies for plan into a reusable CUDA Graph. On error, a non-nil result owns resources that the caller must Destroy.

func (*Compactor) Compact

func (c *Compactor) Compact(pc *PagedCache) (CompactionPlan, error)

Compact executes compaction synchronously on pc according to policy.

func (*Compactor) CompactOnStream

func (c *Compactor) CompactOnStream(pc *PagedCache, stream *cuda.Stream) (CompactionPlan, error)

CompactOnStream executes compaction on pc using the given stream for asynchronous copies. Virtual page tables and the attached RadixTree mappings are updated atomically.

func (*Compactor) Plan

func (c *Compactor) Plan(pc *PagedCache) CompactionPlan

Plan computes the compaction plan for pc without applying it.

func (*Compactor) Policy

func (c *Compactor) Policy() DefragPolicy

Policy returns the compactor policy.

func (*Compactor) ShouldCompact

func (c *Compactor) ShouldCompact(pc *PagedCache, neededBlocks int) bool

ShouldCompact checks whether pc currently requires compaction under the configured policy.

func (*Compactor) WithCopier

func (c *Compactor) WithCopier(copier BlockCopier) *Compactor

WithCopier attaches a custom BlockCopier for physical data relocation.

func (*Compactor) WithRadixTree

func (c *Compactor) WithRadixTree(tree *RadixTree) *Compactor

WithRadixTree attaches a RadixTree prefix cache whose block mappings will be updated atomically during compaction.

type Config

type Config struct {
	Pages       int // physical pages in the arena
	PageTokens  int // tokens per page
	MaxSeqs     int // sequence descriptors
	MaxSeqPages int // page-table entries per sequence
	JournalLen  int // journal events; a power of two
}

Config sizes the metadata regions. The sizes are fixed for the life of the arena.

func ReadWords

func ReadWords(r io.Reader) (Config, []uint64, error)

ReadWords reads metadata words written by WriteWords.

func (Config) CSource

func (c Config) CSource() string

CSource returns a C++ initializer for a kvd_cfg describing c.

func (Config) HashSlots

func (c Config) HashSlots() int

HashSlots returns the number of hash-table slots: the least power of two that is at least twice the number of pages.

func (Config) Init

func (c Config) Init() ([]uint64, error)

Init returns metadata for c in its initial state: every page free, every sequence descriptor free, every page-table entry empty.

func (Config) Validate

func (c Config) Validate() error

Validate reports whether c describes a usable layout.

func (Config) Words

func (c Config) Words() int

Words returns the length of the metadata array.

type Counters

type Counters struct {
	Allocs, Frees, Hits, Misses, Pressure, Evictions, Inserts uint64
}

Counters are the allocator's event counts.

type DefragPolicy

type DefragPolicy struct {
	// Threshold is the fragmentation index threshold (0.0 to 1.0) above which
	// compaction is triggered. Defaults to DefaultDefragThreshold (0.35).
	Threshold float64

	// MaxBlocksPerPass limits the maximum number of blocks moved in a single
	// compaction pass. 0 means unlimited (all scattered blocks are moved).
	MaxBlocksPerPass int
}

DefragPolicy specifies conditions that trigger proactive KV pool defragmentation.

func DefaultDefragPolicy

func DefaultDefragPolicy() DefragPolicy

DefaultDefragPolicy returns a DefragPolicy initialized with DefaultDefragThreshold (0.35).

func (DefragPolicy) ShouldCompact

func (p DefragPolicy) ShouldCompact(stats FragmentationStats, neededBlocks int) bool

ShouldCompact reports whether compaction should be executed based on the current fragmentation statistics and required contiguous blocks.

type Descriptor

type Descriptor struct {
	SeqID       uint64
	Generation  uint64
	PromptToken int32
	Flags       uint32
}

Descriptor is a copied host command value. Generation identifies the ring lifetime; the ring does not interpret the other fields.

type DeviceCommandRing

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

DeviceCommandRing is a bounded, mutex-protected host FIFO for one generation. It is not device-visible storage or a GPU publication protocol. The zero value cannot publish; use NewDeviceCommandRing.

func NewDeviceCommandRing

func NewDeviceCommandRing(capacity, generation uint64) (*DeviceCommandRing, error)

NewDeviceCommandRing creates a ring with capacity slots pinned to generation. Capacity and generation must be nonzero, and the slot storage byte extent must fit in int. The caller chooses a generation for this ring's lifetime; a new generation requires a new ring. Closing the old ring permits its queued descriptors to drain and does not report completion of their work.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	ring, err := nnkv.NewDeviceCommandRing(2, 7)
	if err != nil {
		fmt.Println(err)
		return
	}
	if err := ring.Publish(nnkv.Descriptor{SeqID: 42, Generation: 7, PromptToken: 9}); err != nil {
		fmt.Println(err)
		return
	}
	ring.Close()
	desc, ok := ring.Consume()
	fmt.Println(desc.SeqID, desc.Generation, desc.PromptToken, ok, ring.Len())
}
Output:
42 7 9 true 0

func (*DeviceCommandRing) Close

func (r *DeviceCommandRing) Close()

Close rejects future publications while allowing already published work to drain.

func (*DeviceCommandRing) Consume

func (r *DeviceCommandRing) Consume() (desc Descriptor, ok bool)

Consume removes and returns the oldest descriptor. It reports ok=false when the ring is empty.

func (*DeviceCommandRing) Len

func (r *DeviceCommandRing) Len() int

Len reports the number of descriptors currently queued.

func (*DeviceCommandRing) Publish

func (r *DeviceCommandRing) Publish(desc Descriptor) error

Publish copies desc into the next slot. Its generation must match the ring's nonzero generation. A refusal leaves the queued values and order unchanged.

type Entry

type Entry uint64

Entry is a page-table entry: the page in bits 0-31 and the generation it had when the entry was written in bits 32-61. EmptyEntry marks no page.

func (Entry) Gen

func (e Entry) Gen() uint32

func (Entry) Page

func (e Entry) Page() uint32

type Event

type Event struct {
	Kind EventKind
	Seq  uint32
	Step uint32
	Page uint32
	Gen  uint32
}

Event is a journal record. Its two words are kind (bits 0-7), sequence (8-31) and step (32-63); then page (0-31) and generation (32-61).

type EventKind

type EventKind uint8

EventKind identifies a journal event.

const (
	EventEvict   EventKind = 1 + iota // Seq evicted cached Page at Gen, to allocate it
	EventAlloc                        // Seq took fresh Page at Gen
	EventInsert                       // Seq entered its full Page at Gen in the hash table
	EventHit                          // Seq took a reference to hashed Page at Gen
	EventMiss                         // Seq's lookup found no page for its block Page
	EventRelease                      // Seq dropped a reference to Page at Gen; others remain
	EventCache                        // Seq dropped the last reference to hashed Page at Gen; it is cached
	EventFree                         // Seq dropped the last reference to Page at Gen; it is in limbo
	EventRetire                       // Seq finished
	EventStep                         // the step ended; Page pages left limbo
)

Event kinds, in the order Replay applies a step's events.

func (EventKind) String

func (k EventKind) String() string

type EvictionOrder

type EvictionOrder interface {
	// Before reports whether a should be evicted before b.
	Before(a, b BlockState) bool
}

An EvictionOrder chooses which resident block a PrefixBlockCache evicts when it needs a slot: the block that comes first.

type FP4GatedView

type FP4GatedView struct {
	Slots, Layers, KVHeads, MaxSequence int
}

FP4GatedView describes the contiguous 256-wide KV serving view. A page consists of two 128-wide rows for one token and KV head. Pages are ordered by slot, attention layer, KV head, then token.

func (FP4GatedView) Layout

func (v FP4GatedView) Layout(format kvquant.Format) (FP4PagedLayout, error)

Layout returns the two-row physical page layout for the serving view.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/nn/kv"
	"github.com/tmc/lib/nvidia/x/nn/kvquant"
)

func main() {
	view := kv.FP4GatedView{Slots: 2, Layers: 3, KVHeads: 4, MaxSequence: 16}
	layout, _ := view.Layout(kvquant.MXFP4)
	fmt.Println(layout.PageSize, layout.PageCount)
}
Output:
2 384

type FP4PagedKernels

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

FP4PagedKernels binds append and decode kernels to an sm_121a device and layout. A caller owns the cache and sequencing of reads and writes.

func NewFP4PagedKernels

func NewFP4PagedKernels(dev *cuda.Device, l FP4PagedLayout) (*FP4PagedKernels, error)

NewFP4PagedKernels compiles the native kernel pair using NVRTC.

func (*FP4PagedKernels) Append

func (k *FP4PagedKernels) Append(stream *cuda.Stream, packed, scales cuda.Slice[byte], rows cuda.Slice[int32], source cuda.Slice[float32]) error

Append quantizes and stores finite [row, key/value, 128] source values. rows names distinct, in-range physical rows in the pool. The GPU does not write entries for invalid row IDs. Source and destinations must be disjoint. The launch is asynchronous.

func (*FP4PagedKernels) Close

func (k *FP4PagedKernels) Close() error

Close releases the kernel module. The caller must finish work using the module before closing it.

func (*FP4PagedKernels) Decode

func (k *FP4PagedKernels) Decode(stream *cuda.Stream, packed, scales cuda.Slice[byte], pages cuda.Slice[int32], queries, output cuda.Slice[float32], tokens int) error

Decode runs one query per head. Queries and output are flattened [query, 128] slices. pages contains [query, ceil(tokens/PageSize)] physical page IDs. An invalid page ID produces NaNs for the affected query. The cache must have been initialized by Append, or with equivalent finite FP4 blocks, and output must not overlap the inputs. The launch is asynchronous.

func (*FP4PagedKernels) DecodeGated

func (k *FP4PagedKernels) DecodeGated(stream *cuda.Stream, packed, scales cuda.Slice[byte],
	slots, positions cuda.Slice[int32], query, gate, output cuda.Slice[float32],
	v FP4GatedView, layer, queryHeads int) error

DecodeGated runs one 256-wide query per attention head and applies sigmoid gating. The caller supplies nonaliasing contiguous inputs and output. Slots and positions must identify populated prefixes within the view. Out-of-range entries write NaNs for the affected queries.

func (*FP4PagedKernels) DecodeSplit

func (k *FP4PagedKernels) DecodeSplit(stream *cuda.Stream, packed, scales cuda.Slice[byte], pages cuda.Slice[int32], queries, output, scratch cuda.Slice[float32], tokens, parts int) error

DecodeSplit partitions each query across independent CUDA blocks and merges their softmax states. scratch must be disjoint from all inputs and output. See FP4DecodeScratch for the workspace size.

type FP4PagedLayout

type FP4PagedLayout struct {
	Format    kvquant.Format
	PageSize  int
	PageCount int
}

FP4PagedLayout describes a fixed-size physical FP4 page pool. Each page holds PageSize rows for one attention head of dimension 128. Each row stores packed keys then packed values, with corresponding per-block scale bytes in a separate allocation.

func (FP4PagedLayout) Bytes

func (l FP4PagedLayout) Bytes() (packed, scales int, err error)

Bytes returns the exact payload and scale allocation sizes in bytes.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/nn/kv"
	"github.com/tmc/lib/nvidia/x/nn/kvquant"
)

func main() {
	// The allocations hold 512 rows of one head.
	layout := kv.FP4PagedLayout{Format: kvquant.NVFP4, PageSize: 64, PageCount: 8}
	packed, scales, _ := layout.Bytes()
	fmt.Println(packed, scales)
}
Output:
65536 8192

type FP8Cache

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

FP8Cache manages 8-bit quantized KV memory buffers for low-bandwidth inference.

func NewFP8

func NewFP8(dev *cuda.Device, numLayers, numKVHeads, headDim, maxSeqLen int) (*FP8Cache, error)

NewFP8 creates a new static FP8 KV-cache allocating per-layer 8-bit K and V buffers on dev. A non-nil error-result cache must be closed before closing dev.

func NewFP8Tracked

func NewFP8Tracked(dev *cuda.Device, tracker *cuda.Tracker, numLayers, numKVHeads, headDim, maxSeqLen int) (*FP8Cache, error)

NewFP8Tracked creates an FP8 cache whose device allocations, the K and V buffers and the per-head scales, are accounted by tracker.

The scales are left uninitialized: the caller decides the quantization and writes one factor per KV head into KScale and VScale of every layer before storing into the cache. A non-nil error-result cache retains cleanup ownership and must be closed.

func (*FP8Cache) Close

func (c *FP8Cache) Close() error

Close releases all GPU memory buffers allocated for the FP8 cache. Failed cleanup retains the remaining buffers for retry and forbids further use.

func (*FP8Cache) Layer

func (c *FP8Cache) Layer(idx int) (FP8LayerCache, error)

Layer returns the FP8 KV buffers for the specified layer index.

func (*FP8Cache) Layout

func (c *FP8Cache) Layout() Layout

Layout returns the layout of each layer's K buffer, and of each layer's V buffer: FP8 E4M3 codes with one float32 scale per head, in KScale and VScale, shared by every token.

type FP8LayerCache

type FP8LayerCache struct {
	LayerIndex int
	K          cuda.Slice[uint8]
	V          cuda.Slice[uint8]
	KScale     cuda.Slice[float32]
	VScale     cuda.Slice[float32]
}

FP8LayerCache holds 8-bit quantized K and V buffers and scaling factors for one layer.

type FragmentationStats

type FragmentationStats struct {
	TotalBlocks        int
	AllocatedBlocks    int
	FreeBlocks         int
	LargestContiguous  int
	FragmentationIndex float64
}

FragmentationStats reports metrics about the allocator's free and allocated blocks.

type FusedIndexKVStoreSpec

type FusedIndexKVStoreSpec struct {
	HeadDim       int
	PageBlockSize int
	UseFP4        bool
}

FusedIndexKVStoreSpec configures paged scatter storage of quantized indexer keys.

func (FusedIndexKVStoreSpec) Validate

func (s FusedIndexKVStoreSpec) Validate() error

Validate checks that s has a valid HeadDim, PageBlockSize, and format configuration.

type Granularity

type Granularity uint8

A Granularity says which elements of a KV buffer share one float32 scale.

const (
	NoScale           Granularity = iota // elements are stored as they are read
	ScalePerTensor                       // one scale for the whole buffer
	ScalePerLayerHead                    // one per slot, layer and head, across tokens
	ScalePerToken                        // one per slot, layer and token, across heads
	ScalePerTokenHead                    // one per slot, layer, token and head
)

func (Granularity) String

func (g Granularity) String() string

type HostCommandBatch

type HostCommandBatch struct {
	Consumed  int
	Completed int
	Words     int
}

HostCommandBatch reports one call to HostCommandConsumer.ConsumeBatch. Consumed counts descriptors removed from the ring, Completed counts callbacks that returned nil, and Words counts input words passed to callbacks, including a callback that failed. A removed descriptor is never requeued.

type HostCommandConfig

type HostCommandConfig struct {
	Mode             string
	Generation       uint64
	VocabSize        int32
	MaxEntries       int
	MaxRegistryWords int
	MaxBatch         int
	MaxBatchWords    int
}

HostCommandConfig bounds a copied command registry and each batch.

Mode must be "host-finite"; any other value, including a GPU polling, GIN or decode mode, is refused with ErrHostCommandUnsupported. Generation must equal the ring's generation. VocabSize bounds PromptToken. MaxEntries and MaxBatch must be in [1, 1024]; MaxRegistryWords and MaxBatchWords must be in [1, 1<<20].

type HostCommandConsumer

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

A HostCommandConsumer drains a DeviceCommandRing in bounded synchronous batches, passing each descriptor and its registered input to a caller function on the calling goroutine.

It is host batching only. It starts no goroutines, provides no device executor, and does not poll device-visible memory. Whatever the callback runs, a successful batch is not evidence of persistent GPU execution, model decoding or network transfer.

The consumer borrows the ring and never closes it. The zero value is unusable; use NewHostCommandConsumer.

func NewHostCommandConsumer

func NewHostCommandConsumer(ring *DeviceCommandRing, config HostCommandConfig, inputs []HostCommandInput) (*HostCommandConsumer, error)

NewHostCommandConsumer returns a consumer for ring with a copied registry of inputs. It checks every limit before allocating; later changes to inputs do not affect the consumer. Each entry must have a distinct nonzero SeqID and between 1 and MaxBatchWords words, and the entries together at most MaxRegistryWords words.

Example (Unsupported)
package main

import (
	"fmt"
	"log"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	ring, err := nnkv.NewDeviceCommandRing(1, 1)
	if err != nil {
		log.Fatal(err)
	}
	_, err = nnkv.NewHostCommandConsumer(ring, nnkv.HostCommandConfig{Mode: "device-poll"}, nil)
	fmt.Println(err)
}
Output:
cudakv: host command capability unsupported: mode "device-poll"

func (*HostCommandConsumer) ConsumeBatch

func (c *HostCommandConsumer) ConsumeBatch(ctx context.Context, limit int, run func(context.Context, Descriptor, []uint32) error) (HostCommandBatch, error)

ConsumeBatch removes at most limit descriptors in FIFO order and calls run once for each, with a fresh copy of the registered input that run may keep. It returns when the ring is empty, limit descriptors were consumed, or the next input would exceed MaxBatchWords for this batch; in each of those cases the error is nil and later descriptors stay queued.

A descriptor that fails validation is removed and refused with ErrHostCommandInvalid without calling run. If run returns an error, ConsumeBatch returns it wrapped. A concurrent call refuses with ErrHostCommandBusy rather than waiting.

The context is checked before each removal; a cancelled context leaves the next descriptor queued. Once removed, a descriptor is passed to run even if the context is cancelled meanwhile; run receives the context and decides. Cancellation cannot roll back run's effects, and a native callback must retain its resources until the device work it submitted completes. If run panics, its descriptor stays consumed and the panic propagates.

Example
package main

import (
	"context"
	"fmt"
	"log"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	ring, err := nnkv.NewDeviceCommandRing(4, 1)
	if err != nil {
		log.Fatal(err)
	}
	consumer, err := nnkv.NewHostCommandConsumer(ring, nnkv.HostCommandConfig{
		Mode:             "host-finite",
		Generation:       1,
		VocabSize:        16,
		MaxEntries:       2,
		MaxRegistryWords: 4,
		MaxBatch:         2,
		MaxBatchWords:    4,
	}, []nnkv.HostCommandInput{
		{SeqID: 3, Words: []uint32{8, 9}},
		{SeqID: 4, Words: []uint32{100}},
	})
	if err != nil {
		log.Fatal(err)
	}
	for _, d := range []nnkv.Descriptor{{SeqID: 3, PromptToken: 2}, {SeqID: 4, PromptToken: 5}, {SeqID: 3}} {
		d.Generation = 1
		if err := ring.Publish(d); err != nil {
			log.Fatal(err)
		}
	}
	batch, err := consumer.ConsumeBatch(context.Background(), 2, func(_ context.Context, d nnkv.Descriptor, input []uint32) error {
		fmt.Println("sequence", d.SeqID, "token", d.PromptToken, "input", input)
		return nil
	})
	fmt.Printf("%+v %v, %d queued\n", batch, err, ring.Len())
}
Output:
sequence 3 token 2 input [8 9]
sequence 4 token 5 input [100]
{Consumed:2 Completed:2 Words:3} <nil>, 1 queued

type HostCommandInput

type HostCommandInput struct {
	SeqID uint64
	Words []uint32
}

HostCommandInput binds a nonzero SeqID to application input words. SeqID is an application identity, not a device publication sequence.

type KVPageFormatDescriptor

type KVPageFormatDescriptor struct {
	Format        KVPageTokenFormat
	BytesPerToken int
	NoPEBytes     int
	RoPEBytes     int
	DataBytes     int
	ScaleBytes    int
	ScaleOffset   int
	PaddingBytes  int
}

KVPageFormatDescriptor describes the byte layout of a single token in a paged KV block.

type KVPageTokenFormat

type KVPageTokenFormat int

KVPageTokenFormat identifies a sub-byte paged KV or indexer KV token storage layout.

const (
	// FormatMLA_V32_FP8 is the DeepSeek-V3.2 FP8 paged KV token layout (656 B/token: 512B NoPE, 128B RoPE, 16B scales at 640).
	FormatMLA_V32_FP8 KVPageTokenFormat = iota + 1
	// FormatMLA_V41_FP8 is the DeepSeek-V4.1 FP8 paged KV token layout (528 B/token: 448B NoPE, 64B RoPE, 16B scales at 512).
	FormatMLA_V41_FP8
	// FormatMLA_V41_FP4 is the DeepSeek-V4.1 FP4 paged KV token layout (288 B/token: 224B NoPE, 32B RoPE, 28B scales at 256, 4B pad).
	FormatMLA_V41_FP4
	// FormatIndexKV_MXFP8 is the DeepSeek-V4.1 MXFP8 indexer KV token layout (132 B/token: 128B data, 4B UE8M0 scales at 128).
	FormatIndexKV_MXFP8
	// FormatIndexKV_FP4 is the DeepSeek-V4.1 FP4 indexer KV token layout (68 B/token: 32B data, 4B scales at 64).
	FormatIndexKV_FP4
)

func (KVPageTokenFormat) Descriptor

Descriptor returns the byte layout descriptor for f.

func (KVPageTokenFormat) String

func (f KVPageTokenFormat) String() string

String returns the canonical name of f.

type LRUOrder

type LRUOrder struct{}

LRUOrder evicts the least recently used block first. It is the default order and ignores branch counts.

func (LRUOrder) Before

func (LRUOrder) Before(a, b BlockState) bool

type LatentLayout

type LatentLayout struct {
	LatentDim, RopeDim int
}

A LatentLayout is the shape of an MLA (multi-head latent attention) cache entry: one compressed latent vector c_kv of LatentDim elements and one decoupled RoPE key k_pe of RopeDim elements per token, shared by every query head. There is no separate V: attention reads values from c_kv.

func (LatentLayout) Layouts

func (m LatentLayout) Layouts(codec Codec, scale Granularity, slots, layers, tokens int) (latent, rope Layout, err error)

Layouts returns the layouts of the c_kv and k_pe buffers, each a single head per token, for the given codec, scale granularity and extents. The scale granularity applies to each buffer on its own.

type LayerCache

type LayerCache struct {
	LayerIndex int
	K          cuda.Slice[float32]
	V          cuda.Slice[float32]
}

LayerCache holds the allocated K and V tensor memory buffers for a single transformer layer.

type LayerKVRole

type LayerKVRole int

LayerKVRole identifies whether a decoder layer produces its own KV cache or consumes a shared source layer's KV cache.

const (
	// LayerKVProducer indicates a layer that computes and stores its own KV cache.
	LayerKVProducer LayerKVRole = iota + 1
	// LayerKVSharedConsumer indicates a layer that reuses the KV cache produced by an earlier SourceLayerID.
	LayerKVSharedConsumer
)

type Layout

type Layout struct {
	Codec Codec
	Scale Granularity

	Slots, Layers, Tokens, Heads, HeadDim int
}

A Layout describes one KV buffer (the K buffer, the V buffer, or one part of an MLA latent cache) as a dense row-major array indexed by slot, layer, token, head and element within the head, outermost first. A paged pool is a layout whose tokens are blocks times the block size.

Scales, when the codec has them, are a separate float32 array indexed by the coordinates the granularity keeps, in the same order: slot, layer, token, head. See Layout.ScaleIndex.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	l := nnkv.Layout{Codec: nnkv.FP8E4M3, Scale: nnkv.ScalePerTokenHead, Slots: 4, Layers: 16, Tokens: 2048, Heads: 8, HeadDim: 64}
	if err := l.Check(); err != nil {
		fmt.Println(err)
		return
	}
	i, _ := l.Index(1, 2, 3, 4)
	s, _ := l.ScaleIndex(1, 2, 3, 4)
	fmt.Println(l.DataBytes(), l.ScaleBytes())
	fmt.Println(i, s)
}
Output:
67108864 4194304
18876160 294940

func (Layout) Bytes

func (l Layout) Bytes() int64

Bytes returns DataBytes plus ScaleBytes.

func (Layout) CUDA

func (l Layout) CUDA(name string) (string, error)

CUDA returns CUDA source that describes l to device code: macros NAME_SLOTS, NAME_LAYERS, NAME_TOKENS, NAME_HEADS, NAME_HEAD_DIM, the element strides NAME_SLOT_STRIDE, NAME_LAYER_STRIDE, NAME_TOKEN_STRIDE and NAME_HEAD_STRIDE, and NAME_SCALES, where NAME is name in upper case; and device functions name_index and name_scale_index, which return what Layout.Index and Layout.ScaleIndex do for coordinates inside l. name_scale_index is omitted when l has no scales.

Kernels that include the source address a buffer of layout l the way the host does, and a host check that a buffer's layout equals l before launching such a kernel binds the two.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	l := nnkv.Layout{Codec: nnkv.FP8E4M3, Scale: nnkv.ScalePerLayerHead, Slots: 1, Layers: 1, Tokens: 16, Heads: 2, HeadDim: 4}
	src, err := l.CUDA("kv")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Print(src)
}
Output:
// kv: cudakv.Layout fp8e4m3, scale granularity layer-head.
#define KV_SLOTS 1LL
#define KV_LAYERS 1LL
#define KV_TOKENS 16LL
#define KV_HEADS 2LL
#define KV_HEAD_DIM 4LL
#define KV_SLOT_STRIDE 128LL
#define KV_LAYER_STRIDE 128LL
#define KV_TOKEN_STRIDE 8LL
#define KV_HEAD_STRIDE 4LL
#define KV_SCALES 2LL
__device__ __forceinline__ long long kv_index(int slot, int layer, int token, int head) {
    return slot * KV_SLOT_STRIDE + layer * KV_LAYER_STRIDE + token * KV_TOKEN_STRIDE + head * KV_HEAD_STRIDE;
}
__device__ __forceinline__ long long kv_scale_index(int slot, int layer, int token, int head) {
    return ((long long)slot * KV_LAYERS + layer) * KV_HEADS + head;
}

func (Layout) Check

func (l Layout) Check() error

Check reports whether l is usable: a known codec, a scale granularity the codec allows (FP8 needs scales, the others take none), positive extents, and a byte size that fits in an int.

func (Layout) DataBytes

func (l Layout) DataBytes() int64

DataBytes returns the size of the buffer's elements in bytes.

func (Layout) Elements

func (l Layout) Elements() int64

Elements returns the number of elements in the buffer.

func (Layout) Index

func (l Layout) Index(slot, layer, token, head int) (int64, error)

Index returns the index of the first element of the given head, which must lie within l.

func (Layout) ScaleBytes

func (l Layout) ScaleBytes() int64

ScaleBytes returns the size of the buffer's scales in bytes.

func (Layout) ScaleIndex

func (l Layout) ScaleIndex(slot, layer, token, head int) (int64, error)

ScaleIndex returns the index in the scale array of the scale for the given head, which must lie within l. It is an error if l has no scales.

func (Layout) Scales

func (l Layout) Scales() int64

Scales returns the number of float32 scales the buffer has.

func (Layout) Strides

func (l Layout) Strides() (slot, layer, token, head int64)

Strides returns the distance in elements between consecutive slots, layers, tokens and heads.

type Model

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

A Model is a sequential reference for the allocator, kept in Go values rather than packed words. It has the Region's semantics, including limbo, cached pages and CLOCK eviction, and picks pages as a Region run by one thread does, so it says nothing about which physical page a concurrent run uses.

func NewModel

func NewModel(c Config) (*Model, error)

NewModel returns a model for c in its initial state.

func Replay

func Replay(c Config, events []Event) (*Model, error)

Replay rebuilds a model from a journal, and reports the first event the model refuses. Events of a step may be journaled in any order, so Replay applies each step's evictions first, then its allocations, insertions, hits and drops: whatever order the device ran them in, each was legal at that point in the reordered step if it was in the real one. A page cached in a step cannot be evicted in it, so no eviction depends on a later event of its step. Reordering can turn the drop that cached a page into one that released it, and the reverse, so Replay does not tell them apart. Sequence lengths are not journaled; the replayed tables hold each sequence's pages in no particular order.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	c := nnkv.Config{Pages: 4, PageTokens: 16, MaxSeqs: 2, MaxSeqPages: 2, JournalLen: 64}
	r, _ := nnkv.NewRegion(c)
	r.Admit(0)
	r.Append(0, 1)
	r.Finish(0)
	r.EndStep()

	s, _ := nnkv.Decode(c, r.Words())
	for _, e := range s.Journal {
		fmt.Println(e.Step, e.Kind, e.Seq, e.Page)
	}
	m, err := nnkv.Replay(c, s.Journal)
	fmt.Println("replayed free pages:", m.Free(), err)
}
Output:
0 alloc 0 0
0 free 0 0
0 retire 0 0
0 step 0 1
replayed free pages: 4 <nil>

func (*Model) Admit

func (m *Model) Admit(q int) error

Admit starts sequence q with no tokens.

func (*Model) Append

func (m *Model) Append(q int, tok uint32) error

Append appends token tok to q.

func (*Model) Cached

func (m *Model) Cached() int

Cached reports the number of cached pages.

func (*Model) EndStep

func (m *Model) EndStep()

EndStep returns the pages in limbo to the bitmap.

func (*Model) Finish

func (m *Model) Finish(q int) error

Finish enters q's last page in the hash table if it is full, drops every page q holds, and retires it.

func (*Model) Free

func (m *Model) Free() int

Free reports the number of pages in the bitmap.

func (*Model) Len

func (m *Model) Len(q int) int

Len reports q's token count.

func (*Model) Limbo

func (m *Model) Limbo() int

Limbo reports the number of pages freed this step.

func (*Model) Lookup

func (m *Model) Lookup(q int, toks []uint32) (int, error)

Lookup gives q, with no tokens yet, the hashed pages holding the longest whole-page prefix of toks that leaves at least one token, and reports how many it took.

func (*Model) Ref

func (m *Model) Ref(p uint32) uint32

Ref reports page p's reference count.

func (*Model) Table

func (m *Model) Table(q int) []Entry

Table returns q's page-table entries.

type Page

type Page struct {
	K cuda.Slice[float32]
	V cuda.Slice[float32]
}

Page holds the K and V storage for one layer and one physical slot. The slices are views into PagedCache storage and must not be freed.

type PageKey

type PageKey struct {
	Parent Entry
	Tokens []uint32
}

A PageKey identifies a page's contents: the entry of the page before it in the sequence that wrote it (EmptyEntry for a sequence's first page) and its tokens. It is meaningful only for a page that is, or was, full.

type PageState

type PageState uint8

PageState is the state of a physical page.

const (
	PageFree   PageState = iota // in the bitmap or in limbo
	PageOwned                   // written by the one sequence that holds it, not hashed
	PageShared                  // full, hashed, read-only, held by Ref sequences
	PageCached                  // full, hashed, read-only, held by none; evictable
)

func (PageState) String

func (s PageState) String() string

type PageWord

type PageWord uint64

PageWord is a page's state word: state in bits 62-63, generation in bits 32-61, reference count in bits 0-31. The generation changes each time the page is freed or evicted. A cached page has no references; its bits 0-31 hold the low bits of the step in which it became cached instead, and it cannot be evicted until a later step, so readers of that step are done with it.

func (PageWord) Gen

func (w PageWord) Gen() uint32

func (PageWord) Ref

func (w PageWord) Ref() uint32

func (PageWord) Since

func (w PageWord) Since() uint32

Since reports the step in which a cached page became cached, modulo 2³².

func (PageWord) State

func (w PageWord) State() PageState

type PagedCache

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

PagedCache is a pool of fixed-size KV blocks shared by many sequences, each with its own block table, for continuous batching.

A block is freed when its last holder lets go. A sequence holds the blocks in its table; a prefix cache keeps blocks past the end of the sequence that wrote them with Retain and gives them up with Release. AllocSequenceWithPrefix starts a sequence on blocks another holder already has. Nothing here reads or writes the blocks: that is the attention kernel's job, through Page.

func NewPagedCache

func NewPagedCache(dev *cuda.Device, numLayers, numKVHeads, headDim, blockSize, totalBlocks int) (*PagedCache, error)

NewPagedCache creates a paged KV cache allocator with totalBlocks physical slots of blockSize tokens. A non-nil error-result cache must be closed before closing dev.

func NewPagedCacheTracked

func NewPagedCacheTracked(dev *cuda.Device, tracker *cuda.Tracker, numLayers, numKVHeads, headDim, blockSize, totalBlocks int) (*PagedCache, error)

NewPagedCacheTracked creates a paged cache whose pool is accounted by tracker. A non-nil error-result cache retains partial allocations for Close.

func NewTestPagedCache

func NewTestPagedCache(numLayers, numKVHeads, headDim, blockSize, totalBlocks int) (*PagedCache, error)

NewTestPagedCache creates a paged KV cache backed by host memory for testing allocation, token retention, and compaction without a CUDA GPU.

func (*PagedCache) AllocSequence

func (pc *PagedCache) AllocSequence(seqID int64, promptTokens int) error

AllocSequence gives a new sequence enough blocks for promptTokens tokens.

func (*PagedCache) AllocSequenceWithPrefix

func (pc *PagedCache) AllocSequenceWithPrefix(seqID int64, prefix []int, promptTokens int) error

AllocSequenceWithPrefix gives a new sequence a block table that begins with prefix, blocks another holder (a finished sequence kept by a prefix cache, or a live one) already has, and continues with fresh blocks up to promptTokens.

The prefix blocks count as full: promptTokens must be at least len(prefix)*blockSize, and the sequence writes only from that position on. Every prefix block must currently be held; sharing a free block is an error, since nothing guarantees what it contains.

func (*PagedCache) AllocationGeneration

func (pc *PagedCache) AllocationGeneration(sequence int64) (uint64, bool)

AllocationGeneration identifies a sequence allocation even while suspended. A generation alone is not a usable binding; ValidateSequence also checks completed residency, physical table and token capacity.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	pc, _ := nnkv.NewTestPagedCache(1, 1, 2, 2, 2)
	defer pc.Close()
	pc.AllocSequence(7, 2)
	generation, ok := pc.AllocationGeneration(7)
	fmt.Println(generation, ok)
}
Output:
1 true

func (*PagedCache) AppendToken

func (pc *PagedCache) AppendToken(seqID int64) error

AppendToken reserves physical memory for an additional decoded token in sequence.

func (*PagedCache) BlockSize

func (pc *PagedCache) BlockSize() int

BlockSize returns the token capacity per block.

func (*PagedCache) BlockTable

func (pc *PagedCache) BlockTable(seqID int64) []int

BlockTable returns a copy of the block table for sequence seqID.

func (*PagedCache) Close

func (pc *PagedCache) Close() error

Close deallocates all physical GPU memory buffers. The caller must first complete all GPU use of pages. Failed cleanup retains the remaining buffers for retry; page access and allocation remain closed.

func (*PagedCache) Defrag

func (pc *PagedCache) Defrag(policy ...DefragPolicy) (CompactionPlan, error)

Defrag performs proactive compaction on pc according to policy.

func (*PagedCache) EmitTMABlockRetarget

func (pc *PagedCache) EmitTMABlockRetarget(desc, blockAddress string) (string, error)

EmitTMABlockRetarget emits a PTX 9.5 tensormap.replace.tile.global_address instruction for retargeting a .shared::cta TMA descriptor across a per-layer K or V block buffer in pc using pc.TMABlockRetargetAllocClass().

func (*PagedCache) FragmentationIndex

func (pc *PagedCache) FragmentationIndex() float64

FragmentationIndex returns the current fragmentation ratio (0.0 to 1.0).

func (*PagedCache) FragmentationStats

func (pc *PagedCache) FragmentationStats() FragmentationStats

FragmentationStats returns current pool fragmentation statistics.

func (*PagedCache) FreeSequence

func (pc *PagedCache) FreeSequence(seqID int64)

FreeSequence ends a sequence's hold on its blocks. Blocks nothing else holds return to the pool; blocks a prefix cache retained, or another sequence shares, stay allocated. Freeing an unknown sequence does nothing.

func (*PagedCache) Holders

func (pc *PagedCache) Holders(block int) (int, error)

Holders reports how many sequences and retainers hold block. Zero means free.

func (*PagedCache) LayerBufferBytes

func (pc *PagedCache) LayerBufferBytes() uint64

LayerBufferBytes returns the byte capacity of a single per-layer K (or V) float32 block buffer allocation as recorded by NewPagedCache, NewPagedCacheTracked, or NewTestPagedCache. Because NewPagedCache allocates each layer's K and V buffers as separate device allocations, TMA descriptors retargeted across blocks in a layer span a single LayerBufferBytes() allocation. It returns 0 if pc is nil or uninitialized.

func (*PagedCache) LayerPool

func (pc *PagedCache) LayerPool(layer int) (Page, error)

LayerPool returns the full K and V pool storage for layer across all physical blocks. Kernels that index blocks through a device block table use these views as base pointers without requiring any particular physical slot to be allocated. The returned views are valid until Close and must not be freed.

func (*PagedCache) Layout

func (pc *PagedCache) Layout() Layout

Layout returns the layout of each layer's K buffer, and of each layer's V buffer: block b holds tokens b*BlockSize through (b+1)*BlockSize-1.

func (*PagedCache) MemoryFragmentation

func (pc *PagedCache) MemoryFragmentation() (fragIndex float64, totalFreeBytes, largestFreeBytes uint64)

MemoryFragmentation reports fragmentation stats in bytes, connecting the block pool metrics with cudamem.Tracker accounting.

func (*PagedCache) NumFreeBlocks

func (pc *PagedCache) NumFreeBlocks() int

NumFreeBlocks returns the count of currently unallocated physical blocks.

func (*PagedCache) Page

func (pc *PagedCache) Page(layer, slot int) (Page, error)

Page returns the storage for layer and physical slot. The returned views are valid until Close and must not be freed.

func (*PagedCache) PoolBytes

func (pc *PagedCache) PoolBytes() uint64

PoolBytes returns the aggregate byte capacity across all layers' separate K and V float32 block buffers (numLayers * 2 * LayerBufferBytes()). For TMA descriptor allocation-class sizing, use LayerBufferBytes() or TMABlockRetargetAllocClass(), since each layer's K and V buffers are allocated separately.

func (*PagedCache) ReadToken

func (pc *PagedCache) ReadToken(seqID int64, tokenIdx int, layer int) (k, v []float32, err error)

ReadToken retrieves K and V activations for tokenIdx of seqID in layer.

func (*PagedCache) Release

func (pc *PagedCache) Release(blocks []int) error

Release undoes one Retain, returning to the pool any block left with no holder. The share AllocSequenceWithPrefix takes ends with FreeSequence.

func (*PagedCache) Retain

func (pc *PagedCache) Retain(blocks []int) error

Retain keeps blocks allocated after the sequence holding them is freed, until a matching Release. It is how a prefix cache takes ownership of the blocks a finished sequence wrote. Every block must currently be held.

func (*PagedCache) TMABlockRetargetAllocClass

func (pc *PagedCache) TMABlockRetargetAllocClass() layout.AllocClass

TMABlockRetargetAllocClass returns the PTX 9.5 .alloc_class qualifier for retargeting TMA descriptors over a per-layer K or V buffer in pc (cudatma.AllocLarge when LayerBufferBytes() > 4 GiB, cudatma.AllocSame otherwise).

func (*PagedCache) Table

func (pc *PagedCache) Table(seqID int64) []int

Table returns a copy of the block table for sequence seqID.

func (*PagedCache) Tracker

func (pc *PagedCache) Tracker() *cuda.Tracker

Tracker returns the memory tracker associated with this cache, or nil.

func (*PagedCache) ValidateSequence

func (pc *PagedCache) ValidateSequence(binding ResidencyBinding) error

ValidateSequence refuses stale, suspended or incompletely restored bindings.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	pc, _ := nnkv.NewTestPagedCache(1, 1, 2, 2, 2)
	defer pc.Close()
	pc.AllocSequence(7, 2)
	generation, _ := pc.AllocationGeneration(7)
	binding := nnkv.ResidencyBinding{SequenceID: 7, Generation: generation, Blocks: pc.BlockTable(7), Tokens: 2}
	fmt.Println(pc.ValidateSequence(binding))
	pc.FreeSequence(7)
	fmt.Println(pc.ValidateSequence(binding) != nil)
}
Output:
<nil>
true

func (*PagedCache) VirtualPageTable

func (pc *PagedCache) VirtualPageTable(seqID int64) VirtualPageTable

VirtualPageTable returns the virtual-to-physical block table for seqID.

func (*PagedCache) VirtualPageTables

func (pc *PagedCache) VirtualPageTables() []VirtualPageTable

VirtualPageTables returns virtual page tables for all sequences.

func (*PagedCache) WriteToken

func (pc *PagedCache) WriteToken(seqID int64, tokenIdx int, layer int, k, v []float32) error

WriteToken stores K and V activations for tokenIdx of seqID in layer. This is used for host-backed testing or CPU verification.

type PredictedReturnOrder

type PredictedReturnOrder struct {
	Table ReturnTable
}

PredictedReturnOrder is BranchLRUOrder with the referenced blocks ordered by the predicted time until their branch returns: among blocks with Refs > 0, the block with the larger expected remaining idle time Table.Remaining(Idle) goes first, and LastUsed breaks ties. A zero Table means DefaultReturnTable.

It is the predicted_return_fixed order of EvolvingInfra's unified_tree_core.py (_retention_eviction_key at 503650d, lines 1175-1211), without its soft pin for branches with a request in flight and its host-duplicate level, which have no counterpart in this cache.

Example
package main

import (
	"fmt"
	"time"

	cudakv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	o := cudakv.PredictedReturnOrder{} // the default return table
	idle5 := cudakv.BlockState{LastUsed: 2, Refs: 1, Idle: 5 * time.Second}
	idle30 := cudakv.BlockState{LastUsed: 1, Refs: 1, Idle: 30 * time.Second}
	idle200 := cudakv.BlockState{LastUsed: 3, Refs: 1, Idle: 200 * time.Second}
	fmt.Println(o.Before(idle30, idle5))   // returns later, goes first
	fmt.Println(o.Before(idle200, idle30)) // past 150 s: taken as finished
}
Output:
true
true

func (PredictedReturnOrder) Before

func (o PredictedReturnOrder) Before(a, b BlockState) bool

type PrefillChunk

type PrefillChunk struct {
	SeqID    string
	Tokens   []int32
	StartPos int
	IsLast   bool
}

PrefillChunk describes prompt tokens consumed by one forward pass. Scheduling and completion belong to cudabatch.BatchScheduler.

type PrefixBlockCache

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

PrefixBlockCache is a concurrency-safe, content-addressed cache of fixed-size token blocks backed by a bounded pool of physical block slots [0, capacity). It evicts in LRU order unless SetEvictionOrder selects another order. PrefixBlockCache.AttachBranch and PrefixBlockCache.EndBranch keep per-block counts of the live branches that reference each block, which branch-aware orders read.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	cache, err := nnkv.NewPrefixBlockCache(nnkv.DefaultPrefixBlockSize, 16)
	if err != nil {
		fmt.Println(err)
		return
	}
	prompt := make([]int32, 160)
	for i := range prompt {
		prompt[i] = int32(100 + i)
	}
	// Cache the 128-token (8-block) shared system prefix.
	writes := cache.StoreBlocks(prompt[:128], 128)
	match := cache.MatchPrompt(prompt)
	fmt.Printf("writes=%d matched=%d suffix=%d rate=%.2f\n",
		len(writes), match.CachedTokens, len(prompt)-match.SuffixStart, cache.HitRate())
}
Output:
writes=8 matched=128 suffix=32 rate=0.80

func NewPrefixBlockCache

func NewPrefixBlockCache(blockSize, capacity int) (*PrefixBlockCache, error)

NewPrefixBlockCache constructs a content-addressed LRU block cache with the given token blockSize and pool slot capacity.

func (*PrefixBlockCache) ActiveRefs

func (c *PrefixBlockCache) ActiveRefs(poolSlot int) int

ActiveRefs returns the number of active zero-copy readers pinning poolSlot.

func (*PrefixBlockCache) AttachBranch

func (c *PrefixBlockCache) AttachBranch(b Branch, tokens []int32) error

AttachBranch records that branch b's context is tokens and adjusts the per-block count of live branches referencing each block:

  • A new ID counts every complete block of tokens. A fork that reuses its parent's prefix adds one to each shared block.
  • The same ID and version extending its earlier context counts only the newly appended blocks. A context that does not extend the earlier one changes nothing: only a new version may shrink or rewrite a branch.
  • A newer version (a compaction) releases the blocks it dropped and counts the blocks it added; blocks in both keep their count.
  • An older version returns ErrStaleBranch and changes nothing.

Counts are kept by block hash, so a block counts whether or not it is resident, and a block stored later starts with its count. Call AttachBranch before MatchPrompt and StoreBlocks for the request.

This follows the anchor-path counts of EvolvingInfra's session_ref_tracker.py (KvSessionRetention.admit, _replace_anchor and _advance_anchor at 503650d, lines 602-668, 472-502 and 738-753).

Example

A paused branch keeps its prefix under BranchLRUOrder while a finished branch's newer blocks are evicted.

package main

import (
	"fmt"

	cudakv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func seq(n int, base int32) []int32 {
	out := make([]int32, n)
	for i := range out {
		out[i] = base + int32(i)
	}
	return out
}

func main() {
	const bs = cudakv.DefaultPrefixBlockSize
	c, err := cudakv.NewPrefixBlockCache(bs, 4)
	if err != nil {
		panic(err)
	}
	c.SetEvictionOrder(cudakv.BranchLRUOrder{})

	paused := seq(2*bs+1, 100)
	c.AttachBranch(cudakv.Branch{ID: "agent-1"}, paused)
	c.StoreBlocks(paused, len(paused))

	done := seq(2*bs+1, 900)
	c.AttachBranch(cudakv.Branch{ID: "agent-2"}, done)
	c.StoreBlocks(done, len(done))
	c.EndBranch("agent-2")

	c.StoreBlocks(seq(2*bs, 5000), 2*bs) // needs two slots
	fmt.Println(c.MatchPrompt(paused).CachedTokens)
}
Output:
32

func (*PrefixBlockCache) BlockSize

func (c *PrefixBlockCache) BlockSize() int

BlockSize returns the number of tokens per cached block.

func (*PrefixBlockCache) BranchRefs

func (c *PrefixBlockCache) BranchRefs(hash uint64) int

BranchRefs returns the number of live branches whose context contains the block with the given cumulative hash.

func (*PrefixBlockCache) Capacity

func (c *PrefixBlockCache) Capacity() int

Capacity returns the total number of pool slots managed by the cache.

func (*PrefixBlockCache) EndBranch

func (c *PrefixBlockCache) EndBranch(id string)

EndBranch releases every count held by the branch with the given id. A later AttachBranch with the same id starts a new branch.

func (*PrefixBlockCache) Entries

func (c *PrefixBlockCache) Entries() int

Entries returns the number of valid blocks currently resident in the cache.

func (*PrefixBlockCache) HitRate

func (c *PrefixBlockCache) HitRate() float64

HitRate returns HitsTokens / TotalTokens, or 0 when TotalTokens is 0.

func (*PrefixBlockCache) HitsTokens

func (c *PrefixBlockCache) HitsTokens() uint64

HitsTokens returns the total number of prompt tokens served from the prefix cache across observed prompts.

func (*PrefixBlockCache) LookupBlock

func (c *PrefixBlockCache) LookupBlock(hash uint64) (int, bool)

LookupBlock returns the pool slot index currently holding cumulative hash, if present and valid.

func (*PrefixBlockCache) MatchAndPinPrompt

func (c *PrefixBlockCache) MatchAndPinPrompt(tokens []int32) PrefixBlockMatch

MatchAndPinPrompt behaves like MatchPrompt and atomically increments the active reference count of every matched physical pool slot under the cache lock, preventing LRU eviction or overwrite until the caller calls UnpinSlots.

func (*PrefixBlockCache) MatchPrompt

func (c *PrefixBlockCache) MatchPrompt(tokens []int32) PrefixBlockMatch

MatchPrompt looks up the longest prefix of complete blocks 0..B-1 such that B*BlockSize() < len(tokens). Each block must match both its cumulative 64-bit hash H_b and its exact token slice; a mismatch or corruption at block k stops matching at k while preserving blocks < k.

func (*PrefixBlockCache) ObservePrompt

func (c *PrefixBlockCache) ObservePrompt(tokens []int32, enabled bool) PrefixBlockMatch

ObservePrompt records len(tokens) in TotalTokens and, when enabled is true, matches the longest cached complete-block prefix satisfying CachedTokens < len(tokens).

func (*PrefixBlockCache) PinnedSlots

func (c *PrefixBlockCache) PinnedSlots() int

PinnedSlots returns the number of physical pool slots currently pinned by at least one active zero-copy reader.

func (*PrefixBlockCache) PromptCounts

func (c *PrefixBlockCache) PromptCounts() (hits, misses uint64)

PromptCounts returns the number of prompts with at least one cached block hit and the number of prompts with zero cached block hits.

func (*PrefixBlockCache) Reset

func (c *PrefixBlockCache) Reset()

Reset clears all cached blocks, branches and branch counts, and resets hit/total counters to zero. The eviction order and clock are kept.

func (*PrefixBlockCache) SetClock

func (c *PrefixBlockCache) SetClock(now func() time.Time)

SetClock sets the clock that times block accesses, from which the cache computes each block's BlockState Idle. Without a clock every Idle is zero. Set it before the first access.

func (*PrefixBlockCache) SetEvictionOrder

func (c *PrefixBlockCache) SetEvictionOrder(o EvictionOrder)

SetEvictionOrder sets the order in which the cache evicts resident blocks. A nil order restores the default, LRU.

func (*PrefixBlockCache) StoreBlocks

func (c *PrefixBlockCache) StoreBlocks(tokens []int32, upToTokens int) []PrefixBlockWrite

StoreBlocks inserts complete blocks from tokens[0 : upToTokens] into the cache and returns the newly assigned pool slots that the caller must populate from the sequence's KV cache. Blocks already resident with matching parent hash and tokens have their LRU timestamp refreshed and are not returned in the write list.

func (*PrefixBlockCache) TotalTokens

func (c *PrefixBlockCache) TotalTokens() uint64

TotalTokens returns the total number of prompt tokens across all prompts observed by the cache.

func (*PrefixBlockCache) UnpinSlots

func (c *PrefixBlockCache) UnpinSlots(poolSlots []int)

UnpinSlots decrements the active zero-copy reader reference count for each physical pool slot in poolSlots. When a slot's reference count reaches zero, its cached entry remains resident for future hits and becomes eligible for LRU eviction under memory pressure.

type PrefixBlockMatch

type PrefixBlockMatch struct {
	Blocks       []int
	Hashes       []uint64
	CachedTokens int
	SuffixStart  int
}

PrefixBlockMatch describes the longest complete-block prefix of a prompt that matched in a PrefixBlockCache while leaving at least one suffix token uncached to produce next-token logits.

type PrefixBlockWrite

type PrefixBlockWrite struct {
	BlockIndex int
	PoolSlot   int
	Hash       uint64
}

PrefixBlockWrite identifies a newly cached complete token block that the caller must copy from the sequence's KV cache slot into PoolSlot.

type RadixNode

type RadixNode struct {
	Tokens []int32
	Blocks []int

	// Children are keyed by the first block of the child's segment, so two
	// sequences that agree on a whole block share a node and diverge at a
	// block boundary. Keying by a single token could not distinguish two
	// blocks that begin with the same token.
	Children map[string]*RadixNode
	Parent   *RadixNode
	// contains filtered or unexported fields
}

RadixNode is one segment of a cached token sequence.

Tokens holds the segment; Blocks holds the cache blocks covering it, one per TokensPerBlock tokens. A node's segment is always a whole number of blocks, so a match never ends in the middle of a block that only partly matches.

type RadixTree

type RadixTree struct {
	Root *RadixNode

	// NodeMap indexes nodes by the blocks they hold, so a caller that knows
	// a block id can find what is cached in it.
	NodeMap map[int]*RadixNode

	// TokensPerBlock is how many tokens one cache block covers. Matches are
	// reported in whole blocks: a caller reuses blocks, so a match of half a
	// block would name tokens it cannot in fact reuse.
	TokensPerBlock int
	// contains filtered or unexported fields
}

RadixTree is a prefix cache: it maps token sequences to the cache blocks holding their computed keys and values, so a request sharing a prefix with an earlier one reuses those blocks instead of recomputing them.

The tree is a radix tree over blocks of tokens. Inserting a sequence that shares a prefix with a stored one splits the stored node at the divergence point, so the shared prefix is stored once however many sequences pass through it.

func NewRadixTree

func NewRadixTree(maxNodes, tokensPerBlock int) *RadixTree

NewRadixTree creates an empty prefix cache holding at most maxNodes segments, each block covering tokensPerBlock tokens.

Inserting into a full tree evicts the least recently matched unpinned leaves.

func (*RadixTree) Acquire

func (r *RadixTree) Acquire(tokens []int32) (int, []int, *RadixNode)

Acquire matches tokens and pins the matched path, so the blocks it returns are not evicted until the returned node is released. It returns a nil node when nothing matched, which needs no release.

func (*RadixTree) Evict

func (r *RadixTree) Evict(n int) []int

Evict removes up to n least recently matched segments and returns the blocks they held, for the caller to hand back to its allocator.

Only leaves are evicted, and only unpinned ones, so a segment is never dropped while a sequence below it is still cached or in use. Evict returns fewer blocks than asked, possibly none, when everything left is pinned or has cached continuations.

func (*RadixTree) Insert

func (r *RadixTree) Insert(tokens []int32, blocks []int) (taken, evicted []int, err error)

Insert stores tokens and the blocks holding them, sharing the parts already stored. It returns the blocks the tree took, which the caller must keep alive until the tree hands them back, for instance with PagedCache.Retain, and the blocks the tree gave up to make room, which the caller now owns again as it would after Evict.

len(tokens) must be a whole number of blocks and blocks must hold one entry per block of tokens. Where a prefix is already stored the tree keeps its own blocks and takes none of the caller's for that part, so the caller's blocks there are redundant and stay the caller's to free. Inserting a sequence already stored in full refreshes it and takes nothing.

func (*RadixTree) Len

func (r *RadixTree) Len() int

Len returns the number of stored segments.

func (*RadixTree) MatchPrefix

func (r *RadixTree) MatchPrefix(tokens []int32) (int, []int, *RadixNode)

MatchPrefix returns the longest stored prefix of tokens.

The result is the number of tokens matched, the blocks holding them in order, and the node the match ended at. The match is a whole number of blocks and stops at the first block that is not stored, so a caller can reuse exactly the blocks returned and must compute the rest.

Example

A RadixTree reports how much of a request's prefix is already cached, in whole blocks, so the caller recomputes only the divergent suffix.

package main

import (
	"fmt"
	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	tree := nnkv.NewRadixTree(64, 4)
	stored := []int32{1, 2, 3, 4, 5, 6, 7, 8}
	if _, _, err := tree.Insert(stored, []int{10, 11}); err != nil {
		fmt.Println(err)
		return
	}
	query := []int32{1, 2, 3, 4, 9, 9, 9, 9}
	n, blocks, _ := tree.MatchPrefix(query)
	fmt.Println(n, blocks)
}
Output:
4 [10]

func (*RadixTree) Release

func (r *RadixTree) Release(node *RadixNode)

Release undoes one Acquire. Releasing a nil node does nothing.

func (*RadixTree) RemapBlocks

func (r *RadixTree) RemapBlocks(remappings map[int]int)

RemapBlocks updates physical block IDs stored in the tree according to remappings. The update is applied atomically under the tree's mutex.

type Region

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

A Region is the metadata of one arena, operated on with the device algorithm: every access to a shared word is atomic, as on the device, so any number of goroutines may call its methods at once, subject to the rules a step imposes on device threads. One goroutine at a time drives a given sequence, and EndStep runs alone, between steps.

func NewRegion

func NewRegion(c Config) (*Region, error)

NewRegion returns a region for c in its initial state.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	c := nnkv.Config{Pages: 8, PageTokens: 16, MaxSeqs: 4, MaxSeqPages: 4, JournalLen: 64}
	r, err := nnkv.NewRegion(c)
	if err != nil {
		panic(err)
	}
	prompt := make([]uint32, 40)
	for i := range prompt {
		prompt[i] = uint32(i)
	}
	r.Admit(0)
	for _, tok := range prompt[:20] { // two pages; the first is full
		r.Append(0, tok)
	}
	r.Admit(1)
	n, _ := r.Lookup(1, prompt) // finds the full page
	r.Finish(0)
	r.EndStep()

	s, err := nnkv.Decode(c, r.Words())
	if err != nil {
		panic(err)
	}
	fmt.Println("pages found:", n)
	fmt.Println("free pages:", s.FreeCount)
	fmt.Println("check:", s.Check())
}
Output:
pages found: 1
free pages: 7
check: <nil>

func (*Region) Admit

func (r *Region) Admit(seq int) error

Admit starts sequence seq with no tokens. The handle must be free or retired.

func (*Region) Append

func (r *Region) Append(seq int, tok uint32) error

Append appends token tok to seq. When the token starts a page it first enters the previous page, now full, in the hash table, and takes a fresh page, evicting a cached one if none is free.

On the device, a page's KV is written in the step that appends its tokens, and the next page boundary comes in a later step, after the writes are fenced (lane 100 §4.3, item 4). So entering the previous page in the hash table here never publishes a page whose KV is unwritten.

func (*Region) Config

func (r *Region) Config() Config

Config returns the region's configuration.

func (*Region) EndStep

func (r *Region) EndStep() error

EndStep returns the pages in limbo to the bitmap and starts the next step. It must run alone: on the device, one thread runs it between two grid barriers.

func (*Region) Finish

func (r *Region) Finish(seq int) error

Finish enters seq's last page in the hash table if it is full, drops every page seq holds, and retires it. A hashed page whose last reference it drops is cached; any other goes to limbo until the step ends.

func (*Region) Lookup

func (r *Region) Lookup(seq int, toks []uint32) (int, error)

Lookup gives seq, a sequence with no tokens yet, the hashed pages that hold the longest prefix of toks made of whole pages, leaving at least one token of toks to compute, and reports how many pages it took; seq then has that many pages of tokens. Each page is matched by its key: the previous page's entry and the page's tokens.

func (*Region) Table

func (r *Region) Table(seq int) ([]Entry, error)

Table returns seq's page-table entries for the pages its tokens cover.

func (*Region) Words

func (r *Region) Words() []uint64

Words returns the region's metadata words. They are the region's own storage; read them only while no method is running.

type Residency

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

Residency owns asynchronous HBM/pinned-host transitions for one complete sequence and every layer in its pages. Create it with NewResidency; its zero value is not usable. Shared-prefix eviction and partial-layer/page plans are unsupported. Callers must quiesce existing kernel/page use before Evict and serialize any future page access through the returned resident binding. Previously obtained raw Page aliases cannot be revoked by this API.

Successful eviction returns physical pool slots for reuse, not the reserved whole-layer CUDA allocation. Pinned host memory and device allocation borrows remain owned until Close succeeds. Failed waits/closes retain retry owners. Close abandons a nonresident sequence; it does not invent a usable binding.

func NewResidency

func NewResidency(pc *PagedCache, sequence int64, generation uint64) (*Residency, error)

NewResidency binds the exact currently resident allocation generation of sequence. It does not enqueue work or allocate pinned storage. A non-nil error-result owner, if any, must be closed. The caller supplies transfer streams to Evict and Prefetch; no stream is constructed or owned here.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	// Residency needs actual owned CUDA Page storage. A host-test cache cannot
	// silently stand in for pinned transfers; this refusal calls no vendor API.
	pc, _ := nnkv.NewTestPagedCache(1, 1, 2, 2, 2)
	defer pc.Close()
	pc.AllocSequence(7, 2)
	generation, _ := pc.AllocationGeneration(7)
	owner, err := nnkv.NewResidency(pc, 7, generation)
	fmt.Println(owner == nil, err != nil)
}
Output:
true true

func (*Residency) Binding

func (r *Residency) Binding() (ResidencyBinding, error)

Binding returns a detached currently usable whole-sequence binding.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	var owner *nnkv.Residency
	_, err := owner.Binding()
	fmt.Println(err != nil)
}
Output:
true

func (*Residency) Close

func (r *Residency) Close() error

Close waits for pending transfers and releases pinned buffers and device borrows. Failed completion/free cleanup retains the owner for retry. Closing a completed host-resident sequence abandons its suspended allocation. A successful resident HBM sequence stays allocated for its caller.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	var owner *nnkv.Residency
	fmt.Println(owner.Close())
}
Output:
<nil>

func (*Residency) Evict

func (r *Residency) Evict(stream *cuda.Stream) error

Evict starts D2H copies of every selected page/layer. Until Wait succeeds the sequence is suspended and the original slots remain held. Host allocation exhaustion leaves the HBM binding valid; the caller can continue there.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	var owner *nnkv.Residency
	fmt.Println(owner.Evict(nil) != nil)
}
Output:
true

func (*Residency) Prefetch

func (r *Residency) Prefetch(stream *cuda.Stream) error

Prefetch reserves new pool slots and starts H2D copies. Slots and a new allocation generation become a usable binding only after successful Wait. Exhaustion leaves the pinned-host copy owned and the sequence suspended.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	var owner *nnkv.Residency
	fmt.Println(owner.Prefetch(nil) != nil)
}
Output:
true

func (*Residency) Tier

func (r *Residency) Tier() ResidencyTier

Tier reports placement. Only ResidencyHBM permits Binding to succeed.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	var owner *nnkv.Residency
	fmt.Println(owner.Tier())
}
Output:
closed

func (*Residency) Wait

func (r *Residency) Wait(ctx context.Context) error

Wait establishes actual transfer completion. Cancellation only stops waiting; it does not cancel CUDA work, free owners or publish residency. Event cleanup and native wait failures keep the completion owner for a later retry.

Example
package main

import (
	"context"
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	var owner *nnkv.Residency
	fmt.Println(owner.Wait(context.Background()) != nil)
}
Output:
true

type ResidencyBinding

type ResidencyBinding struct {
	SequenceID int64
	Generation uint64
	Blocks     []int
	Tokens     int
}

ResidencyBinding is a detached whole-sequence binding for ValidateSequence. Generation changes on restore, including when the same physical slots return.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	binding := nnkv.ResidencyBinding{SequenceID: 7, Generation: 3, Blocks: []int{2, 1}, Tokens: 4}
	fmt.Println(binding.SequenceID, binding.Generation, binding.Blocks)
}
Output:
7 3 [2 1]

type ResidencyTier

type ResidencyTier string

ResidencyTier records completed placement or an outstanding transfer. A pending prediction/copy is never a usable resident sequence binding.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	fmt.Println(nnkv.ResidencyEvicting, nnkv.ResidencyHost)
}
Output:
evicting pinned_host
const (
	ResidencyHBM         ResidencyTier = "hbm"
	ResidencyEvicting    ResidencyTier = "evicting"
	ResidencyHost        ResidencyTier = "pinned_host"
	ResidencyPrefetching ResidencyTier = "prefetching"
	ResidencyLost        ResidencyTier = "lost"
	ResidencyClosed      ResidencyTier = "closed"
)

type ReturnTable

type ReturnTable struct {
	// Remaining returns m(tau) = E[G - tau | G > tau] in seconds: the
	// expected remaining idle time of a block idle for tau, where G is the
	// gap before its branch returns. +Inf means the branch is taken as
	// finished.
	Remaining func(idle time.Duration) float64
}

A ReturnTable predicts how long an idle branch stays away.

func DefaultReturnTable

func DefaultReturnTable() ReturnTable

DefaultReturnTable returns the predicted_return_fixed table of EvolvingInfra (see defaultReturnAnchors). Its constants were fitted on a single trace; a workload with other pause lengths needs its own table.

Example
package main

import (
	"fmt"
	"time"

	cudakv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	t := cudakv.DefaultReturnTable()
	for _, s := range []int{0, 10, 30, 119, 150} {
		fmt.Println(s, t.Remaining(time.Duration(s)*time.Second))
	}
}
Output:
0 21
10 38
30 70
119 29
150 +Inf

func FixedReturnTable

func FixedReturnTable(m []float64, deadAfter time.Duration) ReturnTable

FixedReturnTable returns the table whose m for idle age tau is m[floor(tau / 1s)], with ages past the last bin using the last bin. A positive deadAfter makes every age at or past it +Inf. This is FixedReturnTable.m_of_age of retention_order.py, lines 120-124.

type RollingKVCache

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

RollingKVCache tracks residency and slot indices for an attention sink and rolling window. It does not allocate or move K/V tensors. Callers own storage and must coordinate writes, reads, and Advance with device execution.

Example
package main

import (
	"fmt"
	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	cache, err := nnkv.NewRollingKVCache(nnkv.SlidingWindowConfig{
		SinkTokens: 1,
		WindowSize: 2,
	})
	if err != nil {
		panic(err)
	}
	// This example tracks positions only; tensor storage is caller-owned.
	if err := cache.Advance(4); err != nil {
		panic(err)
	}
	fmt.Println(cache.Slot(0)) // The sink token stays resident.
	fmt.Println(cache.Slot(1)) // The rolling window has overwritten token 1.
	fmt.Println(cache.Slot(3))
}
Output:
0 true
-1 false
1 true

func NewRollingKVCache

func NewRollingKVCache(cfg SlidingWindowConfig) (*RollingKVCache, error)

NewRollingKVCache creates a sliding window KV cache preserving sink tokens and rolling window.

func (*RollingKVCache) ActiveTokens

func (c *RollingKVCache) ActiveTokens() int

ActiveTokens returns the total number of currently active tokens.

func (*RollingKVCache) Advance

func (c *RollingKVCache) Advance(n int) error

Advance records that n new tokens have been written into the rolling cache.

func (*RollingKVCache) PhysicalSlot

func (c *RollingKVCache) PhysicalSlot(logicalPos int) int

PhysicalSlot maps a logical sequence position to its physical buffer slot in the ring buffer. It returns -1 for a negative position.

The mapping is many-to-one: every windowSize positions share a slot, so a slot holds the requested position only while that position is resident. Use Slot to get the mapping and that check together.

func (*RollingKVCache) Resident

func (c *RollingKVCache) Resident(logicalPos int) bool

Resident reports whether logicalPos is still addressable. A position is resident if it has been written, and either lies in the sink or has not yet been lapped by the rolling window.

func (*RollingKVCache) Slot

func (c *RollingKVCache) Slot(logicalPos int) (slot int, ok bool)

Slot returns the physical slot holding logicalPos, and whether that slot still holds it. Callers must not read the slot when ok is false: the ring has reused it for a later position.

func (*RollingKVCache) TotalSeen

func (c *RollingKVCache) TotalSeen() int

TotalSeen returns the total number of tokens processed across the stream.

func (*RollingKVCache) WindowStart

func (c *RollingKVCache) WindowStart() int

WindowStart returns the oldest logical position still held in the rolling window. Positions below it have been overwritten, except for the sink.

type SSDOffloader

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

SSDOffloader provides secondary SSD storage offloading for NVIDIA CUDA KV buffers.

func NewSSDOffloader

func NewSSDOffloader(dir string) (*SSDOffloader, error)

NewSSDOffloader creates a new SSDOffloader rooted at dir. Instances may share a directory; each owns distinct spill files. Spills are process-local scratch storage, not crash-durable checkpoints.

func (*SSDOffloader) Close

func (o *SSDOffloader) Close() error

Close removes the layer files the offloader spilled and forgets them. Failed removals remain owned so a later Close can retry them. The offloader can be reused after Close.

func (*SSDOffloader) EvictLayer

func (o *SSDOffloader) EvictLayer(ctx context.Context, layer LayerCache) error

EvictLayer writes a layer's K and V buffers from host/device memory to SSD storage.

func (*SSDOffloader) RestoreLayer

func (o *SSDOffloader) RestoreLayer(ctx context.Context, layer LayerCache) error

RestoreLayer restores K and V buffers from SSD back into GPU memory.

type SWAReplayConfig

type SWAReplayConfig struct {
	WindowSize           int
	SpeculativeOvershoot int
	PageBlockSize        int
}

SWAReplayConfig configures constant-window SWA bounded replay.

type SWAReplayWindow

type SWAReplayWindow struct {
	StartPos      int
	EndPos        int
	ActiveTokens  int
	RequiredPages int
	RingSlots     []int
}

SWAReplayWindow describes the bounded active token range and circular ring buffer slots for SWA replay.

func ResolveSWABoundedReplay

func ResolveSWABoundedReplay(seqLenK int, queryLen int, cfg SWAReplayConfig) (SWAReplayWindow, error)

ResolveSWABoundedReplay computes the bounded rolling window [max(0, seqLenK - (WindowSize + SpeculativeOvershoot)), seqLenK) for SWA layers and maps logical positions to bounded circular ring buffer slots (pos % ringCapacity).

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	win, err := nnkv.ResolveSWABoundedReplay(300, 1, nnkv.SWAReplayConfig{
		WindowSize:           128,
		SpeculativeOvershoot: 6,
		PageBlockSize:        64,
	})
	if err != nil {
		panic(err)
	}
	fmt.Printf("start=%d end=%d active=%d pages=%d firstSlot=%d lastSlot=%d\n",
		win.StartPos, win.EndPos, win.ActiveTokens, win.RequiredPages,
		win.RingSlots[0], win.RingSlots[len(win.RingSlots)-1])
}
Output:
start=166 end=300 active=134 pages=3 firstSlot=32 lastSlot=31

type SeqState

type SeqState uint8

SeqState is the state of a sequence descriptor.

const (
	SeqFree    SeqState = iota // unused handle
	SeqActive                  // admitted, holding pages
	SeqRetired                 // finished; its pages are dropped and the handle may be reused
)

func (SeqState) String

func (s SeqState) String() string

type SeqWord

type SeqWord uint64

SeqWord is a sequence descriptor: state in bits 0-7, token length in bits 32-63.

func (SeqWord) Len

func (w SeqWord) Len() uint32

func (SeqWord) State

func (w SeqWord) State() SeqState

type SharedLayerSpec

type SharedLayerSpec struct {
	LayerID       int
	SourceLayerID int
	Role          LayerKVRole
	IsSWA         bool
	WindowSize    int
}

SharedLayerSpec describes the KV cache sharing role of a single transformer layer.

type SharedLayerTopology

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

SharedLayerTopology maps a multi-layer decoder stack to compressed physical KV cache pools.

func NewSharedLayerTopology

func NewSharedLayerTopology(specs []SharedLayerSpec) (*SharedLayerTopology, error)

NewSharedLayerTopology validates and constructs a SharedLayerTopology from per-layer specs.

Example
package main

import (
	"fmt"

	nnkv "github.com/tmc/lib/nvidia/x/nn/kv"
)

func main() {
	specs := []nnkv.SharedLayerSpec{
		{LayerID: 0, SourceLayerID: 0, Role: nnkv.LayerKVProducer, IsSWA: true, WindowSize: 128},
		{LayerID: 1, SourceLayerID: 1, Role: nnkv.LayerKVProducer, IsSWA: true, WindowSize: 128},
		{LayerID: 2, SourceLayerID: 1, Role: nnkv.LayerKVSharedConsumer, IsSWA: true, WindowSize: 128},
		{LayerID: 3, SourceLayerID: 1, Role: nnkv.LayerKVSharedConsumer, IsSWA: true, WindowSize: 128},
	}
	topo, err := nnkv.NewSharedLayerTopology(specs)
	if err != nil {
		panic(err)
	}
	slot3, err := topo.PhysicalSlotForLayer(3)
	if err != nil {
		panic(err)
	}
	fmt.Printf("producers=%v slot3=%d savings=%.2f\n", topo.ProducerLayers(), slot3, topo.MemorySavingsRatio())
}
Output:
producers=[0 1] slot3=1 savings=0.50

func (*SharedLayerTopology) CompactPrefillRange

func (t *SharedLayerTopology) CompactPrefillRange(layerID, totalTokens, windowTokens int) (start, end int)

CompactPrefillRange returns the [start, end) token range required by layerID during prefill when SWA window compaction is active.

func (*SharedLayerTopology) IsConsumer

func (t *SharedLayerTopology) IsConsumer(layerID int) bool

IsConsumer reports whether layerID is a shared KV cache consumer layer.

func (*SharedLayerTopology) MemorySavingsRatio

func (t *SharedLayerTopology) MemorySavingsRatio() float64

MemorySavingsRatio returns the fraction of KV cache layers saved by cross-layer sharing (1 - producers/total).

func (*SharedLayerTopology) NumLayers

func (t *SharedLayerTopology) NumLayers() int

NumLayers returns the total number of layers in the topology.

func (*SharedLayerTopology) PhysicalSlotForLayer

func (t *SharedLayerTopology) PhysicalSlotForLayer(layerID int) (int, error)

PhysicalSlotForLayer returns the compressed physical KV pool slot index [0..len(ProducerLayers)-1] for layerID.

func (*SharedLayerTopology) ProducerLayers

func (t *SharedLayerTopology) ProducerLayers() []int

ProducerLayers returns the ordered slice of producer layer IDs.

func (*SharedLayerTopology) SharedHiddenRequired

func (t *SharedLayerTopology) SharedHiddenRequired(layerID int) bool

SharedHiddenRequired reports whether layerID is a producer layer whose KV representation is consumed by at least one downstream consumer layer.

func (*SharedLayerTopology) SpecForLayer

func (t *SharedLayerTopology) SpecForLayer(layerID int) (SharedLayerSpec, error)

SpecForLayer returns the SharedLayerSpec for layerID.

type SlidingWindowCache

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

SlidingWindowCache manages a fixed-size rotating buffer for sliding window attention.

func NewSlidingWindowCache

func NewSlidingWindowCache(numLayers, numKVHeads, headDim, windowSize int) (*SlidingWindowCache, error)

NewSlidingWindowCache creates a cache manager for windowSize context tokens.

func (*SlidingWindowCache) Advance

func (swc *SlidingWindowCache) Advance(n int)

Advance advances the current logical token position by n.

func (*SlidingWindowCache) ContextBounds

func (swc *SlidingWindowCache) ContextBounds(pos int) (start, end int)

ContextBounds returns the start and end logical token indices visible to attention at position pos.

func (*SlidingWindowCache) SlotForPosition

func (swc *SlidingWindowCache) SlotForPosition(pos int) int

SlotForPosition returns the physical circular buffer index for logical position pos.

type SlidingWindowConfig

type SlidingWindowConfig struct {
	SinkTokens int // Number of initial tokens preserved indefinitely (typically 4)
	WindowSize int // Number of rolling window tokens preserved (e.g. 4096)
}

SlidingWindowConfig configures an attention sink and rolling window KV buffer.

type Snapshot

type Snapshot struct {
	Config    Config
	FreeCount int64
	Step      uint64
	Cause     uint64
	Counters  Counters
	Bitmap    []uint64
	Clock     []uint64 // CLOCK reference bits
	Pages     []PageWord
	Keys      []PageKey
	Hash      []uint64 // slots: an Entry, EmptyEntry, or a removed entry's tombstone
	Limbo     []uint32
	Seqs      []SeqWord
	Tables    [][]Entry // MaxSeqs tables of MaxSeqPages entries
	Journal   []Event   // the retained events, oldest first
	Dropped   uint64    // events overwritten before the snapshot
}

A Snapshot is metadata decoded from its words, taken while no thread was operating on it.

func Decode

func Decode(c Config, w []uint64) (*Snapshot, error)

Decode decodes metadata words laid out for c.

func (*Snapshot) Check

func (s *Snapshot) Check() error

Check verifies the invariants that hold whenever no thread is operating on the metadata:

  • no cause code is recorded;
  • every free page is in the bitmap or in limbo, once, and no other page is in either (I1), and the free count equals the bitmap's population;
  • an owned or shared page's reference count equals the number of active sequences whose table names it at its current generation, an owned page has one, and every active table entry names such a page (I2, I5);
  • a cached page is named by no table;
  • every hash entry names a shared or cached page at its generation and lies on the probe path of that page's key, and every shared or cached page has exactly one entry (I3);
  • an active sequence's table covers exactly its tokens, and every other sequence's table is empty.

func (*Snapshot) Drained

func (s *Snapshot) Drained() error

Drained reports whether s is the state after every sequence has finished and the step has ended: every page free and in the bitmap, or cached, with no references (I8). It assumes Check passes.

type VirtualPageTable

type VirtualPageTable struct {
	SeqID  int64
	Blocks []int
}

VirtualPageTable represents a sequence's virtual-to-physical block table.

type YOCOTopology

type YOCOTopology = SharedLayerTopology

YOCOTopology is an alias for SharedLayerTopology.

type YoCoBoundaryIndices

type YoCoBoundaryIndices struct {
	BoundaryIndices []int32
	FullIndices     []int32
	NumTokens       int
	RecentCap       int
}

YoCoBoundaryIndices holds precomputed query-to-KV index tables for cross-layer YoCo SWA attention.

func BuildYoCoBoundary

func BuildYoCoBoundary(cuSeqlensQ []int32, seqlensK []int32, recentCap int) (YoCoBoundaryIndices, error)

BuildYoCoBoundary computes yoco_boundary_indices ([numTokens, recentCap]) and yoco_full_indices matching MLAState.prepare_aux, mapping each query token to the most recent min(seqLenQ, recentCap) KV positions for cross-layer YoCo SWA attention.

Directories

Path Synopsis
Package tier implements a three-tier asynchronous KV-cache offloader across GPU VRAM, pinned CPU RAM, and NVMe SSD storage without stalling the decode loop.
Package tier implements a three-tier asynchronous KV-cache offloader across GPU VRAM, pinned CPU RAM, and NVMe SSD storage without stalling the decode loop.

Jump to

Keyboard shortcuts

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