tensor

package
v0.2.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: Unlicense Imports: 11 Imported by: 0 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

Index

Constants

View Source
const DefaultComplex128EMLMaxCount = 500000

DefaultComplex128EMLMaxCount is the baseline count where auto mode routes complex128 to emlgo before standard math takes over.

View Source
const DefaultComplex64EMLMaxCount = 250000

DefaultComplex64EMLMaxCount is the baseline count where auto mode still routes complex64 to emlgo.

View Source
const DefaultMinEMLVectorCount = 50000

DefaultMinEMLVectorCount is the baseline minimum vector count before auto mode routes any type to emlgo.

View Source
const DefaultTurboQuantEMLMinCount = 50000

DefaultTurboQuantEMLMinCount is the baseline count for TurboQuant EMLGo dispatch.

View Source
const MinEMLVectorCount = DefaultMinEMLVectorCount

MinEMLVectorCount mirrors the emlgo build threshold (kept in sync for tests).

Variables

View Source
var (
	TensorOperationsTotal = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "longbow_tensor_operations_total",
			Help: "Total number of tensor calculus operations executed",
		},
		[]string{"op", "device", "dtype"},
	)

	TensorOperationDurationSeconds = promauto.NewHistogramVec(
		prometheus.HistogramOpts{
			Name:    "longbow_tensor_operation_duration_seconds",
			Help:    "Execution duration of tensor calculus operations in seconds",
			Buckets: prometheus.DefBuckets,
		},
		[]string{"op", "device"},
	)

	TensorBytesProcessedTotal = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "longbow_tensor_bytes_processed_total",
			Help: "Total bytes processed during tensor operations",
		},
		[]string{"op"},
	)

	TensorOptimizerPassesTotal = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "longbow_tensor_optimizer_passes_total",
			Help: "Total number of optimization rewrite passes applied to tensor DAGs",
		},
		[]string{"rule"},
	)

	TensorOptimizerFlopsSavedTotal = promauto.NewCounter(
		prometheus.CounterOpts{
			Name: "longbow_tensor_optimizer_flops_saved_total",
			Help: "Estimated floating-point operations saved by tensor DAG optimizations",
		},
	)
)

Functions

func ApplyDispatchConfig

func ApplyDispatchConfig()

ApplyDispatchConfig reads LONGBOW_MATH_DISPATCH and hardware features to configure math thresholds and backend.

func Cost

func Cost(n *IRNode) int

Cost estimates the computational cost of a node in FLOPs. Used by the auto-scheduler to decide CPU vs GPU placement.

func FindCommonSubexpressions

func FindCommonSubexpressions(root *IRNode) map[*IRNode][]*IRNode

FindCommonSubexpressions detects identical subgraphs and returns a mapping from canonical node to list of equivalent nodes (CSE).

func Finite32

func Finite32(v float32) bool

Finite checks if a float32 value is finite (non-NaN, non-Inf).

func Finite64

func Finite64(v float64) bool

Finite64 checks if a float64 value is finite.

func InitMathDispatch

func InitMathDispatch(useSIMD bool)

InitMathDispatch selects the best available math kernel implementation. Call once at startup after CPU feature detection. Without the "emlgo" build tag, SIMD mode defaults to standard math.

func ResolveBackend

func ResolveBackend(typeName string, vectorCount int) mathutil.Backend

ResolveBackend selects the math backend for a given data type and vector count. Without the emlgo build tag, all modes fall through to BackendStandard.

func SetDispatchMode

func SetDispatchMode(m DispatchMode)

SetDispatchMode sets the dispatch mode. Without the emlgo build tag this only records the mode; the math backend is always standard.

func SetDispatchThresholds

func SetDispatchThresholds(t DispatchThresholds)

SetDispatchThresholds sets the active dispatch thresholds.

func SetMathImpl

func SetMathImpl(impl MathImpl)

SetMathImpl switches between MathGo, MathSIMD, and MathEML. Without the "emlgo" build tag, MathEML falls through to MathSIMD.

func ShouldDispatchBatchAMX

