graph

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: 17 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 graph provides the core tensor computation DAG IR, fluent tensor construction, einsum rank canonicalization, speed-of-light bounds, device function emission, and model architecture fact extraction.

Use NewGraph and Graph.Snapshot to build and freeze validated DAGs, NewInput and Tensor methods to construct source-attributed tensor expressions, EmitTree and EmitBackwardTree to emit composable CUDA C++ device functions, CanonicalizeRanks and ComputeSOLBounds to analyze einsum workloads, and [ExtractFacts] to derive transformer model metadata.

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 (
	EmbedScaleConstant   = "constant"
	EmbedScaleSqrtHidden = "sqrt_hidden"
)

The embedding scale kinds.

View Source
const (
	ScalingLinear = "linear"
	ScalingLlama3 = "llama3"
)

The RoPE scaling types. ScalingLlama3 names the method, which models other than Llama use too.

View Source
const (
	SelectionBiasScores = "scores"
	SelectionBiasLogits = "logits"
)

The selection bias placement modes for Experts.SelectionBiasOn.

View Source
const (
	ScoreSoftmax = "softmax"
	ScoreSigmoid = "sigmoid"
)

The router score functions.

View Source
const (
	ActivationSiLU     = "silu"
	ActivationGELUTanh = "gelu_tanh"
)

The MLP activations. ActivationGELUTanh is the tanh approximation of GELU.

View Source
const QScaleLog1pPos = "log1p_pos"

The pre-attention Q scale expression kinds.

Variables

View Source
var (
	// ErrCyclicGraph reports a rank graph that cannot be traversed from its inputs.
	ErrCyclicGraph = errors.New("cudatensor: cyclic einsum graph")
	// ErrNotCanonicalized reports analysis or export before rank canonicalization.
	ErrNotCanonicalized = errors.New("cudatensor: einsum graph is not canonicalized")
)
View Source
var (
	ScaleDTypes   = []string{"ue8m0", "e4m3", "f32"}
	ScaleLayouts  = []string{"row_major", "tcgen05_128x4", "blocked_32x4"}
	ComputeDTypes = []string{"f32", "bf16", "f16"}
)

The scale dtypes and layouts recognized in FormatSpec.

View Source
var (
	// ErrCycleDetected is returned when a graph contains a directed cycle.
	ErrCycleDetected = errors.New("cudair: cycle detected in graph")

	// ErrMixedGraphOwnership is returned when nodes from different graphs are wired together.
	ErrMixedGraphOwnership = errors.New("cudair: mixed graph node ownership")

	// ErrUnknownOperator is returned when a node requests unknown operator semantics.
	ErrUnknownOperator = errors.New("cudair: unknown operator semantics")

	// ErrShapeMismatch is returned when tensor dimensions violate operation contracts.
	ErrShapeMismatch = errors.New("cudair: shape mismatch")

	// ErrTypeMismatch is returned when tensor data types are incompatible.
	ErrTypeMismatch = errors.New("cudair: type mismatch")

	// ErrInvalidAxis is returned when an axis index or permutation is out of bounds.
	ErrInvalidAxis = errors.New("cudair: invalid axis")

	// ErrInvalidOutput is returned when an output specification is invalid or unreachable.
	ErrInvalidOutput = errors.New("cudair: invalid graph output")

	// ErrArenaOverflow is returned when total memory arena demand exceeds address limits.
	ErrArenaOverflow = errors.New("cudair: arena memory allocation overflow")

	// ErrUnsupportedEffect reports a storage effect without admitted execution semantics.
	ErrUnsupportedEffect = errors.New("cudair: unsupported storage effect")
)
View Source
var (
	// ErrInvalidSOLCeiling reports missing or invalid roofline limits.
	ErrInvalidSOLCeiling = errors.New("cudatensor: invalid SOL ceiling")
	// ErrMissingSOLData reports graph metrics required to compute a SOL bound.
	ErrMissingSOLData = errors.New("cudatensor: missing SOL graph data")
	// ErrSOLOverflow reports a non-finite duration or byte total.
	ErrSOLOverflow = errors.New("cudatensor: SOL result overflow")
)

Activations lists the MLP activations a Layer may name.

View Source
var ErrBackwardEmissionUnsupported = fmt.Errorf("cudair: backward emission unsupported: %w", cuda.ErrUnsupported)

ErrBackwardEmissionUnsupported reports that a node does not support backward device code generation.

View Source
var ErrContextBoundsExceeded = errors.New("cudair: emitted context or write rule violated")

ErrContextBoundsExceeded reports emitted code that violates a context or write rule, including out-of-region context access, unsupported calls and writes outside allowed body locals or backward gradient outputs.

View Source
var ErrEmissionUnsupported = fmt.Errorf("cudair: emission unsupported: %w", cuda.ErrUnsupported)

ErrEmissionUnsupported reports that a node does not support forward device code generation.

View Source
var Formats = []string{"bf16", "e4m3", "nvfp4", "mxfp8"}

Formats lists the storage formats Model.Weights and Model.KVCache may name.

Functions

func BackwardShmemBytes

func BackwardShmemBytes(node any, nThreads int, mode GradientMode) (int, error)

BackwardShmemBytes queries the dynamic shared memory needed for backward execution. If node does not implement BackwardEmitter, it returns ErrBackwardEmissionUnsupported.

func CanonicalKey

func CanonicalKey(g *EinsumGraph) string

CanonicalKey returns a stable serialization suitable for graph comparisons.

func EmitBackward

func EmitBackward(node any, name string, nThreads int) (string, error)

EmitBackward checks if node implements BackwardEmitter, calling its EmitBackward. If node does not implement BackwardEmitter, it returns ErrBackwardEmissionUnsupported naming the node.

func EmitBackwardFromBody

func EmitBackwardFromBody(n BackwardEmitter, name, body string) (string, error)

EmitBackwardFromBody generates the fixed backward CUDA __device__ function signature, emits lane-offset context preambles when enabled, and splices body. This matches tiny-cuda-nn object.h:681.

func EmitForward

func EmitForward(node any, name string) (string, error)

EmitForward checks if node implements Emitter, calling its EmitForward. If node does not implement Emitter, it returns ErrEmissionUnsupported naming the node.

func EmitFromBody

func EmitFromBody(n Emitter, name, body string) (string, error)

EmitFromBody generates the fixed forward CUDA __device__ function signature, emits lane-offset context preambles when enabled, and splices body. This matches tiny-cuda-nn object.h:665.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/ir/graph"
)

type exampleLayer struct {
	name     string
	inWidth  int
	outWidth int
}

func (l *exampleLayer) Name() string                  { return l.name }
func (l *exampleLayer) InputWidth() int               { return l.inWidth }
func (l *exampleLayer) OutputWidth() int              { return l.outWidth }
func (l *exampleLayer) PaddedOutputWidth() int        { return l.outWidth }
func (l *exampleLayer) FwdCtxBytes() (int, error)     { return 0, nil }
func (l *exampleLayer) FwdCtxAlignedPerElement() bool { return true }
func (l *exampleLayer) EmitForward(name string) (string, error) {
	return graph.EmitFromBody(l, name, "\treturn input;")
}

