dfly

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: 16 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package dfly reads DFly2 drafter checkpoints and checks their compatibility with a paired DeepSeek V4.1 target before device execution.

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

Index

Examples

Constants

View Source
const (
	V41HiddenSize      = 5120
	V41NumHiddenLayers = 40
	V41QLoRARank       = 1280
	V41CEDSourceLayer  = 20
	V41RMSNormEps      = 1e-20
	V41MaskTokenID     = 128799
	V41TokenizerSHA256 = "c90dfa01249db1be4245780a052ede752e1361c612ac6d08e2bdada7d599476b"
	V41CEDWindow       = 128
	V41CEDTopK         = 512
	V41DraftBlockSize  = 6
)

Canonical DeepSeek V4.1 Flash target constants required for DFly2 paired speculative verification.

Variables

View Source
var V41CEDHiddenLayers = [...]int{19, 27, 31, 35}

V41CEDHiddenLayers lists the four V4.1 Flash hidden-state tap layers used by the DFly2 drafter.

View Source
var V41CEDIndexLayers = [...]int{28, 32, 36}

V41CEDIndexLayers lists the three V4.1 Flash decoder layers that reuse layer-20 KV with independent per-layer index tables.

Functions

func ValidateIndex

func ValidateIndex(c Config, data []byte) error

ValidateIndex validates every name and shard assignment in a B6 export index.

func ValidatePairedRunSheet

func ValidatePairedRunSheet(s PairedRunSheet) error

ValidatePairedRunSheet enforces fail-closed admission before launching a paired target-drafter run on GPU.

Types

type Block

type Block struct {
	Anchor, Position int
	Previous         []int
}

Block specifies the anchor and the previous tokens used by correction. Slots following the anchor use the configured mask token for draft input.

type Checkpoint

type Checkpoint struct {
	Config Config
	// contains filtered or unexported fields
}

A Checkpoint holds validated tensor headers and reads data on demand. Close releases the underlying files.

func Open

func Open(c Config, path string) (_ *Checkpoint, err error)

Open opens a single training safetensors file or a directory containing a B6 export index and all four shards. It validates headers before reading weights.

func (*Checkpoint) Close

func (c *Checkpoint) Close() error

Close releases the open shard files.

func (*Checkpoint) Tensor

func (c *Checkpoint) Tensor(name string) (st.Tensor, error)

Tensor reads a validated tensor by checkpoint name.

type Config

