Documentation
¶
Overview ¶
Package ckpt provides zero-copy SafeTensors loading, typed checkpoint tensor binding, NVIDIA ModelOpt quantized weight metadata decoding, multi-rank loading strategy chains with mutation-aware rollback, speculative draft publication gating, role-scoped shard selection, and cold-load quantization scale validation.
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 (
"log"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/host/safetensors"
nnckpt "github.com/tmc/lib/nvidia/x/nn/ckpt"
)
func main() {
f, err := safetensors.OpenSharded("/path/to/checkpoint")
if err != nil {
log.Fatal(err)
}
defer f.Close()
dev, err := cuda.NewDevice(0)
if err != nil {
log.Fatal(err)
}
defer dev.Close()
w, err := nnckpt.LoadSlice[uint16](f, "model.embed_tokens.weight", dev)
if err != nil {
log.Fatal(err)
}
defer w.Close()
}
Output:
Index ¶
- Constants
- Variables
- func DraftNamespace(identityHash, draftClass, version, uri string) (string, error)
- func IsDraftTensor(name string) bool
- func LoadSlice[T any](r TensorReader, name string, dev *cuda.Device) (cuda.Slice[T], error)
- func LookupStrategy(name string) (func() Strategy, bool)
- func RegisterStrategy(name string, factory func() Strategy) error
- func RegisteredStrategies() []string
- func SelectShards(r io.Reader, available []string, role string, rule WeightRule) ([]string, error)
- func ValidateScales(specs []ScaleSpec) (map[string]float32, error)
- type Chain
- type DraftGate
- type Entry
- type Error
- type Ignore
- type NVFP4Linear
- type PairAccumulator
- type QuantConfig
- type RankGatherer
- type Receipt
- type ScaleSpec
- type Slot
- type State
- type Strategy
- type StrategyError
- type Target
- type Tensor
- type TensorReader
- type Tensors
- type WeightRule
Examples ¶
Constants ¶
const DraftPrefix = "mx_draft::"
DraftPrefix is the tensor name prefix isolating speculative draft tensors from main-model tensors in a shared manifest.
const QuantConfigFile = "hf_quant_config.json"
QuantConfigFile is the name of the file ModelOpt writes beside the shards.
Variables ¶
var ErrRecovery = errors.New("ckpt: unrecoverable strategy state")
ErrRecovery reports that a failed strategy left the target in an unrecoverable state (or ranks diverged on finalize) and the chain must stop.
Functions ¶
func DraftNamespace ¶
DraftNamespace returns a deterministic "mx_draft::<32-hex>::" prefix isolating draft tensor names from main-model tensors in a shared manifest. identityHash and draftClass must be non-empty.
func IsDraftTensor ¶
IsDraftTensor reports whether name carries DraftPrefix.
func LoadSlice ¶
LoadSlice reads the named tensor from r, allocates device memory for it on dev, and copies the tensor's bytes there unchanged. T must have the size and kind of the tensor's dtype: float32 for F32, uint16 for F16 or BF16, uint8 for U8 or the F8 types, and so on.
On error a nonzero slice must still be freed before dev is closed. It holds either a partial allocation or a buffer whose release after a failed copy also failed.
Example (Dtype) ¶
LoadSlice refuses an element type that does not hold the tensor's dtype bit for bit, before it touches the device.
package main
import (
"bytes"
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/host/safetensors"
nnckpt "github.com/tmc/lib/nvidia/x/nn/ckpt"
)
func main() {
var buf bytes.Buffer
w := safetensors.Tensor{Name: "w", Dtype: safetensors.BF16, Shape: []int{2}, Data: make([]byte, 4)}
if err := safetensors.Write(&buf, []safetensors.Tensor{w}, nil); err != nil {
log.Fatal(err)
}
f, err := safetensors.NewFile(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
if err != nil {
log.Fatal(err)
}
_, err = nnckpt.LoadSlice[float32](f, "w", nil)
fmt.Println(err)
}
Output: cudasafetensors: tensor "w" dtype BF16 is incompatible with float32 storage
func LookupStrategy ¶
LookupStrategy returns the registered factory for name, if present.
func RegisterStrategy ¶
RegisterStrategy registers a named strategy factory in the process-wide registry. Strategies produced by the registered factory are wrapped so that any panic during Prepare, Load, or Finalize is converted into a mutated *StrategyError.
func RegisteredStrategies ¶
func RegisteredStrategies() []string
RegisteredStrategies returns the sorted names of all registered strategies.
func SelectShards ¶
SelectShards filters available shard paths using the weight_map in r (formatted as safetensors.IndexFile). It returns nil, nil when the index is unreadable, malformed, incomplete, contains unsafe shard paths, has ambiguous basenames, or selects no shards, so callers retain full-shard fallback. Rule panics are not suppressed.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/nn/ckpt"
)
func main() {
idx := `{"weight_map":{"model.w":"s1.safetensors","mtp.w":"s2.safetensors"}}`
avail := []string{"/ckpt/s1.safetensors", "/ckpt/s2.safetensors"}
rule := func(name, role string) bool { return !strings.HasPrefix(name, "mtp.") }
selected, err := ckpt.SelectShards(strings.NewReader(idx), avail, "main", rule)
fmt.Println(selected, err)
}
Output: [/ckpt/s1.safetensors] <nil>
func ValidateScales ¶
ValidateScales verifies that every spec in specs has a unique non-empty Name and non-empty Values where every element is finite and strictly positive (and length 1 when Singleton is true). It returns the maximum value per scale name.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/nn/ckpt"
)
func main() {
mirrors, err := ckpt.ValidateScales([]ckpt.ScaleSpec{
{Name: "k_scale", Values: []float32{0.5, 2.0, 1.25}},
})
fmt.Println(mirrors["k_scale"], err)
}
Output: 2 <nil>
Types ¶
type Chain ¶
type Chain struct {
Strategies []Strategy
Gatherer RankGatherer // optional; nil for single-rank
}
Chain executes an ordered list of strategies with multi-rank phase agreement (eligible -> prepare -> load -> finalize) and mutation-aware rollback.
func (*Chain) Run ¶
Run executes the chain until one strategy succeeds on all ranks. It returns the winning strategy name on success.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/nn/ckpt"
)
type exampleTarget struct{ reinits int }
func (t *exampleTarget) Reinit(context.Context) error { t.reinits++; return nil }
type exampleStrategy struct {
name string
fail bool
}
func (s exampleStrategy) Name() string { return s.name }
func (s exampleStrategy) Available(context.Context) (bool, error) { return true, nil }
func (s exampleStrategy) Prepare(context.Context, ckpt.Target) error { return nil }
func (s exampleStrategy) Load(context.Context, ckpt.Target) error {
if s.fail {
return &ckpt.StrategyError{Strategy: s.name, Mutated: true, Err: errors.New("miss")}
}
return nil
}
func (s exampleStrategy) Finalize(context.Context, ckpt.Target) error { return nil }
func (s exampleStrategy) Abort(context.Context, ckpt.Target) error { return nil }
func (s exampleStrategy) Rollback(context.Context) error { return nil }
func main() {
dst := &exampleTarget{}
chain := &ckpt.Chain{
Strategies: []ckpt.Strategy{
exampleStrategy{name: "rdma", fail: true},
exampleStrategy{name: "default"},
},
}
winner, err := chain.Run(context.Background(), dst)
fmt.Println(winner, dst.reinits, err)
}
Output: default 1 <nil>
type DraftGate ¶
type DraftGate struct {
// contains filtered or unexported fields
}
DraftGate holds main-model source publication until DraftGate.Release is called or the configured grace duration elapses after DraftGate.Arm. A non-positive grace disables expiry so the gate stays closed until Release.
The zero value is not usable; construct one with NewDraftGate.
func NewDraftGate ¶
NewDraftGate returns a DraftGate that opens upon Release or once grace has elapsed after Arm. If grace <= 0, expiry is disabled. If now is nil, time.Now is used.
func (*DraftGate) Arm ¶
func (g *DraftGate) Arm()
Arm starts the grace timer if grace > 0. Calling Arm on a gate with grace <= 0 leaves expiry disabled.
type Entry ¶
type Entry struct {
// Tensor is the checkpoint's tensor. For a Missing entry only Name is set.
Tensor
State State
// Reason is the matching rule's reason for an Ignored entry and the
// slot's dtype and shape for a Missing or Mismatched one.
Reason string
}
An Entry accounts for one tensor name.
type Error ¶
type Error struct {
Problems []string
}
An Error is a refused binding. Problems holds one line per entry that is not Bound or Ignored, in name order.
type Ignore ¶
type Ignore struct {
// Pattern is a [path.Match] pattern over tensor names. Tensor names
// hold no slashes, so * matches any run of characters, dots included.
Pattern string
// Reason says why the tensors are not read. It must not be empty.
Reason string
}
An Ignore rule names checkpoint tensors that are deliberately not read.
type NVFP4Linear ¶
type NVFP4Linear struct {
// Weight holds weight (Packed), weight_scale (Scales) and
// weight_scale_2 (TensorScale).
Weight *nnquant.NVFP4Weight
// InputScale is input_scale, the static global scale of the
// activations for a kernel that also quantizes them (W4A4).
InputScale float32
}
An NVFP4Linear is a linear layer exported by ModelOpt as NVFP4.
func ReadNVFP4Linear ¶
func ReadNVFP4Linear(ts Tensors, prefix string) (*NVFP4Linear, error)
ReadNVFP4Linear reads the NVFP4 linear layer whose tensors are named prefix+".weight", prefix+".weight_scale", prefix+".weight_scale_2" and prefix+".input_scale". It checks every dtype and shape, and rejects NaN or negative block scales and tensor or input scales that are not positive and finite. K must be a multiple of 64, as nnquant.NVFP4Weight requires.
type PairAccumulator ¶
type PairAccumulator[T any] struct { // contains filtered or unexported fields }
PairAccumulator buffers out-of-order streaming tensor pairs (such as an FP8 weight and its companion weight_scale) keyed by logical tensor name so callers commit complete pairs and detect stranded halves via PairAccumulator.Pending.
func (*PairAccumulator[T]) Add ¶
func (p *PairAccumulator[T]) Add(key string, isScale bool, v T) (weight, scale T, ready bool)
Add records either the weight (isScale == false) or the scale (isScale == true) for key. When both halves are present, Add removes key from the accumulator and returns (weight, scale, true).
func (*PairAccumulator[T]) Pending ¶
func (p *PairAccumulator[T]) Pending() []string
Pending returns the sorted keys that currently have only one half buffered.
type QuantConfig ¶
type QuantConfig struct {
Producer struct {
Name string `json:"name"`
Version string `json:"version"`
} `json:"producer"`
Quantization struct {
QuantAlgo string `json:"quant_algo"`
KVCacheQuantAlgo string `json:"kv_cache_quant_algo"`
GroupSize int `json:"group_size"`
ExcludeModules []string `json:"exclude_modules"`
} `json:"quantization"`
}
A QuantConfig is a decoded hf_quant_config.json.
func ParseQuantConfig ¶
func ParseQuantConfig(data []byte) (*QuantConfig, error)
ParseQuantConfig decodes an hf_quant_config.json. Unknown fields, trailing data and malformed exclude patterns are errors.
func (*QuantConfig) Excluded ¶
func (c *QuantConfig) Excluded(module string) bool
Excluded reports whether module, a dotted module name such as "model.layers.0.self_attn.q_proj", matches one of the exclude_modules patterns. A pattern's * matches any run of characters, dots included, as the exporter's fnmatch does.
Example ¶
package main
import (
"fmt"
"log"
nnckpt "github.com/tmc/lib/nvidia/x/nn/ckpt"
)
func main() {
c, err := nnckpt.ParseQuantConfig([]byte(`{
"producer": {"name": "modelopt", "version": "0.46.0"},
"quantization": {"quant_algo": "NVFP4", "kv_cache_quant_algo": "FP8", "group_size": 16,
"exclude_modules": ["lm_head", "model.layers.0.self_attn*"]}}`))
if err != nil {
log.Fatal(err)
}
fmt.Println(c.Excluded("model.layers.0.self_attn.q_proj"))
fmt.Println(c.Excluded("model.layers.0.mlp.experts.7.down_proj"))
}
Output: true false
func (*QuantConfig) ExcludedBy ¶
func (c *QuantConfig) ExcludedBy(module string) []string
ExcludedBy returns every exclude_modules pattern that matches module, in file order.
type RankGatherer ¶
type RankGatherer interface {
AllGather(ctx context.Context, phase string, local []byte) ([][]byte, error)
}
RankGatherer exchanges one phase-tagged state value across all ranks. A nil RankGatherer runs single-rank without synchronization.
type Receipt ¶
type Receipt struct {
Entries []Entry
}
A Receipt accounts for every checkpoint tensor and every slot, sorted by name.
func Bind ¶
Bind binds each slot to the tensor of the same name and accounts for every tensor. It returns an error, and no receipt, when the slots or rules are malformed: a slot without a name or dtypes, a slot declared twice or matched by a rule, a rule without a reason or with a malformed pattern, or a tensor listed twice. When a tensor is missing, mismatched or unbound, Bind returns the receipt together with an *Error.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/safetensors"
nnckpt "github.com/tmc/lib/nvidia/x/nn/ckpt"
)
func main() {
bf16 := []safetensors.Dtype{safetensors.BF16}
slots := []nnckpt.Slot{
{Name: "model.norm.weight", Dtypes: bf16, Shape: []int{8}},
{Name: "lm_head.weight", Dtypes: bf16, Shape: []int{32, 8}},
}
ignore := []nnckpt.Ignore{{Pattern: "*.rotary_emb.inv_freq", Reason: "computed from rope_theta"}}
tensors := []nnckpt.Tensor{
{Name: "model.norm.weight", Dtype: safetensors.BF16, Shape: []int{8}},
{Name: "lm_head.weight", Dtype: safetensors.BF16, Shape: []int{8, 32}},
{Name: "model.layers.0.self_attn.rotary_emb.inv_freq", Dtype: safetensors.F32, Shape: []int{4}},
}
r, err := nnckpt.Bind(slots, ignore, tensors)
for _, e := range r.Entries {
fmt.Println(e.Name, e.State)
}
fmt.Println(err)
}
Output: lm_head.weight mismatched model.layers.0.self_attn.rotary_emb.inv_freq ignored model.norm.weight bound ckptbind: lm_head.weight is BF16 [8 32], want BF16 [32 8]
type ScaleSpec ¶
ScaleSpec describes one device-resident quantization scale tensor and its host-copied values for cold-load host mirror validation.
type Slot ¶
type Slot struct {
Name string
// Dtypes lists the dtypes the reader accepts. It must not be empty.
Dtypes []safetensors.Dtype
// Shape is the exact shape the tensor must have; nil or empty means a
// scalar.
Shape []int
}
A Slot is one weight a lowering reads.
func ModelSlots ¶
ModelSlots returns a slot for every tensor the decoder layers of m name: norms, QK-norms, projections and their biases, the dense or shared MLP, and the expert router and selection bias. Shapes follow the record's documented layout. Every slot accepts the dtypes of m.Weights.
The record names neither the embedding, the final norm and the output head, nor each routed expert's weights, nor the attention output gate; the caller adds slots for those it reads. ModelSlots refuses an invalid record, and a weight format such as nvfp4 whose weights are not one tensor per slot.
type State ¶
type State string
A State is the outcome of binding one tensor name.
const ( Bound State = "bound" // a slot's tensor, with an accepted dtype and the shape Ignored State = "ignored" // matched by an Ignore rule Missing State = "missing" // a slot with no tensor Mismatched State = "mismatched" // a slot's tensor with another dtype or shape Unbound State = "unbound" // a tensor neither bound nor ignored )
The binding states. A receipt with only Bound and Ignored entries is accepted.
type Strategy ¶
type Strategy interface {
Name() string
Available(ctx context.Context) (bool, error)
Prepare(ctx context.Context, dst Target) error
Load(ctx context.Context, dst Target) error
Finalize(ctx context.Context, dst Target) error
Abort(ctx context.Context, dst Target) error
Rollback(ctx context.Context) error
}
Strategy is one self-contained weight-loading path. Available must not mutate Target or perform network or disk writes.
type StrategyError ¶
StrategyError marks an expected strategy miss or dirty failure. When Mutated is true, the chain calls Target.Reinit before trying the next strategy.
func (*StrategyError) Error ¶
func (e *StrategyError) Error() string
func (*StrategyError) Unwrap ¶
func (e *StrategyError) Unwrap() error
type Target ¶
Target is the engine-owned model state loaded by a Chain. Reinit must release old device allocations before allocating fresh ones.
type Tensor ¶
type Tensor struct {
Name string
Dtype safetensors.Dtype
Shape []int
// Size is the tensor's length in bytes.
Size int64
// Shard is the file that holds the tensor, or "" when unknown.
Shard string
}
A Tensor is one tensor of a checkpoint, as its header describes it.
type TensorReader ¶
type TensorReader interface {
Tensor(name string) (safetensors.Tensor, error)
}
A TensorReader reads a named tensor. *safetensors.File and *safetensors.Sharded implement it.
type Tensors ¶
type Tensors interface {
Tensor(name string) (safetensors.Tensor, error)
}
Tensors reads named tensors. *safetensors.File and *safetensors.Sharded implement it.
type WeightRule ¶
WeightRule reports whether the named checkpoint tensor is needed for role (for example "main" or "draft").