func main() {
	layer := &exampleLayer{name: "linear", inWidth: 4, outWidth: 4}
	code, err := graph.EmitFromBody(layer, "linear_eval", "\treturn input;")
	if err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}
	fmt.Printf("%t\n", len(code) > 0)
}
Output:
true

func Encode

func Encode(w io.Writer, m *Model) error

Encode writes m as indented JSON.

func ExportTimeloopWorkload

func ExportTimeloopWorkload(g *CanonicalGraph, w io.Writer) error

ExportTimeloopWorkload writes a Timeloop v0.5 workload as YAML-compatible JSON. It accepts only an unchanged graph returned by CanonicalizeRanks. The output includes SOLAR's per-einsum and top-level tensor-role renames.

func NodeName

func NodeName(node any) string

NodeName returns a readable string identifier for node.

func Paths

func Paths() []string

Paths returns every fact path of Model, in declaration order.

func Set

func Set(m *Model, path string, v any) error

Set assigns v to the fact at path in m, in every layer for a layer fact, allocating pointer facts on the way. It is for tests that show a lowering reads what its Caps say it lowers: change a Lowered fact, and the lowering's result must change or be an error.

func ValidateFwdContextBounds

func ValidateFwdContextBounds(node Emitter, bytesWritten int) error

ValidateFwdContextBounds verifies that the actual context bytes written by node does not exceed its declared FwdCtxBytes.

Types

type ArenaPlan

type ArenaPlan struct {
	TotalBytes int
	Offsets    map[*Node]int
}

ArenaPlan represents the planned memory layout for tensor scratchpads. Offsets contains arena-backed nodes, including their storage aliases. External inputs and aliases backed by external inputs have no offset. Snapshot accessors return detached keys; compare their stable node IDs.

func PlanMemory

func PlanMemory(g *Graph) *ArenaPlan

PlanMemory plans a memory arena reusing intermediate buffers after their last consumer completes. Graph outputs remain live through graph completion. It returns an empty plan on error; use Graph.Snapshot for checked planning.

type Attention

type Attention struct {
	// Scale multiplies q·k before the softmax, usually HeadDim^-0.5.
	Scale float64 `json:"scale"`
	// ScaleExpr is an optional typed position-dependent pre-attention
	// multiplier applied to Q (for example bias + scale * log1p(max(pos, 0))).
	// Scale still holds the QK score multiplier.
	ScaleExpr *QScaleExpr `json:"scale_expr,omitempty"`
	// SlidingWindow limits each query to that many most recent keys; 0
	// means unlimited.
	SlidingWindow int `json:"sliding_window,omitempty"`
	// OutputGate reports a sigmoid gate on the attention output, computed
	// from the layer input.
	OutputGate bool `json:"output_gate,omitempty"`
	// Softcap bounds each scaled score s as Softcap·tanh(s/Softcap); 0
	// means none.
	Softcap float64 `json:"softcap,omitempty"`
	// Sinks names a [Heads] tensor of per-head logits that join each
	// softmax denominator without contributing a value; empty for none.
	Sinks string `json:"sinks,omitempty"`
	// PackedQGate stores the gate projection in the second segment of
	// each head in Q instead of a separately bound projection.
	PackedQGate bool `json:"packed_q_gate,omitempty"`
}

Attention holds the facts of the attention core.

type BackwardCompositeSymbolEmitter

type BackwardCompositeSymbolEmitter interface {
	EmitBackwardWithChildren(name string, children []ChildSymbol, nThreads int, mode GradientMode) (string, error)
}

BackwardCompositeSymbolEmitter emits a backward parent using names chosen by EmitTree.

type BackwardEmitter

type BackwardEmitter interface {
	Emitter
	EmitBackward(name string, nThreads int) (string, error)
	BackwardShmemBytes(nThreads int, mode GradientMode) int
}

BackwardEmitter extends Emitter for nodes that support backward device code generation.

type BackwardModeEmitter

type BackwardModeEmitter interface {
	EmitBackwardMode(name string, nThreads int, mode GradientMode) (string, error)
}

BackwardModeEmitter selects the parameter-gradient write mode at emission. Its output buffer belongs to one sample; batch reduction is a separate step.

type CanonicalGraph

type CanonicalGraph struct {
	Nodes []CanonicalNode
	Shape map[string]string
	// contains filtered or unexported fields
}

CanonicalGraph is an einsum graph whose ranks have stable generated names.

func CanonicalizeRanks

func CanonicalizeRanks(g *EinsumGraph) (*CanonicalGraph, error)

CanonicalizeRanks renames dimension ranks in predecessor-ready breadth-first order. Start nodes are retained as external inputs and their output ranks receive generated labels.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/ir/graph"
)

func main() {
	eg := &graph.EinsumGraph{Nodes: []graph.EinsumNode{
		{ID: "input", OutputRank: 1},
		{ID: "relu", Equation: "x->x", Inputs: []string{"input"}},
	}}
	canonical, err := graph.CanonicalizeRanks(eg)
	if err != nil {
		panic(err)
	}
	fmt.Println(canonical.Nodes[1].Equation)
	fmt.Println(graph.CanonicalKey(eg) != "")
}
Output:
A->A
true

type CanonicalNode

type CanonicalNode struct {
	ID            string
	Equation      string
	Inputs        []string
	Start         bool
	Output        []hostshape.DimToken
	MACs          uint64
	OtherOps      uint64
	InputTensors  []TensorInfo
	OutputTensors []TensorInfo
}

CanonicalNode is the rank-renamed representation of one graph node.

type Cap

type Cap struct {
	Use   Use
	Allow []any
	Why   string
}

A Cap is what one lowering does with one fact.

func Ignore

func Ignore(why string) Cap

Ignore returns the Cap of a fact that cannot change the lowering's result, for the reason why.

func Lower

func Lower() Cap

Lower returns the Cap of a fact the lowering reads.

func Only

func Only(values ...any) Cap

Only returns the Cap of a fact the lowering accepts only at one of values, which must have the fact's Go type. For a pointer fact, values is empty and only nil is accepted.

type Caps

type Caps struct {
	// Name prefixes Check's errors, for example "arch config".
	Name   string
	Fields map[string]Cap
}

Caps records what one lowering does with every fact of a Model, keyed by fact path: the JSON names from the Model down, joined by dots, with slices and embedded structs transparent. The attention window of every layer is "layers.attention.sliding_window"; the experts block is "layers.mlp.experts", and its fields "layers.mlp.experts.count" and so on. A pointer fact has a path of its own; its fields need entries only when it is Lowered.

A lowering calls Caps.Check before it reads a Model, and its tests call Caps.Coverage, which fails when a field is added to Model without a decision.

func (*Caps) Check

func (c *Caps) Check(m *Model) error

Check reports every fact of m that c refuses or has no entry for, each once, at the first layer where it occurs. It does not validate m; see Model.Validate.