func ShouldDispatchBatchAMX(batchSize int) bool

ShouldDispatchBatchAMX returns true if host CPU supports Intel AMX and the batch size B >= 32 (Item 41).

Types

type CPUHardwareProfile

type CPUHardwareProfile struct {
	HasAVX512     bool
	HasAVX512VNNI bool
	HasAMX        bool
	L2CacheBytes  int
	L3CacheBytes  int
}

CPUHardwareProfile captures the hardware traits used to calibrate dispatch thresholds.

func DetectHardwareProfile

func DetectHardwareProfile() CPUHardwareProfile

DetectHardwareProfile inspects the host CPU for vector extensions and cache topology.

type Contract

type Contract struct {
	LHS       int      // index into operand list
	RHS       int      // index into operand list
	SumLabels []string // labels being summed (contracted)
	OutLabels []string // labels in the output
}

Contract describes a pairwise tensor contraction.

type DispatchMode

type DispatchMode int

DispatchMode controls which math backend is used.

const (
	// DispatchAuto uses empirical routing rules based on data type and scale.
	DispatchAuto DispatchMode = iota
	// DispatchEML forces emlgo for all operations.
	DispatchEML
	// DispatchStandard forces standard math for all operations.
	DispatchStandard
)

func GetDispatchMode

func GetDispatchMode() DispatchMode

GetDispatchMode returns the current dispatch mode.

func ParseDispatchMode

func ParseDispatchMode(val string) DispatchMode

ParseDispatchMode parses a LONGBOW_MATH_DISPATCH env var value.

type DispatchThresholds

type DispatchThresholds struct {
	MinEMLVectorCount     int
	Complex64EMLMaxCount  int
	Complex128EMLMaxCount int
	TurboQuantEMLMinCount int
}

DispatchThresholds specifies the calibrated vector count cutoffs for math dispatch.

func CalibrateThresholds

func CalibrateThresholds(profile CPUHardwareProfile) DispatchThresholds

CalibrateThresholds computes dynamic, hardware-aware dispatch thresholds based on CPU instruction set extensions (AVX-512, VNNI, AMX) and L2/L3 cache sizes.

func DefaultThresholds

func DefaultThresholds() DispatchThresholds

DefaultThresholds returns the uncalibrated baseline thresholds.

func GetDispatchThresholds

func GetDispatchThresholds() DispatchThresholds

GetDispatchThresholds returns the current active dispatch thresholds.

type Dtype

type Dtype uint8

Dtype represents the element type of a tensor.

const (
	DtypeInvalid Dtype = iota
	DtypeFloat32
	DtypeFloat64
	DtypeInt8
	DtypeUint8
	DtypeInt16
	DtypeUint16
	DtypeInt32
	DtypeUint32
	DtypeInt64
	DtypeUint64
	DtypeFloat16
	DtypeComplex64
	DtypeComplex128
)

func Promote

func Promote(a, b Dtype) Dtype

Promote returns the dtype for binary operations (e.g. float32+int32 -> float32).

func (Dtype) IsComplex

func (d Dtype) IsComplex() bool

func (Dtype) IsFloat

func (d Dtype) IsFloat() bool

func (Dtype) IsInt

func (d Dtype) IsInt() bool

func (Dtype) IsUint

func (d Dtype) IsUint() bool

func (Dtype) Size

func (d Dtype) Size() int

func (Dtype) String

func (d Dtype) String() string

type EinsumOp

type EinsumOp struct {
	Inputs     [][]string // index labels per input tensor
	Output     []string   // output index labels
	NumIndices int
}

EinsumOp describes a parsed Einstein summation operation.

func ParseEinsum

func ParseEinsum(expr string) (*EinsumOp, error)

ParseEinsum parses an Einstein summation string like "ij,jk->ik".

func (*EinsumOp) InferOutputShape

func (op *EinsumOp) InferOutputShape(shapes []Shape) Shape

InferOutputShape computes the output shape from an EinsumOp and input shapes.

func (*EinsumOp) OptimizePath

func (op *EinsumOp) OptimizePath(shapes []Shape) *Path