type Config struct {
	Architectures                    []string `json:"architectures"`
	AttentionType                    string   `json:"attention_type"`
	AttentiveCorrection              bool     `json:"attentive_correction"`
	AttentiveCorrectionBlockKeys     bool     `json:"attentive_correction_block_keys"`
	AttentiveCorrectionBlockKVIn     string   `json:"attentive_correction_block_kv_in"`
	AttentiveCorrectionBlockMode     string   `json:"attentive_correction_block_mode"`
	AttentiveCorrectionSourceLayer   int      `json:"attentive_correction_source_layer"`
	BetaFast                         float64  `json:"beta_fast"`
	BetaSlow                         float64  `json:"beta_slow"`
	BlockSize                        int      `json:"block_size"`
	CausalBlock                      bool     `json:"causal_block"`
	ConfidenceHeadWithMarkov         bool     `json:"confidence_head_with_markov"`
	ConfidenceOnPrenormHidden        bool     `json:"confidence_on_prenorm_hidden"`
	ContextLocalWindow               int      `json:"context_local_window"`
	DraftMLPType                     string   `json:"draft_mlp_type"`
	DSABackend                       string   `json:"dsa_backend"`
	EnableConfidenceHead             bool     `json:"enable_confidence_head"`
	EnableHiddenCorrection           bool     `json:"enable_hidden_correction"`
	HCEps                            float64  `json:"hc_eps"`
	HCMult                           int      `json:"hc_mult"`
	HCSinkhornIters                  int      `json:"hc_sinkhorn_iters"`
	HeadDim                          int      `json:"head_dim"`
	HiddenCorrectionIntermediateSize int      `json:"hidden_correction_intermediate_size"`
	HiddenSize                       int      `json:"hidden_size"`
	LayerArch                        string   `json:"layer_arch"`
	MarkovRank                       int      `json:"markov_rank"`
	MaskTokenID                      int      `json:"mask_token_id"`
	MaxPositionEmbeddings            int      `json:"max_position_embeddings"`
	ModelArch                        string   `json:"model_arch"`
	ModelType                        string   `json:"model_type"`
	MoEAuxFreeBiasUpdate             bool     `json:"moe_aux_free_bias_update"`
	MoEIntermediateSize              int      `json:"moe_intermediate_size"`
	MoERouterEnableExpertBias        bool     `json:"moe_router_enable_expert_bias"`
	MoERouterScoreFunc               string   `json:"moe_router_score_func"`
	MoESkipExpertInit                bool     `json:"moe_skip_expert_init"`
	MTPFusion                        string   `json:"mtp_fusion"`
	MTPFusionInit                    string   `json:"mtp_fusion_init"`
	NumAttentionHeads                int      `json:"num_attention_heads"`
	NumExperts                       int      `json:"num_experts"`
	NumExpertsPerTok                 int      `json:"num_experts_per_tok"`
	NumHiddenLayers                  int      `json:"num_hidden_layers"`
	NumSharedExperts                 int      `json:"num_shared_experts"`
	NumTargetLayers                  int      `json:"num_target_layers"`
	OGroups                          int      `json:"o_groups"`
	OLoRARank                        int      `json:"o_lora_rank"`
	OriginalSeqLen                   int      `json:"original_seq_len"`
	QLoRARank                        int      `json:"q_lora_rank"`
	QKRopeHeadDim                    int      `json:"qk_rope_head_dim"`
	RMSNormEps                       float64  `json:"rms_norm_eps"`
	RopeFactor                       float64  `json:"rope_factor"`
	RopeTheta                        float64  `json:"rope_theta"`
	RouteNorm                        bool     `json:"route_norm"`
	RouterScalingFactor              float64  `json:"router_scaling_factor"`
	SharedExpertSwigluClamp          bool     `json:"shared_expert_swiglu_clamp"`
	SwigluLimit                      float64  `json:"swiglu_limit"`
	TargetAttnInitLayers             []int    `json:"target_attn_init_layers"`
	TargetHCInitLayers               []int    `json:"target_hc_init_layers"`
	TargetHiddenSize                 int      `json:"target_hidden_size"`
	TargetIndexLayer                 []int    `json:"target_index_layer"`
	TargetIndexTopk                  int      `json:"target_index_topk"`
	TargetKVLayers                   []int    `json:"target_kv_layers"`
	TargetLayerIDs                   []int    `json:"target_layer_ids"`
	TargetMLPInitExperts             string   `json:"target_mlp_init_experts"`
	TargetMLPInitLayers              []int    `json:"target_mlp_init_layers"`
	TargetNumHiddenLayers            int      `json:"target_num_hidden_layers"`
	TieWordEmbeddings                bool     `json:"tie_word_embeddings"`
	VocabSize                        int      `json:"vocab_size"`
	// contains filtered or unexported fields
}

Config describes the DSV4.1 DFly2 drafter.

func ParseConfig

func ParseConfig(data []byte) (Config, error)

ParseConfig reads one strict training or exported DeepSeek V4.1 config.

Example
package main