Example
caps := &Caps{Name: "dense", Fields: make(map[string]Cap)}
for _, p := range Paths() {
	caps.Fields[p] = Lower()
}
caps.Fields["layers.attention.sliding_window"] = Only(0)
caps.Fields["layers.mlp.experts"] = Only()

m := llama()
fmt.Println(caps.Check(m))
m.Layers[0].Attention.SlidingWindow = 4096
fmt.Println(caps.Check(m))

delete(caps.Fields, "layers.attention.sinks")
fmt.Println(caps.Coverage())
Output:
<nil>
dense: layer 0: layers.attention.sliding_window 4096 is not lowered
dense: fact layers.attention.sinks is neither lowered, ignored nor refused

func (*Caps) Coverage

func (c *Caps) Coverage() error

Coverage reports every problem with c: a fact path with no entry and no refused or ignored pointer above it, an entry naming no fact, an Ignored entry without a reason, or an Allow value of the wrong type.

func (*Caps) Hold

func (c *Caps) Hold(path string, base func() *Model, edit func(*Model) error, v any, lower func(*Model) (string, error)) error

Hold checks that lower treats the fact at path as c says. Lower returns the lowering's result as text, or an error when it refuses the record. Edit changes the fact in a fresh base record; for a nil edit, Set assigns v to the fact instead. Then:

  • a Lowered fact must change the result and not be refused;
  • an Ignored fact must leave the result as it was;
  • a Refused fact must be refused with an error naming path, while each value its Cap allows must lower, each to a different result.

A lowering's tests call Hold for every entry of its Caps, so that a fact the lowering reads but calls ignored, or drops but calls lowered, fails a test.

type Ceiling

type Ceiling struct {
	MACsPerCycle    float64
	BytesPerCycle   float64
	FrequencyGHz    float64
	BytesPerElement float64
}

Ceiling contains the per-cycle rates and element size used for SOL predictions. It matches SOLAR's architecture configuration units.

type ChildSymbol

type ChildSymbol struct {
	Name                string
	FwdCtxOffset        int
	ParentFwdCtxBytes   int
	ParentFwdCtxAligned bool
}

ChildSymbol carries the exact emitted child symbol and its context-region offset.

func (ChildSymbol) FwdCtxArg

func (c ChildSymbol) FwdCtxArg() string

FwdCtxArg returns the parent expression for passing this child's context region while preserving the per-lane offset already applied by the parent.

type CompositeEmitter

type CompositeEmitter interface {
	Emitter
	Children() []Emitter
}

CompositeEmitter represents a sequential composition and exposes its ordered child emitters.

type CompositeSymbolEmitter

type CompositeSymbolEmitter interface {
	EmitForwardWithChildren(name string, children []ChildSymbol) (string, error)
}

CompositeSymbolEmitter emits a parent using the exact child symbols and context offsets selected by EmitTree.

type DAGEmitter

type DAGEmitter interface {
	Emitter
	DAGKey() string
	DAGSymbol() string
	Dependencies() []DAGEmitter
	EmitForwardWithDependencies(name string, dependencies []ChildSymbol) (string, error)
}

DAGEmitter opts into context-free fan-out emission. Each ordered dependency takes the parent's complete packed input vector. Parent and child input and parameter types must match; compute types may differ. DAGKey identifies the immutable computation; DAGSymbol is its exact valid C++ function identifier. EmitForwardWithDependencies must call every supplied child once, in order, using input, params and the child's FwdCtxArg. Bodies use EmitFromBody's generated signature and the existing read-only write contract. Shared keys deduplicate definitions, not execution. Any nonzero forward context refuses.

The initial contract admits at most 256 unique nodes, 4096 traversal visits, width 1048576, and 4 MiB of combined source. Keys are at most 4096 bytes; symbols are at most 256 ASCII identifier bytes and cannot be C++ keywords, reserved double-underscore names, generated parameter names, or the math intrinsics expf/erff/sqrtf/rsqrtf and helper lane_id. Declared shared memory must be nonnegative and at most 4 MiB; device limits still require separate validation. EmitTree's name must equal the root DAGSymbol. Emitters must remain immutable throughout both validation and emission.

Example
package main

import "fmt"

type dagExampleLeaf struct{}

func (dagExampleLeaf) InputWidth() int               { return 1 }
func (dagExampleLeaf) OutputWidth() int              { return 1 }
func (dagExampleLeaf) PaddedOutputWidth() int        { return 1 }
func (dagExampleLeaf) FwdCtxBytes() (int, error)     { return 0, nil }
func (dagExampleLeaf) FwdCtxAlignedPerElement() bool { return false }
func (dagExampleLeaf) DAGKey() string                { return "input:fp32:1" }
func (dagExampleLeaf) DAGSymbol() string             { return "leaf" }
func (dagExampleLeaf) Dependencies() []DAGEmitter    { return nil }
func (n dagExampleLeaf) EmitForward(name string) (string, error) {
	return EmitFromBody(n, name, "return input;")
}
func (n dagExampleLeaf) EmitForwardWithDependencies(name string, children []ChildSymbol) (string, error) {
	return n.EmitForward(name)
}

func main() {
	u, err := EmitTree(dagExampleLeaf{}, "leaf")
	fmt.Println(u.Symbols, u.FwdCtxBytes, err)
}
Output:
[leaf] 0 <nil>

type DataType

type DataType int

DataType identifies tensor primitive data types.

const (
	Float32 DataType = iota
	Float16
	BFloat16
	Int32
	Int64
	Uint8
	Int8
)

func (DataType) SizeBytes

func (dt DataType) SizeBytes() int

SizeBytes returns the size in bytes of a single scalar element.

func (DataType) String

func (dt DataType) String() string

type EinsumGraph

type EinsumGraph struct {
	Nodes []EinsumNode
	// Shape maps source equation ranks to Timeloop bound expressions in one
	// namespace shared by every node. Keys are kept verbatim; canonicalization
	// renames matching upper-case keys.
	Shape map[string]string
}

Graph is an ordered einsum graph. Node order is significant and supplies the stable order used to resolve otherwise equivalent traversals.

type EinsumNode

type EinsumNode struct {
	ID            string
	Equation      string
	Inputs        []string
	OutputRank    int
	MACs          uint64
	OtherOps      uint64 // retained from analysis; SOLAR does not include it in compute cycles
	InputTensors  []TensorInfo
	OutputTensors []TensorInfo
}

EinsumNode describes one operation in an einsum DAG. Inputs are predecessor node IDs in operand order. Start nodes describe external tensors and have no equation; their output rank count is OutputRank.

type EmbedScale

type EmbedScale struct {
	// Kind is EmbedScaleConstant or EmbedScaleSqrtHidden.
	Kind  string  `json:"kind"`
	Value float64 `json:"value,omitempty"`
	DType string  `json:"dtype,omitempty"`
}

EmbedScale describes a typed embedding multiplier applied after token lookup.

type Emitter

type Emitter interface {
	EmitForward(name string) (string, error)
	InputWidth() int
	OutputWidth() int
	PaddedOutputWidth() int
	FwdCtxBytes() (int, error)
	FwdCtxAlignedPerElement() bool
}