OptimizePath uses greedy search to find a contraction order minimizing FLOPs.

func (*EinsumOp) Validate

func (op *EinsumOp) Validate(shapes []Shape) error

Validate checks that an EinsumOp is valid for the given tensor shapes.

type Executor

type Executor struct {
	GPUThreshold int // minimum number of elements to consider GPU offload
	// contains filtered or unexported fields
}

Executor executes a tensor IR graph against concrete input tensors.

func NewExecutor

func NewExecutor() *Executor

NewExecutor creates an executor with default settings.

func (*Executor) Run

func (e *Executor) Run(g *Graph, inputs []*Tensor) (*Tensor, error)

Run evaluates a tensor graph with the given input tensors. inputs[i] must correspond to IRNode with InputIdx == i.

func (*Executor) SetGPU

func (e *Executor) SetGPU(enabled bool)

SetGPU enables or disables GPU offload.

type Graph

type Graph struct {
	Root  *IRNode
	Input []*IRNode // leaf input nodes in order
}

Graph holds a tensor expression DAG.

func NewGraph

func NewGraph(root *IRNode) *Graph

NewGraph creates a graph from a root node.

type IRNode

type IRNode struct {
	Kind     OpKind
	Dtype    Dtype
	Shape    Shape
	Children []*IRNode

	// OpContract
	SumLabels []string // indices being contracted
	OutLabels []string // output index order

	// OpTranspose
	Perm []int // new axis order

	// OpReduce
	ReduceAxis int
	ReduceOp   string // "sum", "max", "min"

	// OpElementwise
	ElemOp string // "add", "mul", "sub", "div", "sin", "cos", "tan", "exp", "log", "neg", "pow"

	// OpInput / OpConstant
	InputIdx int     // index into input tensor list
	ConstVal *Tensor // constant tensor value
}

IRNode is a node in the tensor expression DAG.

func NewConstant

func NewConstant(t *Tensor) *IRNode

NewConstant creates an IR leaf node for a constant tensor.

func NewContract

func NewContract(a, b *IRNode, sumLabels, outLabels []string) *IRNode

NewContract creates a contraction node (einsum-style).

func NewElementwise

func NewElementwise(op string, args ...*IRNode) *IRNode

NewElementwise creates an element-wise operation node.

func NewInput

func NewInput(idx int, dtype Dtype, shape Shape) *IRNode

NewInput creates an IR leaf node for an input tensor.

func NewReduce

func NewReduce(a *IRNode, axis int, op string) *IRNode

NewReduce creates a reduction node.

func NewReshape

func NewReshape(a *IRNode, shape Shape) *IRNode

NewReshape creates a reshape node.

func NewTranspose

func NewTranspose(a *IRNode, perm []int) *IRNode

NewTranspose creates a transpose node.

func (*IRNode) Labels

func (n *IRNode) Labels() []string

Labels returns the index labels for this node (used for contraction matching).

func (*IRNode) NumElements

func (n *IRNode) NumElements() int

NumElements returns the total number of elements.

func (*IRNode) Rank

func (n *IRNode) Rank() int

Rank returns the number of axes.

func (*IRNode) String

func (n *IRNode) String() string

String returns a human-readable representation.

type MathImpl

type MathImpl int

MathImpl identifies which math kernel implementation to use.

const (
	MathGo   MathImpl = iota // pure Go fallback (Taylor series, Newton)
	MathSIMD                 // Standard SIMD-accelerated kernels wrapping math.*
	MathEML                  // High-performance EMLGo SIMD & fastmath (no-op without emlgo tag)
)

func GetMathImpl

func GetMathImpl() MathImpl

GetMathImpl returns the active math implementation.

type OpKind

type OpKind int

OpKind identifies the kind of tensor operation.

const (
	OpContract    OpKind = iota // tensor contraction (sum over shared indices)
	OpTranspose                 // axis permutation
	OpReshape                   // shape change (no data movement)
	OpElementwise               // element-wise unary/binary operation
	OpReduce                    // reduction along axis (sum, max, min)
	OpConstant                  // constant tensor (leaf)
	OpInput                     // input tensor (leaf)
)

