Documentation
¶
Index ¶
- Constants
- Variables
- func ApplyDispatchConfig()
- func Cost(n *IRNode) int
- func FindCommonSubexpressions(root *IRNode) map[*IRNode][]*IRNode
- func Finite32(v float32) bool
- func Finite64(v float64) bool
- func InitMathDispatch(useSIMD bool)
- func ResolveBackend(typeName string, vectorCount int) mathutil.Backend
- func SetDispatchMode(m DispatchMode)
- func SetDispatchThresholds(t DispatchThresholds)
- func SetMathImpl(impl MathImpl)
- func ShouldDispatchBatchAMX(batchSize int) bool
- type CPUHardwareProfile
- type Contract
- type DispatchMode
- type DispatchThresholds
- type Dtype
- type EinsumOp
- type Executor
- type Graph
- type IRNode
- func NewConstant(t *Tensor) *IRNode
- func NewContract(a, b *IRNode, sumLabels, outLabels []string) *IRNode
- func NewElementwise(op string, args ...*IRNode) *IRNode
- func NewInput(idx int, dtype Dtype, shape Shape) *IRNode
- func NewReduce(a *IRNode, axis int, op string) *IRNode
- func NewReshape(a *IRNode, shape Shape) *IRNode
- func NewTranspose(a *IRNode, perm []int) *IRNode
- type MathImpl
- type OpKind
- type Optimizer
- type Path
- type RewriteRule
- type Shape
- type Strides
- type Tensor
- func Acos(a *Tensor) (*Tensor, error)
- func Add(a, b *Tensor) (*Tensor, error)
- func Asin(a *Tensor) (*Tensor, error)
- func Atan(a *Tensor) (*Tensor, error)
- func ChristoffelSymbols(metric, metricDeriv *Tensor) (*Tensor, error)
- func Cos(a *Tensor) (*Tensor, error)
- func Cosh(a *Tensor) (*Tensor, error)
- func Div(a, b *Tensor) (*Tensor, error)
- func Einsum(expr string, tensors ...*Tensor) (*Tensor, error)
- func Erf(a *Tensor) (*Tensor, error)
- func Exp(a *Tensor) (*Tensor, error)
- func InvertMetric2D(metric *Tensor) (*Tensor, error)
- func LeviCivita(dim int, dt Dtype) (*Tensor, error)
- func Log(a *Tensor) (*Tensor, error)
- func MatMul(a, b *Tensor) (*Tensor, error)
- func MetricLower(t *Tensor, metric *Tensor, axis int) (*Tensor, error)
- func MetricRaise(t *Tensor, metricInv *Tensor, axis int) (*Tensor, error)
- func Mul(a, b *Tensor) (*Tensor, error)
- func Neg(a *Tensor) (*Tensor, error)
- func New(dtype Dtype, shape Shape) *Tensor
- func NewFromData(dtype Dtype, shape Shape, data []byte) *Tensor
- func Pow(a, b *Tensor) (*Tensor, error)
- func ReduceSum(a *Tensor, axis int) (*Tensor, error)
- func Reshape(a *Tensor, shape Shape) *Tensor
- func RicciScalar(ricci, metricInv *Tensor) (*Tensor, error)
- func RicciTensor(riemann *Tensor) (*Tensor, error)
- func RiemannCurvature(christoffel, christoffelDeriv *Tensor) (*Tensor, error)
- func Sin(a *Tensor) (*Tensor, error)
- func Sinh(a *Tensor) (*Tensor, error)
- func Sqrt(a *Tensor) (*Tensor, error)
- func Sub(a, b *Tensor) (*Tensor, error)
- func Tan(a *Tensor) (*Tensor, error)
- func Tanh(a *Tensor) (*Tensor, error)
- func TensorContract(a, b *Tensor, sumLabels, outLabels []string) (*Tensor, error)
- func Transpose(a *Tensor, perm []int) (*Tensor, error)
- func WedgeProduct(formA, formB *Tensor) (*Tensor, error)
- func (t *Tensor) At(indices ...int) unsafe.Pointer
- func (t *Tensor) Clone() *Tensor
- func (t *Tensor) Complex64s() []complex64
- func (t *Tensor) Complex128s() []complex128
- func (t *Tensor) Data() []byte
- func (t *Tensor) Diagonal(axis1, axis2 int) (*Tensor, error)
- func (t *Tensor) Dtype() Dtype
- func (t *Tensor) Float32s() []float32
- func (t *Tensor) Float64s() []float64
- func (t *Tensor) Int8s() []int8
- func (t *Tensor) Int32s() []int32
- func (t *Tensor) Int64s() []int64
- func (t *Tensor) IsContiguous() bool
- func (t *Tensor) Labels() []string
- func (t *Tensor) NumElements() int
- func (t *Tensor) Rank() int
- func (t *Tensor) Reshape(shape Shape) *Tensor
- func (t *Tensor) SetLabels(labels []string)
- func (t *Tensor) Shape() Shape
- func (t *Tensor) Slice(axes map[int]int) *Tensor
- func (t *Tensor) Strides() Strides
- func (t *Tensor) Trace(axis1, axis2 int) (*Tensor, error)
- func (t *Tensor) Uint8s() []uint8
Constants ¶
const DefaultComplex128EMLMaxCount = 500000
DefaultComplex128EMLMaxCount is the baseline count where auto mode routes complex128 to emlgo before standard math takes over.
const DefaultComplex64EMLMaxCount = 250000
DefaultComplex64EMLMaxCount is the baseline count where auto mode still routes complex64 to emlgo.
const DefaultMinEMLVectorCount = 50000
DefaultMinEMLVectorCount is the baseline minimum vector count before auto mode routes any type to emlgo.
const DefaultTurboQuantEMLMinCount = 50000
DefaultTurboQuantEMLMinCount is the baseline count for TurboQuant EMLGo dispatch.
const MinEMLVectorCount = DefaultMinEMLVectorCount
MinEMLVectorCount mirrors the emlgo build threshold (kept in sync for tests).
Variables ¶
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 ¶
Cost estimates the computational cost of a node in FLOPs. Used by the auto-scheduler to decide CPU vs GPU placement.
func FindCommonSubexpressions ¶
FindCommonSubexpressions detects identical subgraphs and returns a mapping from canonical node to list of equivalent nodes (CSE).
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 ¶
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 ¶
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.
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 ¶
ParseEinsum parses an Einstein summation string like "ij,jk->ik".
func (*EinsumOp) InferOutputShape ¶
InferOutputShape computes the output shape from an EinsumOp and input shapes.
func (*EinsumOp) OptimizePath ¶
OptimizePath uses greedy search to find a contraction order minimizing FLOPs.
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.
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 ¶
NewConstant creates an IR leaf node for a constant tensor.
func NewContract ¶
NewContract creates a contraction node (einsum-style).
func NewElementwise ¶
NewElementwise creates an element-wise operation node.
func NewReshape ¶
NewReshape creates a reshape node.
func NewTranspose ¶
NewTranspose creates a transpose node.
func (*IRNode) Labels ¶
Labels returns the index labels for this node (used for contraction matching).
func (*IRNode) NumElements ¶
NumElements returns the total number of elements.
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
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 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 ChristoffelSymbols ¶
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 Einsum ¶
Einsum evaluates an Einstein summation expression on the given tensors. Supports multi-tensor contractions, permutations, reductions, diagonals ("ii->i"), and trace ("ii->").
func InvertMetric2D ¶
InvertMetric2D computes the matrix inverse of a rank-2 metric tensor g_ab -> g^ab.
func LeviCivita ¶
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 MatMul ¶
MatMul performs matrix multiplication (2D tensor contraction over the last axis of a and second-to-last of b).
func MetricLower ¶
MetricLower lowers a contravariant index on tensor T at `axis` using metric g_{mu nu}: T^{...mu...} g_{mu nu} -> T^{...}_{...nu...}
func MetricRaise ¶
MetricRaise raises a covariant index on tensor T at `axis` using inverse metric g^{mu nu}: T_{...mu...} g^{mu nu} -> T_{...}^{...nu...}
func New ¶
New creates a new tensor with the given dtype and shape, backed by a freshly allocated buffer.
func NewFromData ¶
NewFromData creates a tensor wrapping existing data. The caller must ensure data's length matches the expected size (product(shape) * dtype.Size()).
func RicciScalar ¶
RicciScalar contracts the Ricci tensor with the inverse metric to compute the Ricci curvature scalar: R = g^{sigma nu} R_{sigma nu}
func RicciTensor ¶
RicciTensor contracts the Riemann curvature tensor to obtain the Ricci tensor: R_{sigma nu} = R^mu_{sigma mu nu}
func RiemannCurvature ¶
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 TensorContract ¶
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 WedgeProduct ¶
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 ¶
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) Complex64s ¶
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) Diagonal ¶
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) Float32s ¶
Float32s returns the data as a float32 slice. Panics if dtype is not Float32.
func (*Tensor) Float64s ¶
Float64s returns the data as a float64 slice. Panics if dtype is not Float64.
func (*Tensor) IsContiguous ¶
IsContiguous returns true if the tensor is stored contiguously.
func (*Tensor) NumElements ¶
NumElements returns the total number of scalar elements.
func (*Tensor) Reshape ¶
Reshape returns a new view with the given shape if the total number of elements matches.
func (*Tensor) Shape ¶
Shape returns the shape of the tensor (aliases the internal slice; do not mutate).
func (*Tensor) Slice ¶
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].