Emitter is implemented by nodes that can render themselves as a self-contained CUDA __device__ function. Nodes without this support must not implement it. Unsupported nodes return ErrEmissionUnsupported together with the node's name.

Writable body locals support float, int, bool, uint8_t and auto, with one declaration per statement. Template values such as tvec<float, N> may be declared without an initializer, then written element by element. Template initializers and comma-separated declarations are refused. Other local types are refused when written. Pointer and reference locals are refused.

Backward bodies may also write through generated dL_dx and dL_dparams output parameters. Input and context parameters remain read-only. Supported forms include (*dL_dx)[i], dL_dparams[i] and *(dL_dparams + i). A direct *dL_dparams assignment is refused; use an indexed output write.

Context accessor integer constants and arithmetic offsets are checked at emission; dynamic offsets are checked against FwdCtxBytes at run time by LoadByte/StoreByte and LoadFloat/StoreFloat. Float access uses aligned four-byte offsets and checked spans; load destinations must be matching scalar body locals.

type Experts

type Experts struct {
	Count        int    `json:"count"`
	TopK         int    `json:"top_k"`
	Intermediate int    `json:"intermediate"`
	Router       string `json:"router"`
	// Score is ScoreSoftmax, over all Count logits, or ScoreSigmoid.
	Score string `json:"score"`
	// SelectionBias names a [Count] tensor that moves expert selection but
	// not the weights; empty for none.
	SelectionBias string `json:"selection_bias,omitempty"`
	// SelectionBiasOn records where SelectionBias is added:
	// SelectionBiasScores ("scores") or SelectionBiasLogits ("logits").
	// Empty defaults to scores for backward compatibility.
	SelectionBiasOn string `json:"selection_bias_on,omitempty"`
	Normalize       bool   `json:"normalize,omitempty"`
	// NormalizeEps is the epsilon added to the renormalization denominator
	// (sum(w) + NormalizeEps) when Normalize is true.
	NormalizeEps float64 `json:"normalize_eps,omitempty"`
	Scale        float64 `json:"scale"`
	// RouterDType and CombineDType record the compute dtypes of router
	// scoring and expert output combination ("f32", "bf16", "f16").
	RouterDType  string `json:"router_dtype,omitempty"`
	CombineDType string `json:"combine_dtype,omitempty"`
	// WeightFormat overrides Model.Weights for the routed experts.
	WeightFormat string `json:"weight_format,omitempty"`
	// TensorPrefix precedes the decimal expert index and dot in numbered
	// checkpoint keys. An empty prefix leaves the binding to the consumer.
	TensorPrefix string `json:"tensor_prefix,omitempty"`
}

Experts describes a routed mixture of experts. Gate, Up and Down of the enclosing MLP are then the shared experts, and are empty when there are none. For a token x the routed output is

s = Score(Router·x)
E = the TopK experts by s + SelectionBias
w_e = s_e / Σ_{e∈E} s_e if Normalize, else s_e
y = Scale · Σ_{e∈E} w_e · Expert_e(x)

where a missing SelectionBias is zero.

type FormatSpec

type FormatSpec struct {
	Format      string `json:"format"`
	ScaleDType  string `json:"scale_dtype,omitempty"`
	BlockSize   int    `json:"block_size,omitempty"`
	ScaleLayout string `json:"scale_layout,omitempty"`
}

FormatSpec carries storage and scale-layout metadata for quantized weight formats such as mxfp8 so scale tensors and layouts survive lowering.

type Frame

type Frame struct {
	File     string
	Line     int
	Function string
}

A Frame is one caller of the statement a SourceLocation names.

type GatedDeltaLayout

type GatedDeltaLayout struct {
	QKVChannels    int
	ConvHistory    [2]int // QKV channel, previous token
	RecurrentState [3]int // value head, key feature, value feature
}

GatedDeltaLayout gives per-sequence cache extents. A decoder allocates independent state per recurrent layer and sequence. Both are zero at the start of a new sequence.

type GatedDeltaNet

type GatedDeltaNet struct {
	KeyHeads     int `json:"key_heads"`
	ValueHeads   int `json:"value_heads"`
	KeyHeadDim   int `json:"key_head_dim"`
	ValueHeadDim int `json:"value_head_dim"`
	ConvKernel   int `json:"conv_kernel"`

	// QKV, Z, A and B have respectively [QKVChannels, hidden],
	// [ValueHeads*ValueHeadDim, hidden] and two [ValueHeads, hidden]
	// weights. Output has weight [hidden, ValueHeads*ValueHeadDim].
	QKV    Projection `json:"qkv"`
	Z      Projection `json:"z"`
	A      Projection `json:"a"`
	B      Projection `json:"b"`
	Output Projection `json:"output"`

	// ConvWeight is [QKVChannels, 1, ConvKernel]. ALog and DTBias are
	// [ValueHeads], and OutputNorm's weight is [ValueHeadDim].
	ConvWeight string `json:"conv_weight"`
	ALog       string `json:"a_log"`
	DTBias     string `json:"dt_bias"`
	OutputNorm Norm   `json:"output_norm"`

	// State formats describe live cache storage, not checkpoint weights.
	ConvHistoryDType string `json:"conv_history_dtype"`
	StateDType       string `json:"state_dtype"`
}

GatedDeltaNet describes a causal depthwise convolution followed by the recurrent gated delta rule. Its inputs are the normalized residual stream. QKV packs Q, K and V consecutively. Each channel uses its own convolution filter over the current token and preceding history, with missing earlier tokens treated as zero. The convolution is followed by SiLU before Q and K are L2-normalized and Q is scaled by the inverse square root of KeyHeadDim. Each key head is repeated over a contiguous group of value heads.

The beta gate is sigmoid(B(x)). With a := A(x), the state decay is exp(-exp(ALog)*softplus(a+DTBias)). OutputNorm normalizes each recurrent value head before multiplying by SiLU(Z(x)) and applying Output.

func (GatedDeltaNet) Layout

func (g GatedDeltaNet) Layout() (GatedDeltaLayout, error)

Layout derives the cache shapes, rejecting dimensions whose index products overflow int.

Example
g := GatedDeltaNet{KeyHeads: 16, ValueHeads: 64, KeyHeadDim: 128, ValueHeadDim: 128, ConvKernel: 4}
cache, err := g.Layout()
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(cache.ConvHistory, cache.RecurrentState)
Output:
[12288 3] [64 128 128]

type GradientMode

type GradientMode int

GradientMode specifies how gradients are accumulated into parameter buffers.

const (
	// GradientModeIgnore ignores gradient writes.
	GradientModeIgnore GradientMode = iota
	// GradientModeOverwrite overwrites gradient memory directly.
	GradientModeOverwrite
	// GradientModeAccumulate adds gradients to existing output memory. The
	// emitter must declare its policy for concurrently shared outputs.
	GradientModeAccumulate
)

func (GradientMode) String

func (m GradientMode) String() string

String returns the string representation of the gradient mode.

type Graph

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

Graph represents a directed acyclic computation graph.

func NewGraph

func NewGraph() *Graph

NewGraph creates an empty IR Graph.

