Documentation
¶
Overview ¶
Package logprob records per-token log-probabilities of scored sequences and compares records from different engines or paths.
A Record is the evidence for one sequence: its token IDs and prompt boundary, the log-probability of each scored token with its mode and dtype, the sampling settings, a digest of the logical weight tensors, and the batch, cache, kernel and pause/resume configuration the values came from. Position p holds log P(tokens[p] | tokens[:p]), which a causal model reads from the logits row of position p-1.
A Scorer turns logits rows into positions with the rules of the sampler (see sample.LogProbsCPU); every producer uses it, so a record from a serving engine and a record from a reference forward pass are computed the same way.
The comparisons are:
- Align pairs two records of the same tokens position by position; a position missing or empty in either is a failure, never a skip.
- ZeroDiff checks exact equality of the raw bits, reported apart from any tolerance result.
- FirstDiv finds the first divergent position and its pattern: a shift present from the first position points at shared numerics, a jump at a later position points at inputs, cache or state there.
- Split3 compares a reference, a clean-cache prefill and a recorded decode, reporting both differences and their k3 estimates per token separately; k3 is not additive, so they are never summed.
- Localize compares per-block inputs and outputs and blames a block only when its inputs match.
Every distribution is reported as a Summary: N, mean, p99, max and the count over a threshold. Maxima are compared only at matched N. A Gate's threshold comes from an A/A baseline of the same configuration and its allowed over-count from R null replicates, so it fails a fresh clean comparison with probability at most 1/(R+1). Its detection power is measured with planted errors on inputs not used to calibrate it, and Gate.Reading states what a PASS rules out.
Records name no host paths, users or hosts: Record.Validate and Record.CheckIdentity run before a record is written.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
Example compares a recorded sequence with a reference scoring of the same tokens: bit-exact counts first, then the first divergence.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/nn/logprob"
)
// record scores tokens from logits rows, as an engine or a reference
// would: row p-1 gives the log-probability of tokens[p].
func record(rows [][]float32, tokens []int32) *logprob.Record {
sc := logprob.Scorer{Vocab: 4, Mode: "raw"}
pos, err := sc.TeacherForce(rows, tokens, 1)
if err != nil {
panic(err)
}
return &logprob.Record{
Schema: logprob.Schema,
Sequence: logprob.Sequence{ID: "s0", TokenIDs: tokens, PromptLen: 1},
Mode: "raw",
Pos: pos,
}
}
func main() {
tokens := []int32{0, 2, 1}
ref := record([][]float32{{0, 1, 2, 0}, {1, 3, 0, 0}}, tokens)
got := record([][]float32{{0, 1, 2, 0}, {1, 3.01, 0, 0}}, tokens)
a, err := logprob.Align(ref, got)
if err != nil {
panic(err)
}
z := logprob.ZeroDiff(a)
fmt.Printf("exact %d of %d\n", z.Exact, z.N)
fd := logprob.FirstDiv(a, 1e-4)
fmt.Printf("first divergence at position %d (%s)\n", fd.Pos, fd.Pattern)
}
Output: exact 1 of 2 first divergence at position 2 (jump)
Index ¶
- Constants
- func CompareMax(a, b Summary) (bool, error)
- func InputDigest(s Sequence) string
- func IsHostPath(s string) bool
- func NormalizeDType(s string) string
- func WriteRecord(w io.Writer, r *Record) error
- type Aligned
- type Bits
- type Blame
- type Block
- type Config
- type Counts
- type DType
- type Detection
- type Engine
- type Env
- type Event
- type FirstDivResult
- type Gate
- type Kernel
- type Kernels
- type Mode
- type Model
- type Pair
- type Position
- type Power
- type Record
- type Result
- type Sampling
- type Scorer
- type Sequence
- type Split3Result
- type Split3Row
- type Summary
- type TensorDigest
- type Trace
- type WeightsDigest
- type ZeroResult
Examples ¶
Constants ¶
const DigestAlgo = "sha256-logical-v0"
DigestAlgo is the algorithm DigestTensors implements. It is interim: the shared evidence core's root is DigestJCS of the sorted tensor list, which replaces it once the JCS encoder lands.
const FlagSupportMismatch = "support-mismatch"
FlagSupportMismatch flags a position whose recorder found the support the sampler reported differs from the support the score was taken over, or found no report: its score may be of another distribution. Such a position stays in every comparison for diagnosis, but no comparison containing one passes, and no gate is calibrated or measured on one.
const Schema = "logprob-evidence/v0"
Schema is the schema name of the records this package writes.
Variables ¶
This section is empty.
Functions ¶
func CompareMax ¶
CompareMax reports whether a's maximum exceeds b's. Maxima grow with N, so it refuses summaries of different N.
func InputDigest ¶
InputDigest returns the digest of a sequence's input, its prompt tokens: two records of one prompt have the same input whatever their IDs or completions.
func IsHostPath ¶
IsHostPath reports whether s looks like a path on some host: absolute, home-relative, or a Windows drive path.
func NormalizeDType ¶
NormalizeDType returns the shared lowercase name of a dtype spelled as safetensors or NumPy spell it ("BF16", "F8_E4M3", "float32"), or the lowercased input if it is not one it knows.
Types ¶
type Aligned ¶
type Aligned struct {
Pairs []Pair
// Missing lists the positions scored in one record and not the
// other. Every comparison fails while it is non-empty.
Missing []int
// Unverified counts the record pairs not both carrying a weights
// digest: nothing shows they ran the same weights.
Unverified int
// Inputs lists the [InputDigest] of each compared sequence.
Inputs []string
// Flagged lists the paired positions either record flags
// [FlagSupportMismatch]. Every comparison fails while it is
// non-empty.
Flagged []int
}
Aligned is two records of the same tokens, paired by position.
func Align ¶
Align pairs ref and got. A record with no positions leaves every position of the other missing. They must score the same tokens, with the same prompt boundary, in the same mode and, for processed records, under the same sampler settings: a record of different tokens was regenerated, not teacher-forced, and comparing it would measure nothing, and records of different prompt boundaries declare different inputs, which one input digest cannot describe. Records whose weights digests differ are an error too.
type Bits ¶
type Bits uint64
Bits is a float64 encoded as its IEEE bits in hex.
func (Bits) MarshalJSON ¶
MarshalJSON encodes b as a quoted hex string.
func (*Bits) UnmarshalJSON ¶
UnmarshalJSON decodes a quoted hex string.
type Blame ¶
type Blame struct {
Pos int `json:"pos"`
Block string `json:"block"`
Index int `json:"index"`
// Verdict is "none" (every output agrees), "operator" (the block's
// inputs agree and its output does not), or "input" (the block's
// inputs already differ although the previous block's outputs agree:
// the data between blocks, such as a packing mask or a cache read).
Verdict string `json:"verdict"`
// InMax and OutMax are max |Δ| of the block's input and output.
InMax float64 `json:"in_max"`
OutMax float64 `json:"out_max"`
}
A Blame is the verdict of Localize.
type Block ¶
type Block struct {
Name string `json:"name"`
Input []float32 `json:"input"`
Output []float32 `json:"output"`
}
A Block is one stage of a forward pass at one position: its input and output activations. Name identifies it ("embed", "layer.3", "final_norm", "lm_head"); both traces must use the same names in the same order.
type Config ¶
type Config struct {
BatchRows int `json:"batch_rows,omitempty"`
PrefixCache bool `json:"prefix_cache"`
PrefillChunk int `json:"prefill_chunk,omitempty"`
KVDType string `json:"kv_dtype,omitempty"`
WeightDType string `json:"weight_dtype,omitempty"`
// SettingsGeneration is the serving settings' generation when the
// request started; Events mark tokens produced under another.
SettingsGeneration uint64 `json:"settings_generation,omitempty,string"`
}
Config is the batch, cache and prefill configuration of the run.
type Counts ¶
type Counts struct {
Exact int `json:"exact"`
PassTolerance int `json:"pass_tolerance"`
Fail int `json:"fail"`
Flagged int `json:"flagged"`
}
Counts splits a gated comparison's positions three ways, never merged: bit-identical, different but within the gate, and failing (over the threshold, or missing). Flagged counts the positions flagged FlagSupportMismatch, which are also in one of the three.
func CountsOf ¶
func CountsOf(z ZeroResult, r Result) Counts
CountsOf returns the counts of a comparison checked as r with exact result z.
type DType ¶
DType states the precision of the values a record was computed from, in the shared lowercase names: f64 f32 f16 bf16 f8e4m3 f8e5m2 f4e2m1 i64 ... u8 bool.
type Detection ¶
type Detection struct {
// Plant names the planted error, such as "weight_row_scale" (one weight
// row of the model multiplied by 1+e).
Plant string `json:"plant"`
N int `json:"n"`
Detected []float64 `json:"detected"`
Missed []float64 `json:"missed"`
// CalibrationInputs and DetectionInputs list the inputs the gate was
// calibrated on and the inputs the errors were planted on. They are
// disjoint: an error planted on a calibration input is measured
// against a threshold fitted to that input's own noise and looks
// detected at any size.
CalibrationInputs []string `json:"calibration_inputs"`
DetectionInputs []string `json:"detection_inputs"`
// Floor is the smallest e detected such that every larger e tried
// was detected too; nil if none was.
Floor *float64 `json:"floor"`
}
A Detection is a gate's power against one kind of planted error at its N: the error sizes it rejected and the ones it passed. A gate's PASS says nothing about errors below Floor.
type Engine ¶
type Engine struct {
Name string `json:"name"`
Commit string `json:"commit,omitempty"`
// Path is the engine path, such as "cuda-serve", "cuda-prefill",
// "cpu-ref64" or "sglang".
Path string `json:"path"`
}
Engine names what produced a record.
type Env ¶
type Env struct {
Prefixes []string `json:"prefixes"`
Norm string `json:"norm"`
Values map[string]string `json:"values"`
Hashed map[string]string `json:"hashed"`
}
Env is the environment a producer observed, in the shared redacted form: every variable matching one of Prefixes appears in Values (an allowlisted key whose value matches its pattern) or in Hashed (the "sha256:" digest of its value normalized by Norm), never both.
type Event ¶
type Event struct {
Pos int `json:"pos"`
Kind string `json:"kind"`
StepID uint64 `json:"step_id,omitempty,string"`
}
An Event marks something that happened to the sequence at Pos. Kind is "pause", "resume" or "preempt", the names receipts share, or "settings": a token produced under another serving-settings generation than the request started under.
type FirstDivResult ¶
type FirstDivResult struct {
// Pos is the first position whose |Δ| is over the threshold or that
// is missing; -1 if none.
Pos int `json:"pos"`
Delta float64 `json:"delta"`
// Pattern is "none", "missing", "from-start" (the first scored
// position already diverges) or "jump" (earlier positions agree).
Pattern string `json:"pattern"`
// Persistent is the fraction of positions from Pos on that are over
// the threshold.
Persistent float64 `json:"persistent"`
Before Summary `json:"before"`
After Summary `json:"after"`
// Reading is the interpretation of the pattern.
Reading string `json:"reading"`
}
A FirstDivResult locates the first divergence of two records.
func FirstDiv ¶
func FirstDiv(a *Aligned, threshold float64) FirstDivResult
FirstDiv finds the first position of a whose |Δ| exceeds threshold. A shift from the first position on means the two paths' shared numerics differ (kernels, rounding, accumulation order); a jump after agreeing positions means the inputs, cache or state differ there.
type Gate ¶
type Gate struct {
Threshold float64 `json:"threshold"`
// AllowedOver is the number of positions over Threshold a passing
// comparison may have.
AllowedOver int `json:"allowed_over"`
// N is the number of positions of every baseline; the gate checks
// only comparisons of the same N.
N int `json:"n"`
AA Summary `json:"aa"`
Nulls []Summary `json:"nulls,omitempty"`
// FalseFailBound bounds the chance the gate fails a fresh clean
// comparison of the same config: it fails only one whose over-count
// exceeds every null replicate's, which for exchangeable replicates
// has probability at most 1/(len(Nulls)+1). It is 1 with no nulls.
FalseFailBound float64 `json:"false_fail_bound"`
// Detection is the gate's measured power; nil if never measured.
Detection *Detection `json:"detection,omitempty"`
// Inputs lists the inputs of the A/A and null comparisons, sorted.
Inputs []string `json:"calibration_inputs"`
}
A Gate is a tolerance on per-token |Δ log p| calibrated from A/A baselines: comparisons of a configuration with itself or with its reference on inputs where nothing is wrong.
The threshold is the largest difference of the first baseline. Since a maximum grows with N and a fresh sample exceeds an old maximum about half the time, the gate does not fail on one position over it: the allowed count over the threshold is the largest count any further baseline (a null replicate of the same N) reached.
func Calibrate ¶
Calibrate returns the gate of the A/A comparison aa and the null replicates nulls, which must all have aa's N. With no nulls the gate allows no position over the threshold, which is right only for comparisons expected to be bit-exact or exactly repeatable.
Example ¶
ExampleCalibrate builds a gate from an A/A comparison and a null replicate, then checks a new comparison of the same N against it.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/nn/logprob"
)
// record scores tokens from logits rows, as an engine or a reference
// would: row p-1 gives the log-probability of tokens[p].
func record(rows [][]float32, tokens []int32) *logprob.Record {
sc := logprob.Scorer{Vocab: 4, Mode: "raw"}
pos, err := sc.TeacherForce(rows, tokens, 1)
if err != nil {
panic(err)
}
return &logprob.Record{
Schema: logprob.Schema,
Sequence: logprob.Sequence{ID: "s0", TokenIDs: tokens, PromptLen: 1},
Mode: "raw",
Pos: pos,
}
}
func main() {
tokens := []int32{0, 2, 1}
ref := record([][]float32{{0, 1, 2, 0}, {1, 3, 0, 0}}, tokens)
near := func(d float32) *logprob.Record {
return record([][]float32{{0, 1, 2 + d, 0}, {1, 3 + d, 0, 0}}, tokens)
}
aa, _ := logprob.Align(ref, near(0.002))
null, _ := logprob.Align(ref, near(0.001))
g, err := logprob.Calibrate(aa, null)
if err != nil {
panic(err)
}
for _, d := range []float32{0.001, 0.1} {
a, _ := logprob.Align(ref, near(d))
r, _ := g.Check(a)
fmt.Printf("shift %g: pass %v\n", d, r.Pass)
}
fmt.Printf("false-fail bound %.2f\n", g.FalseFailBound)
}
Output: shift 0.001: pass true shift 0.1: pass false false-fail bound 0.50
func (Gate) Check ¶
Check applies g to a. It fails when a position is missing or flagged, or more than AllowedOver differences are over the threshold.
func (Gate) Measure ¶
Measure checks g against comparisons with planted errors of sizes sizes[i] and returns its detection power.
type Kernel ¶
type Kernel struct {
Name string `json:"name"`
ModuleSHA256 string `json:"module_sha256"`
Extensions map[string]json.RawMessage `json:"extensions,omitempty"`
}
A Kernel identifies one kernel by name and the digest of its module, "sha256:<hex>". Vendor detail goes in Extensions, keyed by vendor.
type Mode ¶
type Mode string
A Mode is "raw" or "processed"; see sample.LogProbRaw and sample.LogProbProcessed.
type Model ¶
type Model struct {
ID string `json:"id"`
Weights *WeightsDigest `json:"weights,omitempty"`
}
Model identifies the weights.
type Position ¶
type Position struct {
Pos int `json:"pos"`
Token int32 `json:"token"`
// LogProb is the value; Bits, its float64 bits in hex, is
// authoritative, since JSON decimals need not round-trip -Inf.
LogProb float64 `json:"logprob"`
Bits Bits `json:"logprob_bits"`
Phase string `json:"phase,omitempty"`
StepID uint64 `json:"step_id,omitempty,string"`
Row int `json:"row,omitempty"`
// Kept is the size of the support the token was scored in.
Kept int `json:"kept,omitempty"`
Flags []string `json:"flags,omitempty"`
}
A Position is the log-probability of one token.
func (Position) MarshalJSON ¶
MarshalJSON writes LogProb as null when it is not finite, so the record stays valid JSON; Bits carries the value.
func (*Position) SetLogProb ¶
SetLogProb sets p's value and bits.
func (*Position) UnmarshalJSON ¶
UnmarshalJSON reads a position, taking its value from Bits.
type Power ¶
type Power struct {
Planted string `json:"planted"`
Detected bool `json:"detected"`
Result Result `json:"result"`
}
Power is the outcome of checking a gate against a planted error.
type Record ¶
type Record struct {
Schema string `json:"schema"`
Engine Engine `json:"engine"`
Model Model `json:"model"`
Sequence Sequence `json:"sequence"`
Sampling Sampling `json:"sampling"`
Mode Mode `json:"mode"`
DType DType `json:"dtype"`
Config Config `json:"config"`
// Env is the observed environment, redacted as receipts redact it;
// nil until a producer can apply the shared normalizer.
Env *Env `json:"env,omitempty"`
// Runtime holds the versions of the runtime pieces, such as "go",
// "cuda_toolkit" and "gpu_driver_version".
Runtime map[string]string `json:"runtime,omitempty"`
Kernels Kernels `json:"kernels,omitempty"`
Events []Event `json:"events,omitempty"`
Pos []Position `json:"positions"`
}
A Record is the evidence for one scored sequence.
func ReadRecords ¶
ReadRecords reads a JSONL stream of records and validates each.
func (*Record) CheckIdentity ¶
CheckIdentity reports an error if any free-form string of r contains user or host (case-insensitive; names shorter than 3 bytes are not checked). It is the residual check a writer runs before writing.
type Result ¶
type Result struct {
Summary Summary `json:"summary"`
Missing []int `json:"missing,omitempty"`
// Flagged lists the positions flagged [FlagSupportMismatch]; they
// are summarized above but fail the comparison.
Flagged []int `json:"flagged,omitempty"`
Pass bool `json:"pass"`
}
A Result is a gate's verdict on one comparison.
type Sampling ¶
type Sampling struct {
Method string `json:"method"`
Temperature float32 `json:"temperature"`
TopK int `json:"top_k"`
TopP float32 `json:"top_p"`
MinP float32 `json:"min_p"`
// Seed is written as a decimal string: JSON numbers are doubles.
Seed uint64 `json:"seed,string"`
}
Sampling is the sampler configuration the positions were recorded under. A Temperature of 0 is greedy.
func (*Sampling) UnmarshalJSON ¶
UnmarshalJSON accepts the numeric seed emitted by older v0 producers.
type Scorer ¶
type Scorer struct {
// Vocab is the logical vocabulary size. Rows may be longer (a padded
// LM head); columns past Vocab are not tokens.
Vocab int
Mode Mode
Sampling Sampling
}
A Scorer computes positions from logits rows.
func (*Scorer) Score ¶
Score returns position pos, holding token, scored from row, the logits that predict it.
func (*Scorer) TeacherForce ¶
TeacherForce scores tokens[from:] given rows, where rows[j] is the logits row after the model has read tokens[:j+1]. It never generates: every scored token is the recorded one. from must be at least 1.
type Sequence ¶
type Sequence struct {
ID string `json:"id,omitempty"`
TokenIDs []int32 `json:"token_ids"`
// PromptLen is the number of prompt tokens; positions at or past it
// were generated.
PromptLen int `json:"prompt_len"`
}
Sequence is the scored token sequence.
type Split3Result ¶
type Split3Result struct {
Rows []Split3Row `json:"rows"`
Missing []int `json:"missing,omitempty"`
// Flagged lists the positions any of the three records flags
// [FlagSupportMismatch].
Flagged []int `json:"flagged,omitempty"`
// Summaries of |RefPrefill|, |PrefillDecode| and each k3.
RefPrefill Summary `json:"ref_prefill"`
PrefillDecode Summary `json:"prefill_decode"`
K3RefPrefill Summary `json:"k3_ref_prefill"`
K3PrefillDecode Summary `json:"k3_prefill_decode"`
K3RefDecode Summary `json:"k3_ref_decode"`
// Classes counts tokens by which difference is over its threshold:
// "agree", "prefill" (engine numerics), "cache" (decode or cache
// state) and "both".
Classes map[string]int `json:"classes"`
}
Split3Result is a three-way split of a recorded decode.
func Split3 ¶
func Split3(ref, prefill, decode *Record, prefillThreshold, decodeThreshold float64) (*Split3Result, error)
Split3 compares a reference, a clean-cache teacher-forced prefill of the recorded tokens, and the recorded decode itself. A token is classified by whether |prefill - ref| exceeds prefillThreshold and whether |decode - prefill| exceeds decodeThreshold; each threshold should come from an A/A baseline of its own comparison.
type Split3Row ¶
type Split3Row struct {
Pos int `json:"pos"`
Token int32 `json:"token"`
Ref Bits `json:"ref"`
Prefill Bits `json:"prefill"`
Decode Bits `json:"decode"`
// RefPrefill is prefill - ref: the engine's numerics against the
// reference, with no cache in the way.
RefPrefill float64 `json:"ref_prefill"`
// PrefillDecode is decode - prefill: what the cache and the decode
// path add on top of the engine's own prefill.
PrefillDecode float64 `json:"prefill_decode"`
// The k3 estimates of each comparison, with log r taken as the first
// path's log-probability minus the second's. k3 is not additive:
// K3RefDecode is not K3RefPrefill + K3PrefillDecode.
K3RefPrefill float64 `json:"k3_ref_prefill"`
K3PrefillDecode float64 `json:"k3_prefill_decode"`
K3RefDecode float64 `json:"k3_ref_decode"`
}
A Split3Row is one token of a three-way split.
type Summary ¶
type Summary struct {
N int `json:"n"`
Mean float64 `json:"mean"`
// P99 is the nearest-rank 99th percentile.
P99 float64 `json:"p99"`
Max float64 `json:"max"`
// MaxPos is the position of the maximum, -1 when N is 0.
MaxPos int `json:"max_pos"`
// Over counts the values greater than Threshold.
Threshold float64 `json:"threshold"`
Over int `json:"over"`
// NaN counts values that are NaN, and Inf the infinite ones, such as
// a processed-mode token one side kept and the other did not (-Inf).
// Both count as over the threshold and are left out of Mean, P99
// and Max, which summarize the finite values.
NaN int `json:"nan,omitempty"`
Inf int `json:"inf,omitempty"`
}
A Summary describes a distribution of non-negative per-token values, such as absolute log-probability differences.
type TensorDigest ¶
type TensorDigest struct {
Name string `json:"name"`
DType string `json:"dtype"`
Shape []int `json:"shape"`
SHA256 string `json:"sha256"`
}
A TensorDigest is the digest of one logical tensor.
func DigestTensor ¶
func DigestTensor(name, dtype string, shape []int, data []byte) TensorDigest
DigestTensor returns the digest of one tensor's bytes as stored, its dtype in the shared lowercase name (see NormalizeDType).
type WeightsDigest ¶
type WeightsDigest struct {
Algo string `json:"algo"`
Root string `json:"root"`
Tensors []TensorDigest `json:"tensors"`
}
WeightsDigest identifies the logical tensors of a model: each tensor's name, dtype, shape and bytes as the model reads them, independent of how they are split across files.
func DigestTensors ¶
func DigestTensors(tensors []TensorDigest) (*WeightsDigest, error)
DigestTensors returns the digest of a model's tensors. Root is the SHA-256 of one line per tensor, sorted by name: "name dtype d0,d1,... sha256\n".
type ZeroResult ¶
type ZeroResult struct {
N int `json:"n"`
// Exact counts the bit-identical positions; it is never merged with
// a tolerance pass.
Exact int `json:"exact"`
Unequal int `json:"unequal"`
First int `json:"first"` // first unequal position, -1 if none
Missing []int `json:"missing,omitempty"`
// Flagged lists the positions flagged [FlagSupportMismatch]; they
// are counted above but fail the comparison.
Flagged []int `json:"flagged,omitempty"`
Pass bool `json:"pass"`
}
A ZeroResult is the outcome of ZeroDiff.
func ZeroDiff ¶
func ZeroDiff(a *Aligned) ZeroResult
ZeroDiff checks that every position's log-probability has the same bits in both records. It is a diagnostic for paths that should be identical, never a tolerance.