import (
	"fmt"

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

func main() {
	_, err := dfly.ParseConfig([]byte(`{"unrecognized":true}`))
	fmt.Println(err)
}
Output:
dfly: read training config: json: unknown field "unrecognized"

type DecodeOptions

type DecodeOptions struct {
	// ProposalCap limits the number of candidates. Zero uses the model limit.
	ProposalCap int

	// MinConfidence, if non-nil, is a probability in [0, 1].
	// The first slot below it and all later slots are excluded.
	MinConfidence *float32
}

DecodeOptions controls the number of speculative candidates.

type DecodeStats

type DecodeStats struct {
	Steps, TokensGenerated, ContextLength int
	AcceptedPerStep                       []int
	MeanAcceptedLength                    float64
	DraftDurationNs, VerifyDurationNs     int64
}

DecodeStats describes completed target verification steps.

type Model

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

Model holds FP32 dense weights and optional packed experts for CPU inference.

func NewModel

func NewModel(cp *Checkpoint) (*Model, error)

NewModel materializes a checkpoint into a CPU model.

func (*Model) Forward

func (m *Model) Forward(t TargetState, block Block) (Result, error)

Forward evaluates one block using block.Previous for teacher-forced correction.

type PairedRunSheet

type PairedRunSheet struct {
	Target              PairedTargetContract `json:"target"`
	DraftBlockSize      int                  `json:"draft_block_size"`
	LocalWindow         int                  `json:"local_window"`
	TopK                int                  `json:"top_k"`
	TargetCheckpointSHA string               `json:"target_checkpoint_sha256"`
	DraftCheckpointSHA  string               `json:"draft_checkpoint_sha256"`
	AllowCrossVersion   bool                 `json:"allow_cross_version,omitempty"`
}

PairedRunSheet pins the pre-flight admission parameters for a real-target DFly2 speculative verification run (e.g. GB300).

type PairedTargetContract

type PairedTargetContract struct {
	HiddenSize           int     `json:"hidden_size"`
	NumHiddenLayers      int     `json:"num_hidden_layers"`
	QLoRARank            int     `json:"q_lora_rank"`
	RMSNormEps           float64 `json:"rms_norm_eps"`
	MaskTokenID          int     `json:"mask_token_id"`
	TokenizerSHA256      string  `json:"tokenizer_sha256"`
	CandidateSourceLayer int     `json:"candidate_source_layer"`
	CompressionRatios    []int   `json:"compression_ratios"`
	KVSourceLayers       []int   `json:"kv_source_layers"`
	IndexSourceLayers    []int   `json:"index_source_layers"`

	// CrossVersion explicitly opts into an experimental cross-version pairing.
	// CED 1:1 layout invariants still apply, and PairingLabel reports
	// "cross-version".
	CrossVersion bool `json:"cross_version,omitempty"`
}

PairedTargetContract describes the target checkpoint geometry, CED layer reuse mapping, and mounted tokenizer required before initializing a paired DFly2 target-drafter session on GPU.

func CanonicalV41PairedTargetContract

func CanonicalV41PairedTargetContract() PairedTargetContract

CanonicalV41PairedTargetContract returns the strict DeepSeek V4.1 Flash target contract expected by DFly2 B6 drafters.

func (PairedTargetContract) PairingLabel

func (c PairedTargetContract) PairingLabel() string

PairingLabel reports the pairing identity for metrics and run receipts.

func (PairedTargetContract) Validate

func (c PairedTargetContract) Validate() error

Validate checks that c matches the strict DeepSeek V4.1 Flash target contract and 1:1 CED layout invariants before device initialization.

Example
package main

import (
	"fmt"

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

func main() {
	c := dfly.CanonicalV41PairedTargetContract()
	if err := c.Validate(); err != nil {
		fmt.Println("invalid:", err)
		return
	}
	fmt.Println(c.PairingLabel())
}
Output:
deepseek-v4.1-flash

type Result

type Result struct {
	Logits, Confidence, Correction, Fusion []float32
	Hidden, PrenormHidden, CorrectedHidden []float32
}

Result holds row-major FP32 results in draft slot order. Confidence is nil when the checkpoint has no confidence projection.

type SpecDecoder

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

SpecDecoder performs greedy speculative decoding from a resident target. The current anchor is the pending token at ContextLength. It becomes part of the target cache on the next successful step.

func NewSpecDecoder

func NewSpecDecoder(model *Model, target VerifyTarget, anchor, position int, opts DecodeOptions) (*SpecDecoder, error)

NewSpecDecoder starts decoding at position with anchor as the pending token. The target must already hold the prefix ending just before position.

func (*SpecDecoder) Stats

func (d *SpecDecoder) Stats() DecodeStats

Stats returns a snapshot of successful steps. Accepted lengths include the target correction or bonus token emitted in every step.

func (*SpecDecoder) Step

func (d *SpecDecoder) Step(budget int) ([]int32, error)

Step emits up to budget tokens via one target verification. A budget of one verifies only the anchor. The correction or bonus token stays pending until the next step. Stats and anchor advance only after target commit succeeds.

type TargetState

type TargetState interface {
	KV(layer int) (start int, rows []float32)
	TopK(layer, slot int) []int
	LocalWindow(anchor, size int) (start, end int)
	Hidden(layer int) []float32
	FinalHidden() []float32
	Normalize(dst, hidden []float32) error
	Embed(dst []float32, token int) error
	LMHead(dst, hidden []float32) error
}

TargetState supplies the target data and projections for one draft block. KV returns contiguous, already rotated latent rows. The first return value is the absolute position of the first row. TopK returns borrowed absolute positions for a draft slot, with -1 for padding. LocalWindow returns a half-open range of absolute positions. Borrowed slices are read-only and must stay valid throughout Forward.

type V41CEDConfig

type V41CEDConfig struct {
	HiddenSize, NumHiddenLayers, QLoRARank, MaskTokenID  int
	RMSNormEps                                           float64
	TokenizerSHA256                                      string
	CompressionRatios, KVSourceLayers, IndexSourceLayers []int
	CandidateSourceLayer                                 int

	// CrossVersion opts into an experimental pairing. CED layout checks
	// still apply, and Pairing reports the experimental label.
	CrossVersion bool
}

V41CEDConfig describes the target checkpoint and mounted tokenizer. TokenizerSHA256 is the lowercase hex digest of the actual tokenizer file.

type V41CEDTargetAdapter

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

V41CEDTargetAdapter maps the drafter's logical layers to resident V4.1 target data. Its backend owns the hidden taps, index tables and cache transaction. All returned slices borrow the backend's current storage.

func NewV41CEDTargetAdapter

func NewV41CEDTargetAdapter(c V41CEDConfig, backend VerifyTarget) (*V41CEDTargetAdapter, error)

NewV41CEDTargetAdapter validates a backend's checkpoint and CED mappings. KV on backend must expose physical source layer 20. TopK must return distinct index-source views over candidates from layer 20.

func (*V41CEDTargetAdapter) Embed

func (a *V41CEDTargetAdapter) Embed(dst []float32, token int) error

Embed writes the target embedding of token.

func (*V41CEDTargetAdapter) FinalHidden

func (a *V41CEDTargetAdapter) FinalHidden() []float32

FinalHidden borrows the final hidden row preceding the anchor.

func (*V41CEDTargetAdapter) Hidden

func (a *V41CEDTargetAdapter) Hidden(layer int) []float32

Hidden borrows the requested V4.1 hidden tap.

func (*V41CEDTargetAdapter) KV

func (a *V41CEDTargetAdapter) KV(layer int) (int, []float32)

KV borrows an already rotated row range from the shared decoder source.

func (*V41CEDTargetAdapter) LMHead

func (a *V41CEDTargetAdapter) LMHead(dst, hidden []float32) error

LMHead projects the corrected draft hidden row with the target head.

func (*V41CEDTargetAdapter) LocalWindow

func (a *V41CEDTargetAdapter) LocalWindow(anchor, size int) (int, int)

LocalWindow returns the backend window bounded by V4.1's 128 positions.

func (*V41CEDTargetAdapter) Normalize

func (a *V41CEDTargetAdapter) Normalize(dst, hidden []float32) error

Normalize applies the backend target norm.

func (*V41CEDTargetAdapter) Pairing

func (a *V41CEDTargetAdapter) Pairing() string

Pairing reports the checkpoint pairing label for metrics and receipts.

func (*V41CEDTargetAdapter) TopK

func (a *V41CEDTargetAdapter) TopK(layer, slot int) []int

TopK borrows the logical layer's independent per-slot index table.

func (*V41CEDTargetAdapter) VerifyBlock

func (a *V41CEDTargetAdapter) VerifyBlock(position int, tokens []int32) ([]int32, func(int) error, error)

VerifyBlock forwards the transactional target verification.

type VerifyTarget

type VerifyTarget interface {
	TargetState

	// VerifyBlock evaluates the anchor and candidate tokens in one target
	// pass. It returns the greedy next-token prediction after each input
	// token and a function that resolves the provisional cache writes.
	// On error, the committed target state must be unchanged.
	//
	// The returned function is called once. A positive count commits that
	// many input tokens starting at the anchor; zero discards all writes.
	// On finish error the committed target state must be unchanged.
	VerifyBlock(position int, tokens []int32) (predictions []int32, finish func(count int) error, err error)
}

VerifyTarget provides a resident draft view and transactional target verification.

Jump to

Keyboard shortcuts

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