func (*Graph) AddBinary

func (g *Graph) AddBinary(op string, a, b *Node) *Node

AddBinary creates an elementwise binary operation (e.g. "add", "sub", "mul", "div").

func (*Graph) AddBinaryChecked

func (g *Graph) AddBinaryChecked(op string, a, b *Node) (*Node, error)

AddBinaryChecked creates an elementwise binary operation with equal input shapes or a scalar (one-element) operand. Nonscalar broadcasting is not supported.

func (*Graph) AddConcat

func (g *Graph) AddConcat(inputs []*Node, axis int) *Node

AddConcat creates a tensor concatenation along axis.

func (*Graph) AddConcatChecked

func (g *Graph) AddConcatChecked(inputs []*Node, axis int) (*Node, error)

AddConcatChecked creates a tensor concatenation with explicit validation.

func (*Graph) AddConstant

func (g *Graph) AddConstant(name string, shape []int, dt DataType, values []float32) *Node

AddConstant creates a constant tensor node.

func (*Graph) AddConstantChecked

func (g *Graph) AddConstantChecked(name string, shape []int, dt DataType, values []float32) (*Node, error)

AddConstantChecked creates a constant tensor node with explicit validation.

func (*Graph) AddInput

func (g *Graph) AddInput(name string, shape []int, dt DataType) *Node

AddInput creates an external input node.

func (*Graph) AddInputChecked

func (g *Graph) AddInputChecked(name string, shape []int, dt DataType) (*Node, error)

AddInputChecked creates an external input node with explicit validation.

func (*Graph) AddMatMul

func (g *Graph) AddMatMul(a, b *Node) *Node

AddMatMul creates a 2D matrix multiplication node (C = A x B).

func (*Graph) AddMatMulChecked

func (g *Graph) AddMatMulChecked(a, b *Node) (*Node, error)

AddMatMulChecked creates a matrix multiplication node with explicit validation.

func (*Graph) AddOutput

func (g *Graph) AddOutput(n *Node) error

AddOutput adds an explicit output node to the graph.

func (*Graph) AddReduce

func (g *Graph) AddReduce(op string, in *Node, axis int) *Node

AddReduce creates a reduction operation (e.g. "sum", "max") along specified axis.

func (*Graph) AddReduceChecked

func (g *Graph) AddReduceChecked(op string, in *Node, axis int) (*Node, error)

AddReduceChecked creates a reduction operation with explicit validation.

func (*Graph) AddReshape

func (g *Graph) AddReshape(in *Node, shape []int) *Node

AddReshape creates a tensor reshape operation.

func (*Graph) AddReshapeChecked

func (g *Graph) AddReshapeChecked(in *Node, shape []int) (*Node, error)

AddReshapeChecked creates a tensor reshape operation with explicit validation.

func (*Graph) AddSlice

func (g *Graph) AddSlice(in *Node, starts, ends, steps []int) *Node

AddSlice creates a tensor slice operation.

func (*Graph) AddSliceChecked

func (g *Graph) AddSliceChecked(in *Node, starts, ends, steps []int) (*Node, error)

AddSliceChecked creates a tensor slice operation with explicit validation.

func (*Graph) AddTranspose

func (g *Graph) AddTranspose(in *Node, perm []int) *Node

AddTranspose creates a tensor transposition with axis permutation.

func (*Graph) AddTransposeChecked

func (g *Graph) AddTransposeChecked(in *Node, perm []int) (*Node, error)

AddTransposeChecked creates a tensor transposition with explicit validation.

func (*Graph) AddUnary

func (g *Graph) AddUnary(op string, in *Node) *Node

AddUnary creates an elementwise unary operation (e.g. "relu", "gelu", "exp", "log", "sqrt", "neg").

func (*Graph) AddUnaryChecked

func (g *Graph) AddUnaryChecked(op string, in *Node) (*Node, error)

AddUnaryChecked creates an elementwise unary operation with explicit validation.

func (*Graph) Err

func (g *Graph) Err() error

Err returns any sticky error recorded during graph construction.

func (*Graph) Nodes

func (g *Graph) Nodes() []*Node

Nodes returns all nodes in the graph in topological insertion order.

func (*Graph) Outputs

func (g *Graph) Outputs() []*Node

Outputs returns the explicit graph outputs, or if none were explicitly set, all terminal non-input nodes.

func (*Graph) SetOutputs

func (g *Graph) SetOutputs(nodes ...*Node) error

SetOutputs configures explicit graph outputs. Each output node must belong to the graph.

func (*Graph) Snapshot

func (g *Graph) Snapshot() (*Snapshot, error)

Snapshot validates the computation graph and freezes it into an immutable Snapshot. It checks for cycles, mixed-graph node ownership, authoritative semantic compliance, shape and layout validity, and constructs a safe sequential execution plan.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/ir/graph"
)

func main() {
	g := graph.NewGraph()
	a := g.AddInput("A", []int{32, 64}, graph.Float32)
	b := g.AddInput("B", []int{64, 128}, graph.Float32)
	c := g.AddMatMul(a, b) // 32x128
	d := g.AddUnary("relu", c)

	if err := g.SetOutputs(d); err != nil {
		panic(err)
	}

	snap, err := g.Snapshot()
	if err != nil {
		panic(err)
	}

	fmt.Printf("Nodes: %d, Outputs: %d, Order: %d\n",
		len(snap.Nodes()), len(snap.Outputs()), len(snap.Order()))
}
Output:
Nodes: 4, Outputs: 1, Order: 4

type Layer

type Layer struct {
	// Heads and KVHeads count query and key-value heads, each HeadDim wide.
	Heads   int `json:"heads"`
	KVHeads int `json:"kv_heads"`
	HeadDim int `json:"head_dim"`

	AttnNorm     Norm    `json:"attn_norm"`
	PostAttnNorm *Norm   `json:"post_attn_norm,omitempty"`
	MLPNorm      Norm    `json:"mlp_norm"`
	PostMLPNorm  *Norm   `json:"post_mlp_norm,omitempty"`
	QKNorm       *QKNorm `json:"qk_norm,omitempty"`

	// Q, K, V and O are the attention projections. Q is
	// [Heads·HeadDim, hidden], K and V [KVHeads·HeadDim, hidden], and O
	// [hidden, Heads·HeadDim]. With Attention.PackedQGate, Q instead
	// has two consecutive HeadDim segments per head (query, then gate).
	Q Projection `json:"q"`
	K Projection `json:"k"`
	V Projection `json:"v"`
	O Projection `json:"o"`

	// RoPE is optional; nil represents NoPE (no rotary position embedding).
	RoPE      *RoPE     `json:"rope,omitempty"`
	Attention Attention `json:"attention"`

	// Residual multiplies each branch before it is added to the residual
	// stream. It is 1 for most models.
	Residual float64 `json:"residual"`

	MLP MLP `json:"mlp"`

	// Kind selects the decoder mixer. The empty kind is [LayerAttention].
	// GatedDeltaNet is populated only for [LayerGatedDeltaNet].
	Kind          LayerKind      `json:"kind,omitempty"`
	GatedDeltaNet *GatedDeltaNet `json:"gated_delta_net,omitempty"`
}