type Optimizer

type Optimizer struct {
	Rules []RewriteRule
}

Optimizer rewrites a tensor IR graph for efficiency.

func NewOptimizer

func NewOptimizer() *Optimizer

func (*Optimizer) Optimize

func (opt *Optimizer) Optimize(g *Graph) *Graph

Optimize applies algebraic rewrite rules and CSE to simplify a graph.

type Path

type Path struct {
	Contracts []Contract
	Final     []string // output label order
}

Path represents a sequence of pairwise contractions (an einsum path).

type RewriteRule

type RewriteRule int

RewriteRule identifies a transformation on the IR.

const (
	RuleNone                 RewriteRule = iota
	RuleMulByZero                        // A * 0 -> 0
	RuleAddZero                          // A + 0 -> A
	RuleDoubleNeg                        // -(-A) -> A
	RuleTransposeOfTranspose             // T(T(A)) -> A
	RuleReshapeOfReshape                 // R(R(A)) -> A (if shapes allow)
	RuleExpOfLog                         // exp(log(A)) -> A (domain permitting)
	RuleLogOfExp                         // log(exp(A)) -> A
	RuleConstantFolding                  // Op(Const, Const) -> Const
	RuleCSE                              // Common Subexpression Elimination
)

type Shape

type Shape []int

Shape describes the size of each axis in a tensor.

type Strides

type Strides []int

Strides describes the byte offset between consecutive elements along each axis.

type Tensor

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

Tensor is a multi-dimensional array with typed elements.

func Acos

func Acos(a *Tensor) (*Tensor, error)

Acos computes element-wise arccosine.

func Add

func Add(a, b *Tensor) (*Tensor, error)

Add performs element-wise addition.

func Asin

func Asin(a *Tensor) (*Tensor, error)

Asin computes element-wise arcsine.

func Atan

func Atan(a *Tensor) (*Tensor, error)

Atan computes element-wise arctangent.

func ChristoffelSymbols

func ChristoffelSymbols(metric, metricDeriv *Tensor) (*Tensor, error)

ChristoffelSymbols computes Christoffel connection coefficients of the second kind: Gamma^sigma_{mu nu} = 0.5 * g^{sigma rho} * (d_mu g_{nu rho} + d_nu g_{mu rho} - d_rho g_{mu nu}) metric has shape [D, D] (g_ab) metricDeriv has shape [D, D, D] representing d_rho g_{mu nu} (axis 0: derivative coord rho, axis 1: mu, axis 2: nu)

func Cos

func Cos(a *Tensor) (*Tensor, error)

Cos computes element-wise cosine.

func Cosh

func Cosh(a *Tensor) (*Tensor, error)

Cosh computes element-wise hyperbolic cosine.

func Div

func Div(a, b *Tensor) (*Tensor, error)

Div performs element-wise division.

func Einsum

func Einsum(expr string, tensors ...*Tensor) (*Tensor, error)

Einsum evaluates an Einstein summation expression on the given tensors. Supports multi-tensor contractions, permutations, reductions, diagonals ("ii->i"), and trace ("ii->").

func Erf

func Erf(a *Tensor) (*Tensor, error)

Erf computes the error function element-wise.

func Exp

func Exp(a *Tensor) (*Tensor, error)

Exp computes element-wise exponential.

func InvertMetric2D

func InvertMetric2D(metric *Tensor) (*Tensor, error)

InvertMetric2D computes the matrix inverse of a rank-2 metric tensor g_ab -> g^ab.

func LeviCivita

func LeviCivita(dim int, dt Dtype) (*Tensor, error)

LeviCivita generates the totally antisymmetric Levi-Civita permutation tensor of rank `dim`. For dim=3, it produces the standard 3D permutation tensor epsilon_ijk. For dim=4, it produces the 4D relativistic permutation tensor epsilon_mu_nu_rho_sigma.

func Log

func Log(a *Tensor) (*Tensor, error)

Log computes element-wise natural logarithm.