A Layer is one decoder layer:

a = Attention(RoPE(QKNorm(AttnNorm(h)·Q)), RoPE(QKNorm(AttnNorm(h)·K)), AttnNorm(h)·V)·O
h = h + Residual·PostAttnNorm(a)
h = h + Residual·PostMLPNorm(MLP(MLPNorm(h)))

where a nil PostAttnNorm, PostMLPNorm or QKNorm is the identity.

func (Layer) DecoderKind

func (l Layer) DecoderKind() LayerKind

DecoderKind reports the mixer, treating the omitted legacy kind as attention.

Example
var layer Layer
fmt.Println(layer.DecoderKind())
Output:
attention

type LayerKind

type LayerKind string

LayerKind identifies the mixer used by a decoder layer.

const (
	LayerAttention     LayerKind = "attention"
	LayerGatedDeltaNet LayerKind = "gated_deltanet"
)

type MLP

type MLP struct {
	// Activation is one of [Activations].
	Activation   string     `json:"activation"`
	Intermediate int        `json:"intermediate"`
	Gate         Projection `json:"gate"`
	Up           Projection `json:"up"`
	Down         Projection `json:"down"`
	Experts      *Experts   `json:"experts,omitempty"`
	// SharedExpertGate is an optional scalar projection [1, hidden]. Its
	// sigmoid multiplies the shared branch before it joins the routed output.
	SharedExpertGate *Projection `json:"shared_expert_gate,omitempty"`
}

MLP is a gated feed-forward block,

Down(act(Gate·x) ⊙ Up·x)

or, when Experts is set, a routed mixture of such blocks.

type MTP

type MTP struct {
	InputProjection Projection `json:"input_projection"`
	Layers          []Layer    `json:"layers"`
}

MTP describes a head that projects concatenated token embeddings and decoder states from 2*Hidden to Hidden before a stack of decoder layers.

type Model

type Model struct {
	// Hidden is the width of the residual stream.
	Hidden int `json:"hidden"`
	// Vocab is the vocabulary size, or 0 when the record covers layers only.
	Vocab int `json:"vocab,omitempty"`
	// Weights and KVCache name the storage formats of the checkpoint's
	// projection weights (unless overridden by Experts.WeightFormat) and the
	// KV cache. Weights may be "bf16", "e4m3", "nvfp4" or "mxfp8". The cache
	// supports "bf16" and "e4m3".
	Weights string `json:"weights"`
	// WeightFormat holds optional storage/layout metadata for quantized
	// weight formats. Required when Weights is "mxfp8".
	WeightFormat *FormatSpec `json:"weight_format,omitempty"`
	KVCache      string      `json:"kv_cache"`
	// EmbedScale is an optional multiplier applied to token embeddings
	// before layer 0 (for example sqrt(hidden)).
	EmbedScale *EmbedScale `json:"embed_scale,omitempty"`
	// Layers holds one record per physical decoder layer, in physical order.
	Layers []Layer `json:"layers"`
	// Visits holds an optional explicit execution schedule over Layers,
	// binding each execution ordinal to a physical layer and a unique KV
	// cache slot. When empty, Layers run once in order with KV slot == layer.
	Visits []Visit `json:"visits,omitempty"`
	// MTP describes an optional multi-token prediction head. Its layers are
	// independent of the main decoder's execution schedule and KV slots.
	MTP *MTP `json:"mtp,omitempty"`
}

A Model is the architecture record of a decoder-only language model.

func Decode

func Decode(r io.Reader) (*Model, error)

Decode reads a Model encoded as JSON and validates it. Unknown fields are an error.

Example
m, err := Decode(strings.NewReader(`{
		"hidden": 256, "weights": "bf16", "kv_cache": "bf16",
		"layers": [{
			"heads": 4, "kv_heads": 2, "head_dim": 64,
			"attn_norm": {"weight": "in.w", "eps": 1e-5},
			"mlp_norm": {"weight": "post.w", "eps": 1e-5},
			"q": {"weight": "q.w"}, "k": {"weight": "k.w"}, "v": {"weight": "v.w"}, "o": {"weight": "o.w"},
			"rope": {"theta": 10000, "rotary_dim": 64},
			"attention": {"scale": 0.125},
			"residual": 1,
			"mlp": {"activation": "silu", "intermediate": 512,
				"gate": {"weight": "g.w"}, "up": {"weight": "u.w"}, "down": {"weight": "d.w"}}
		}]
	}`))
if err != nil {
	fmt.Println(err)
	return
}
l := m.Layers[0]
fmt.Println(len(m.Layers), l.Heads, l.KVHeads, l.HeadDim, l.MLP.Activation)
Output:
1 4 2 64 silu

func (*Model) Validate

func (m *Model) Validate() error

Validate reports the first fact of m that is missing or inconsistent.

type Node

type Node struct {
	ID        int
	Name      string
	Kind      NodeKind
	Op        string
	Inputs    []*Node
	Shape     []int
	Type      DataType
	SourceLoc SourceLocation

	// Layout and memory metadata
	Layout       hostshape.Layout
	Strides      []int
	Effect       StorageEffect
	StorageAlias *Node

	// Operator specific parameters
	ConstValues []float32
	Axes        []int
	Perm        []int
	SliceStarts []int
	SliceEnds   []int
	SliceSteps  []int
	Axis        int
	// contains filtered or unexported fields
}

Node represents an operation or tensor in the IR graph.

func (*Node) Graph

func (n *Node) Graph() *Graph

Graph returns the graph to which this node belongs.

func (*Node) NumElements

func (n *Node) NumElements() int

NumElements returns total number of elements in the tensor.

func (*Node) SizeBytes

func (n *Node) SizeBytes() int

SizeBytes returns total buffer size in bytes needed for this tensor.

type NodeKind

type NodeKind int

NodeKind identifies the operator category.

const (
	KindInput NodeKind = iota
	KindConstant
	KindUnary
	KindBinary
	KindMatMul
	KindReduce
	KindReshape
	KindTranspose
	KindSlice
	KindConcat
)

func (NodeKind) String

func (k NodeKind) String() string

type Norm

type Norm struct {
	Weight string  `json:"weight"`
	Eps    float64 `json:"eps"`
	Offset float64 `json:"offset,omitempty"`
	DType  string  `json:"dtype,omitempty"`
}

A Norm is an RMSNorm over the last axis:

y = x·rsqrt(mean(x²) + Eps)·(Offset + w)

Offset is 0 for most models and 1 for those that store w - 1. DType optionally records the storage dtype of Weight ("f32", "bf16", "f16").

type Projection

type Projection struct {
	Weight string `json:"weight"`
	Bias   string `json:"bias,omitempty"`
}

A Projection names a weight [out, in] and an optional bias [out].

type QKNorm

type QKNorm struct {
	Q Norm `json:"q"`
	K Norm `json:"k"`
}

A QKNorm normalizes each query and key head over HeadDim, after the projection and before RoPE.

type QScaleExpr

type QScaleExpr struct {
	Kind       string  `json:"kind"`
	DType      string  `json:"dtype"`
	Bias       float64 `json:"bias,omitempty"`
	Scale      float64 `json:"scale,omitempty"`
	BiasParam  string  `json:"bias_param,omitempty"`
	ScaleParam string  `json:"scale_param,omitempty"`
}

QScaleExpr describes a typed position-dependent pre-attention Q multiplier. For Kind == QScaleLog1pPos, the multiplier is:

Bias + Scale * log1p(max(pos, 0))

evaluated in DType, where pos is the absolute token position. BiasParam and ScaleParam optionally name learned checkpoint parameter tensors.

type RoPE

type RoPE struct {
	// Theta is the base of the inverse frequencies θ^(-2i/RotaryDim).
	Theta float64 `json:"theta"`
	// RotaryDim is the number of leading columns of each head that rotate.
	// The rest pass through.
	RotaryDim int `json:"rotary_dim"`
	// Interleaved pairs columns (2i, 2i+1). Otherwise column i pairs with
	// column i + RotaryDim/2, the rotate-half layout of most checkpoints.
	Interleaved bool `json:"interleaved,omitempty"`
	// Scaling rescales the inverse frequencies; nil means none.
	Scaling *RoPEScaling `json:"scaling,omitempty"`
}

RoPE describes the rotary position embedding of one layer.

type RoPEScaling

type RoPEScaling struct {
	// Type is ScalingLinear (every frequency divided by Factor) or
	// ScalingLlama3 (wavelengths above OriginalMaxPos/LowFreqFactor divided by Factor,
	// those below OriginalMaxPos/HighFreqFactor kept, and a smooth blend
	// between).
	Type           string  `json:"type"`
	Factor         float64 `json:"factor"`
	LowFreqFactor  float64 `json:"low_freq_factor,omitempty"`
	HighFreqFactor float64 `json:"high_freq_factor,omitempty"`
	OriginalMaxPos int     `json:"original_max_position,omitempty"`
}

RoPEScaling is a rescaling of the RoPE inverse frequencies.

type SOLReport

type SOLReport struct {
	Unfused              float64
	Fused                float64
	FusedPrefetched      float64
	UnfusedWholeGraph    float64
	FusedWholeGraph      float64
	UnfusedBytes         float64
	FusedBytes           float64
	FusedPrefetchedBytes float64
}

SOLReport contains intended per-op bounds and the whole-graph values used by SOLAR. Durations are seconds; byte fields are decimal byte counts.

func ComputeSOLBounds

func ComputeSOLBounds(g *CanonicalGraph, c Ceiling) (SOLReport, error)

ComputeSOLBounds computes intended per-op unfused/fused bounds and SOLAR's whole-graph values. Fused input and output tensors are deduplicated by name; intermediates are excluded. Shared external reads are charged to the consumer with the largest MAC count, breaking ties by smallest node ID. Start nodes supply external inputs, not work.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/ir/graph"
)

func main() {
	eg := &graph.EinsumGraph{Nodes: []graph.EinsumNode{
		{ID: "input", OutputRank: 1, OutputTensors: []graph.TensorInfo{{Name: "x", Elements: 4}}},
		{ID: "copy", Equation: "i->i", Inputs: []string{"input"}, MACs: 4,
			InputTensors:  []graph.TensorInfo{{Name: "x", Elements: 4}},
			OutputTensors: []graph.TensorInfo{{Name: "y", Elements: 4}}},
	}}
	canonical, err := graph.CanonicalizeRanks(eg)
	if err != nil {
		panic(err)
	}
	report, err := graph.ComputeSOLBounds(canonical, graph.Ceiling{
		MACsPerCycle: 1, BytesPerCycle: 4, FrequencyGHz: 1, BytesPerElement: 2,
	})
	if err != nil {
		panic(err)
	}
	fmt.Printf("fused bound: %.0f ns\n", report.Fused*1e9)
}
Output:
fused bound: 4 ns

type ShmemProvider

type ShmemProvider interface {
	ShmemBytes() int
}

ShmemProvider allows an emitter to declare dynamic shared memory requirements.

type Snapshot

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

Snapshot represents an immutable, topologically validated execution graph. Its accessors return detached copies. Node IDs are stable across copies; node pointer addresses and graph pointers are not.

func (*Snapshot) ArenaPlan

func (s *Snapshot) ArenaPlan() *ArenaPlan

ArenaPlan returns the precomputed memory scratchpad plan.

func (*Snapshot) Consumers

func (s *Snapshot) Consumers(n *Node) []*Node

Consumers returns all direct successor nodes that consume n.

func (*Snapshot) Contains

func (s *Snapshot) Contains(n *Node) bool

Contains reports whether n belongs to this snapshot and retains its original ID. Both original graph nodes and detached nodes from snapshot accessors are accepted. Foreign graph nodes and copies with changed IDs are rejected.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/ir/graph"
)

func main() {
	g := graph.NewGraph()
	x := g.AddInput("x", []int{1}, graph.Float32)
	g.AddUnary("relu", x)
	s, err := g.Snapshot()
	if err != nil {
		fmt.Println(err)
		return
	}
	foreign := graph.NewGraph().AddInput("x", []int{1}, graph.Float32)
	fmt.Println(s.Contains(x), s.Contains(s.NodeByID(x.ID)), s.Contains(foreign))
}
Output:
true true false

func (*Snapshot) Dependencies

func (s *Snapshot) Dependencies(n *Node) []*Node

Dependencies returns all direct prerequisite input nodes for n.

func (*Snapshot) Inputs

func (s *Snapshot) Inputs() []*Node

Inputs returns all external input nodes.

func (*Snapshot) NodeByID

func (s *Snapshot) NodeByID(id int) *Node

NodeByID returns the node with the specified ID, or nil if not found.

func (*Snapshot) Nodes

func (s *Snapshot) Nodes() []*Node

Nodes returns all nodes in the snapshot.

func (*Snapshot) Order

func (s *Snapshot) Order() []*Node

Order returns the nodes sorted in safe sequential topological execution order.

func (*Snapshot) Outputs

func (s *Snapshot) Outputs() []*Node

Outputs returns all graph output nodes.

type SourceLocation

type SourceLocation struct {
	File     string
	Line     int
	Function string
	Callers  []Frame
}

SourceLocation captures host Go source attribution for an IR node.

File, Line and Function name the statement that built the node. Callers holds the frames above that statement, nearest first, so a node built inside a helper can also be charged to the code that called the helper. Callers is capped by whoever records the location and may be empty.

type StorageEffect

type StorageEffect int

StorageEffect indicates the memory effect of an operation on its buffers.

const (
	// EffectReadOnly denotes an operation that reads inputs and produces a distinct output buffer.
	EffectReadOnly StorageEffect = iota
	// EffectMutating denotes an operation that mutates its target buffer in-place.
	EffectMutating
	// EffectInPlaceAlias denotes an operation that aliases an existing input buffer without allocation.
	EffectInPlaceAlias
)

func (StorageEffect) String