func MatMul

func MatMul(a, b *Tensor) (*Tensor, error)

MatMul performs matrix multiplication (2D tensor contraction over the last axis of a and second-to-last of b).

func MetricLower

func MetricLower(t *Tensor, metric *Tensor, axis int) (*Tensor, error)

MetricLower lowers a contravariant index on tensor T at `axis` using metric g_{mu nu}: T^{...mu...} g_{mu nu} -> T^{...}_{...nu...}

func MetricRaise

func MetricRaise(t *Tensor, metricInv *Tensor, axis int) (*Tensor, error)

MetricRaise raises a covariant index on tensor T at `axis` using inverse metric g^{mu nu}: T_{...mu...} g^{mu nu} -> T_{...}^{...nu...}

func Mul

func Mul(a, b *Tensor) (*Tensor, error)

Mul performs element-wise multiplication.

func Neg

func Neg(a *Tensor) (*Tensor, error)

Neg performs element-wise negation.

func New

func New(dtype Dtype, shape Shape) *Tensor

New creates a new tensor with the given dtype and shape, backed by a freshly allocated buffer.

func NewFromData

func NewFromData(dtype Dtype, shape Shape, data []byte) *Tensor

NewFromData creates a tensor wrapping existing data. The caller must ensure data's length matches the expected size (product(shape) * dtype.Size()).

func Pow

func Pow(a, b *Tensor) (*Tensor, error)

Pow computes a raised to the power of b element-wise.

func ReduceSum

func ReduceSum(a *Tensor, axis int) (*Tensor, error)

ReduceSum sums a tensor along an axis.

func Reshape

func Reshape(a *Tensor, shape Shape) *Tensor

Reshape returns a tensor with a new shape (same data, view semantics).

func RicciScalar

func RicciScalar(ricci, metricInv *Tensor) (*Tensor, error)

RicciScalar contracts the Ricci tensor with the inverse metric to compute the Ricci curvature scalar: R = g^{sigma nu} R_{sigma nu}

func RicciTensor

func RicciTensor(riemann *Tensor) (*Tensor, error)

RicciTensor contracts the Riemann curvature tensor to obtain the Ricci tensor: R_{sigma nu} = R^mu_{sigma mu nu}

func RiemannCurvature

func RiemannCurvature(christoffel, christoffelDeriv *Tensor) (*Tensor, error)

RiemannCurvature computes the Riemann curvature tensor: R^rho_{sigma mu nu} = d_mu Gamma^rho_{nu sigma} - d_nu Gamma^rho_{mu sigma}

  • Gamma^rho_{mu lambda} Gamma^lambda_{nu sigma} - Gamma^rho_{nu lambda} Gamma^lambda_{mu sigma}

christoffel has shape [D, D, D] (indices: rho, mu, nu) christoffelDeriv has shape [D, D, D, D] (axis 0: derivative coord lambda, axes 1..3: rho, mu, nu)

func Sin

func Sin(a *Tensor) (*Tensor, error)

Sin computes element-wise sine.

func Sinh

func Sinh(a *Tensor) (*Tensor, error)

Sinh computes element-wise hyperbolic sine.

func Sqrt

func Sqrt(a *Tensor) (*Tensor, error)

Sqrt computes element-wise square root.

func Sub

func Sub(a, b *Tensor) (*Tensor, error)

Sub performs element-wise subtraction.

func Tan

func Tan(a *Tensor) (*Tensor, error)

Tan computes element-wise tangent.

func Tanh

func Tanh(a *Tensor) (*Tensor, error)

Tanh computes element-wise hyperbolic tangent.

func TensorContract

func TensorContract(a, b *Tensor, sumLabels, outLabels []string) (*Tensor, error)

TensorContract performs a tensor contraction (einsum-style) on two tensors. sumLabels are the index names to contract over; outLabels are the output index order.

func Transpose

func Transpose(a *Tensor, perm []int) (*Tensor, error)

Transpose permutes the axes of a tensor.

func WedgeProduct

func WedgeProduct(formA, formB *Tensor) (*Tensor, error)

WedgeProduct computes the exterior differential wedge product of a p-form and a q-form (A ^ B). For 1-forms A and B of dimension D, (A ^ B)_ij = A_i B_j - A_j B_i. In general for forms of rank p and q, the result has rank p + q and is fully antisymmetrized.

func (*Tensor) At

func (t *Tensor) At(indices ...int) unsafe.Pointer

At returns a reference to the element at the given indices. The returned pointer is valid only as long as the tensor is alive.

func (*Tensor) Clone

func (t *Tensor) Clone() *Tensor

Clone creates a deep copy of the tensor.

func (*Tensor) Complex64s

func (t *Tensor) Complex64s() []complex64

Complex64s returns the data as a complex64 slice. Panics if dtype is not Complex64.

func (*Tensor) Complex128s

func (t *Tensor) Complex128s() []complex128

Complex128s returns the data as a complex128 slice. Panics if dtype is not Complex128.

func (*Tensor) Data

func (t *Tensor) Data() []byte

Data returns the backing byte slice.

func (*Tensor) Diagonal

func (t *Tensor) Diagonal(axis1, axis2 int) (*Tensor, error)

Diagonal extracts the diagonal along two axes where axis1 == axis2. The two axes must have matching dimension sizes and are collapsed into a single axis at the end.

func (*Tensor) Dtype

func (t *Tensor) Dtype() Dtype

Dtype returns the element data type.

func (*Tensor) Float32s

func (t *Tensor) Float32s() []float32

Float32s returns the data as a float32 slice. Panics if dtype is not Float32.

func (*Tensor) Float64s

func (t *Tensor) Float64s() []float64

Float64s returns the data as a float64 slice. Panics if dtype is not Float64.

func (*Tensor) Int8s

func (t *Tensor) Int8s() []int8

Int8s returns the data as an int8 slice. Panics if dtype is not Int8.

func (*Tensor) Int32s

func (t *Tensor) Int32s() []int32

Int32s returns the data as an int32 slice. Panics if dtype is not Int32.

func (*Tensor) Int64s

func (t *Tensor) Int64s() []int64

Int64s returns the data as an int64 slice. Panics if dtype is not Int64.

func (*Tensor) IsContiguous

func (t *Tensor) IsContiguous() bool

IsContiguous returns true if the tensor is stored contiguously.

func (*Tensor) Labels

func (t *Tensor) Labels() []string

Labels returns optional axis labels. May be nil.

func (*Tensor) NumElements

func (t *Tensor) NumElements() int

NumElements returns the total number of scalar elements.

func (*Tensor) Rank

func (t *Tensor) Rank() int

Rank returns the number of axes.

func (*Tensor) Reshape

func (t *Tensor) Reshape(shape Shape) *Tensor

Reshape returns a new view with the given shape if the total number of elements matches.

func (*Tensor) SetLabels

func (t *Tensor) SetLabels(labels []string)

SetLabels sets axis labels for Einstein notation.

func (*Tensor) Shape

func (t *Tensor) Shape() Shape

Shape returns the shape of the tensor (aliases the internal slice; do not mutate).

func (*Tensor) Slice

func (t *Tensor) Slice(axes map[int]int) *Tensor

Slice creates a zero-copy view selecting a single index along each specified axis. axes maps axis index -> index to select. Axes not present keep their full range. The returned tensor shares the backing data with the original when the resulting slice is contiguous; otherwise it copies. Example: Slice(map[int]int{0: 1}) on a 3×4 tensor selects row 1 → shape [4].

func (*Tensor) Strides

func (t *Tensor) Strides() Strides

Strides computes the byte strides for a contiguous row-major tensor.

func (*Tensor) Trace

func (t *Tensor) Trace(axis1, axis2 int) (*Tensor, error)

Trace computes the tensor trace by summing along the diagonal of axis1 and axis2.

func (*Tensor) Uint8s

func (t *Tensor) Uint8s() []uint8

Uint8s returns the data as a uint8 (byte) slice. Panics if dtype is not Uint8.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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