func (e StorageEffect) String() string

type Tensor

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

Tensor represents a deferred symbolic or device-backed tensor node in a computation DAG.

func NewConstant

func NewConstant(g *Graph, name string, shape []int, dtype DataType, values []float32) Tensor

NewConstant creates a constant tensor with fixed numerical values.

func NewInput

func NewInput(g *Graph, name string, shape []int, dtype DataType) Tensor

NewInput creates a new input tensor within the given graph.

func (Tensor) Add

func (t Tensor) Add(other Tensor) Tensor

Add computes elementwise addition t + other.

func (Tensor) DataType

func (t Tensor) DataType() DataType

DataType returns the tensor data type.

func (Tensor) Div

func (t Tensor) Div(other Tensor) Tensor

Div computes elementwise division t / other.

func (Tensor) Err

func (t Tensor) Err() error

Err returns the first error encountered during fluent tensor construction.

func (Tensor) Exp

func (t Tensor) Exp() Tensor

Exp computes elementwise exponential exp(t).

func (Tensor) Gelu

func (t Tensor) Gelu() Tensor

Gelu computes elementwise Gaussian Error Linear Unit activation.

func (Tensor) Graph

func (t Tensor) Graph() *Graph

Graph returns the underlying computation graph.

func (Tensor) Log

func (t Tensor) Log() Tensor

Log computes elementwise natural logarithm log(t).

func (Tensor) MarkOutput

func (t Tensor) MarkOutput() Tensor

MarkOutput explicitly marks this tensor as a required graph output.

func (Tensor) MatMul

func (t Tensor) MatMul(w Tensor) Tensor

MatMul computes matrix multiplication t x w.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/ir/graph"
)

func main() {
	g := graph.NewGraph()
	x := graph.NewInput(g, "X", []int{2, 3}, graph.Float32)
	w := graph.NewInput(g, "W", []int{3, 4}, graph.Float32)

	y := x.MatMul(w).Relu()
	if err := y.Err(); err != nil {
		panic(err)
	}

	fmt.Printf("shape: %v, op: %s\n", y.Shape(), y.Node().Op)
}
Output:
shape: [2 4], op: relu

func (Tensor) Mul

func (t Tensor) Mul(other Tensor) Tensor

Mul computes elementwise multiplication t * other.

func (Tensor) Neg

func (t Tensor) Neg() Tensor

Neg computes elementwise negation -t.

func (Tensor) Node

func (t Tensor) Node() *Node

Node returns the underlying IR node.

func (Tensor) RMSNorm

func (t Tensor) RMSNorm(weight Tensor, eps float32) Tensor

RMSNorm computes Root Mean Square layer normalization x * w / sqrt(mean(x^2) + eps).

func (Tensor) ReduceMax

func (t Tensor) ReduceMax(axis int) Tensor

ReduceMax computes reduction maximum along axis.

func (Tensor) ReduceSum

func (t Tensor) ReduceSum(axis int) Tensor

ReduceSum computes reduction sum along axis.

func (Tensor) Relu

func (t Tensor) Relu() Tensor

Relu computes elementwise rectified linear activation max(0, t).

func (Tensor) Reshape

func (t Tensor) Reshape(newShape []int) Tensor

Reshape changes the tensor extents without changing total elements.

func (Tensor) RoPE

func (t Tensor) RoPE(pos Tensor, theta float32) Tensor

RoPE computes Rotary Position Embedding on query/key tensors.

func (Tensor) Shape

func (t Tensor) Shape() []int

Shape returns the tensor dimensions.

func (Tensor) Silu

func (t Tensor) Silu() Tensor

Silu computes elementwise sigmoid linear unit (swish activation) x * sigmoid(x).

func (Tensor) Slice

func (t Tensor) Slice(starts, ends, steps []int) Tensor

Slice extracts a hyper-rectangular sub-tensor.

func (Tensor) Sqrt

func (t Tensor) Sqrt() Tensor

Sqrt computes elementwise square root sqrt(t).

func (Tensor) Sub

func (t Tensor) Sub(other Tensor) Tensor

Sub computes elementwise subtraction t - other.

func (Tensor) Transpose

func (t Tensor) Transpose(perm []int) Tensor

Transpose permutes tensor axes.

type TensorInfo

type TensorInfo struct {
	Name     string
	Elements uint64
	Weight   bool
}

TensorInfo contains tensor-size and weight metadata used by SOL analysis.

type TypedEmitter

type TypedEmitter interface {
	InputType() string
	ParamsType() string
	ComputeType() string
}

TypedEmitter allows an emitter to customize C++ scalar and vector types.

type Unit

type Unit struct {
	Source      string
	Symbols     []string
	FwdCtxBytes int
	ShmemBytes  int
}

Unit carries concatenated device code, emitted symbol names, and resource requirements.

func EmitBackwardTree

func EmitBackwardTree(root BackwardEmitter, name string, nThreads int, mode GradientMode) (Unit, error)

EmitBackwardTree emits backward device functions for a tree. Shared-memory demand is queried from each backward emitter for the requested launch shape.

func EmitTree

func EmitTree(root Emitter, name string) (Unit, error)

EmitTree walks the emitter tree, verifies adjacent width agreement in Go, generates unique nested symbol names, and returns a concatenated Unit.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/ir/graph"
)

type exampleLayer struct {
	name     string
	inWidth  int
	outWidth int
}

func (l *exampleLayer) Name() string                  { return l.name }
func (l *exampleLayer) InputWidth() int               { return l.inWidth }
func (l *exampleLayer) OutputWidth() int              { return l.outWidth }
func (l *exampleLayer) PaddedOutputWidth() int        { return l.outWidth }
func (l *exampleLayer) FwdCtxBytes() (int, error)     { return 0, nil }
func (l *exampleLayer) FwdCtxAlignedPerElement() bool { return true }
func (l *exampleLayer) EmitForward(name string) (string, error) {
	return graph.EmitFromBody(l, name, "\treturn input;")
}

func main() {
	layer := &exampleLayer{name: "linear", inWidth: 8, outWidth: 8}
	unit, err := graph.EmitTree(layer, "eval_root")
	if err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}
	fmt.Printf("symbols: %v\n", unit.Symbols)
}
Output:
symbols: [eval_root]

type Use

type Use int

A Use says what a lowering does with one fact.

const (
	// Lowered means the lowering reads the fact and accepts any valid value.
	Lowered Use = iota + 1
	// Ignored means the fact cannot change what the lowering produces, for
	// example a checkpoint tensor name in a lowering that binds weights by
	// slot. Cap.Why must say why.
	Ignored
	// Refused means the lowering accepts only the values in Cap.Allow. A
	// refused pointer fact must be nil.
	Refused
)

type Visit

type Visit struct {
	Ordinal int `json:"ordinal"`
	Layer   int `json:"layer"`
	KVSlot  int `json:"kv_slot"`
}

A Visit binds one step of a model's execution schedule to a physical layer in Model.Layers and an explicit KV cache slot. Repeated visits to the same physical layer share its weights and use distinct KV slots.

Jump to

Keyboard shortcuts

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