gobackend

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: Apache-2.0 Imports: 24 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.

README

Go Backend

The "go" backend implements a simple, and not very fast, but very portable backend for GoMLX.

The priority is to make something that will work everywhere and is "ergonomic" (doesn't require installing any associated C/C++/Rust library, or special packages other than Go itself).

A second priority is having a very short dependency list: this aimed at being safe, very low dependency library.

See capabilities.go file to see operations that are implemented.

To Do's

This can be split into 2 parts: implement missing ops, and optimizations.

Missing Ops/Functionality

There are still many missing. See file capabilities.go. But feel free to create issues if there is an Op that you need and would like to see it prioritized.

Optimizations

The initial implementation was focused on portability and getting it to work.

But there are many relatively "low-hanging fruits" for optimization, a few obvious items:

  • Pre-calculate constant sub-expressions.
  • Fuse unary ops: it's much faster (for larger data blocks) to loop over the data only once and apply various functions than loop over the data many times, each time applying the unary function.
  • Fuse binary/unary ops: perform unary functions while traversing the data for binary functions. Again to save memory accesses.
  • Parallelization: in-operation, and across operations.
    • Only DotGeneral has been parallelized so far: it is usually the one that consumes most of the time.
  • Use intrinsics/SIMD on platforms that allow it. It was announced as experimental in Go 1.25.
  • Eliminate common sub-expressions.

Documentation

Overview

Package gobackend implements a compute.Backend using Go only.

Its main goal is portability, and not be a state-of-the art ML backend.

It also serves as a reference implementation for the compute.Backend interface.

It only implements the most popular dtypes and operations. But generally, it's easy to add new ops, if you need, just open an issue in GoMLX.

Index

Constants

View Source
const (
	// Bold enables the bold text style
	Bold = "\x1b[1m"
	// Reset clears all text formatting and colors back to default
	Reset = "\x1b[0m"
	// Blue enables the blue text style
	Blue = "\x1b[34m"
	// Green enables the green text style
	Green = "\x1b[32m"
	// Red enables the red text style
	Red = "\x1b[31m"
	// Underline enables the underline text style
	Underline = "\x1b[4m"
)
View Source
const BackendName = "go"

BackendName to be used in GOMLX_BACKEND to specify this backend.

View Source
const MaxDTypes = 32

Variables

View Source
var (

	// MultiOutputsNodeExecutors should be populated during initialization for the multi-output ops
	// implemented. E.g.: RNGBitGenerator.
	MultiOutputsNodeExecutors [compute.OpTypeLast]nodeMultiOutputExecutor

	// NodeClosureExecutors should be populated during initialization for ops that call closures.
	// E.g.: If, While, Sort.
	// These executors receive captured inputs separately with explicit ownership tracking.
	NodeClosureExecutors [compute.OpTypeLast]nodeClosureExecutor
)
View Source
var (
	RegisterAbs = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Abs",
	}
	RegisterAdd = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Add",
	}
	RegisterArgMinMax = OpHandlerRegistration[func(f *Function, x compute.Value, axis int, outputDType dtypes.DType, isMin bool) (compute.Value, error)]{
		Method: "ArgMinMax",
	}
	RegisterAtan2 = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Atan2",
	}
	RegisterBatchNormForInference = OpHandlerRegistration[func(f *Function, operand compute.Value, scale compute.Value, offset compute.Value, mean compute.Value, variance compute.Value, epsilon float32, featureAxis int) (compute.Value, error)]{
		Method: "BatchNormForInference",
	}
	RegisterBatchNormForTraining = OpHandlerRegistration[func(f *Function, operand compute.Value, scale compute.Value, offset compute.Value, epsilon float32, featureAxis int) (normalized compute.Value, batchMean compute.Value, batchVariance compute.Value, err error)]{
		Method: "BatchNormForTraining",
	}
	RegisterBatchNormGradient = OpHandlerRegistration[func(f *Function, operand compute.Value, scale compute.Value, mean compute.Value, variance compute.Value, gradOutput compute.Value, epsilon float32, featureAxis int) (gradOperand compute.Value, gradScale compute.Value, gradOffset compute.Value, err error)]{
		Method: "BatchNormGradient",
	}
	RegisterBitcast = OpHandlerRegistration[func(f *Function, operand compute.Value, targetDType dtypes.DType) (compute.Value, error)]{
		Method: "Bitcast",
	}
	RegisterBitCount = OpHandlerRegistration[func(f *Function, operand compute.Value) (compute.Value, error)]{
		Method: "BitCount",
	}
	RegisterBitwiseAnd = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "BitwiseAnd",
	}
	RegisterBitwiseNot = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "BitwiseNot",
	}
	RegisterBitwiseOr = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "BitwiseOr",
	}
	RegisterBitwiseXor = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "BitwiseXor",
	}
	RegisterBroadcastInDim = OpHandlerRegistration[func(f *Function, operand compute.Value, outputShape shapes.Shape, broadcastAxes []int) (compute.Value, error)]{
		Method: "BroadcastInDim",
	}
	RegisterCall = OpHandlerRegistration[func(f *Function, fn compute.Function, inputs ...compute.Value) ([]compute.Value, error)]{
		Method: "Call",
	}
	RegisterCeil = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Ceil",
	}
	RegisterClamp = OpHandlerRegistration[func(f *Function, min compute.Value, x compute.Value, max compute.Value) (compute.Value, error)]{
		Method: "Clamp",
	}
	RegisterClz = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Clz",
	}
	RegisterComplex = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Complex",
	}
	RegisterConcatenate = OpHandlerRegistration[func(f *Function, axis int, operands ...compute.Value) (compute.Value, error)]{
		Method: "Concatenate",
	}
	RegisterConj = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Conj",
	}
	RegisterConvertDType = OpHandlerRegistration[func(f *Function, x compute.Value, dtype dtypes.DType) (compute.Value, error)]{
		Method: "ConvertDType",
	}
	RegisterConvGeneral = OpHandlerRegistration[func(f *Function, input compute.Value, kernel compute.Value, axes compute.ConvolveAxesConfig, strides []int, paddings [][2]int, inputDilations []int, kernelDilations []int, channelGroupCount int, batchGroupCount int) (compute.Value, error)]{
		Method: "ConvGeneral",
	}
	RegisterCos = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Cos",
	}
	RegisterCumSum = OpHandlerRegistration[func(f *Function, operand compute.Value, axis int, options compute.CumSumOptions) (compute.Value, error)]{
		Method: "CumSum",
	}
	RegisterDiv = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Div",
	}
	RegisterDotGeneral = OpHandlerRegistration[func(f *Function, lhs compute.Value, lhsContractingAxes []int, lhsBatchAxes []int, rhs compute.Value, rhsContractingAxes []int, rhsBatchAxes []int, config compute.DotGeneralConfig) (compute.Value, error)]{
		Method: "DotGeneral",
	}
	RegisterDynamicBroadcastInDim = OpHandlerRegistration[func(f *Function, operand compute.Value, broadcastAxes []int, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)]{
		Method: "DynamicBroadcastInDim",
	}
	RegisterDynamicDimensionSize = OpHandlerRegistration[func(f *Function, operand compute.Value, axis int) (compute.Value, error)]{
		Method: "DynamicDimensionSize",
	}
	RegisterDynamicIota = OpHandlerRegistration[func(f *Function, dtype dtypes.DType, iotaAxis int, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)]{
		Method: "DynamicIota",
	}
	RegisterDynamicPad = OpHandlerRegistration[func(f *Function, x compute.Value, fillValue compute.Value, axesConfig ...compute.DynamicPadAxis) (compute.Value, error)]{
		Method: "DynamicPad",
	}
	RegisterDynamicReshape = OpHandlerRegistration[func(f *Function, operand compute.Value, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)]{
		Method: "DynamicReshape",
	}
	RegisterDynamicShape = OpHandlerRegistration[func(f *Function, operand compute.Value) (compute.Value, error)]{
		Method: "DynamicShape",
	}
	RegisterDynamicSlice = OpHandlerRegistration[func(f *Function, operand compute.Value, startIndices []compute.Value, sliceDims []int) (compute.Value, error)]{
		Method: "DynamicSlice",
	}
	RegisterDynamicUpdateSlice = OpHandlerRegistration[func(f *Function, operand compute.Value, update compute.Value, startIndices []compute.Value) (compute.Value, error)]{
		Method: "DynamicUpdateSlice",
	}
	RegisterEqual = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Equal",
	}
	RegisterEqualTotalOrder = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "EqualTotalOrder",
	}
	RegisterErf = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Erf",
	}
	RegisterExp = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Exp",
	}
	RegisterExpm1 = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Expm1",
	}
	RegisterFFT = OpHandlerRegistration[func(f *Function, operand compute.Value, fftType compute.FFTType, fftLength []int) (compute.Value, error)]{
		Method: "FFT",
	}
	RegisterFloor = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Floor",
	}
	RegisterFusedAttentionQKVProjection = OpHandlerRegistration[func(f *Function, x compute.Value, wQKV compute.Value, biasQ compute.Value, biasK compute.Value, biasV compute.Value, queryDim int, keyValueDim int) (query compute.Value, key compute.Value, value compute.Value, err error)]{
		Method: "FusedAttentionQKVProjection",
	}
	RegisterFusedDense = OpHandlerRegistration[func(f *Function, x compute.Value, weight compute.Value, bias compute.Value, options compute.DenseConfig) (compute.Value, error)]{
		Method: "FusedDense",
	}
	RegisterFusedGelu = OpHandlerRegistration[func(f *Function, x compute.Value, exact bool) (compute.Value, error)]{
		Method: "FusedGelu",
	}
	RegisterFusedLayerNorm = OpHandlerRegistration[func(f *Function, x compute.Value, axes []int, epsilon float64, gamma compute.Value, beta compute.Value) (compute.Value, error)]{
		Method: "FusedLayerNorm",
	}
	RegisterFusedQuantizedDense = OpHandlerRegistration[func(f *Function, x compute.Value, weights compute.Value, bias compute.Value, weightsQuantization *compute.Quantization, activation compute.ActivationType) (compute.Value, error)]{
		Method: "FusedQuantizedDense",
	}
	RegisterFusedScaledDotProductAttention = OpHandlerRegistration[func(f *Function, query compute.Value, key compute.Value, value compute.Value, axesLayout compute.AttentionAxesLayout, options *compute.ScaledDotProductAttentionConfig) (output compute.Value, statesForVJP []compute.Value, err error)]{
		Method: "FusedScaledDotProductAttention",
	}
	RegisterFusedScaledDotProductAttentionVJP = OpHandlerRegistration[func(f *Function, query compute.Value, key compute.Value, value compute.Value, axesLayout compute.AttentionAxesLayout, options *compute.ScaledDotProductAttentionConfig, output compute.Value, statesForVJP []compute.Value, dOutput compute.Value) (dQuery compute.Value, dKey compute.Value, dValue compute.Value, err error)]{
		Method: "FusedScaledDotProductAttentionVJP",
	}
	RegisterFusedSoftmax = OpHandlerRegistration[func(f *Function, x compute.Value, axis int) (compute.Value, error)]{
		Method: "FusedSoftmax",
	}
	RegisterGather = OpHandlerRegistration[func(f *Function, operand compute.Value, startIndices compute.Value, indexVectorAxis int, offsetOutputAxes []int, collapsedSliceAxes []int, startIndexMap []int, sliceSizes []int, indicesAreSorted bool) (compute.Value, error)]{
		Method: "Gather",
	}
	RegisterGreaterOrEqual = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "GreaterOrEqual",
	}
	RegisterGreaterOrEqualTotalOrder = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "GreaterOrEqualTotalOrder",
	}
	RegisterGreaterThan = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "GreaterThan",
	}
	RegisterGreaterThanTotalOrder = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "GreaterThanTotalOrder",
	}
	RegisterIdentity = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Identity",
	}
	RegisterIf = OpHandlerRegistration[func(f *Function, pred compute.Value, trueBranch compute.Function, falseBranch compute.Function) ([]compute.Value, error)]{
		Method: "If",
	}
	RegisterImag = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Imag",
	}
	RegisterIota = OpHandlerRegistration[func(f *Function, shape shapes.Shape, iotaAxis int) (compute.Value, error)]{
		Method: "Iota",
	}
	RegisterIsFinite = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "IsFinite",
	}
	RegisterIsNaN = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "IsNaN",
	}
	RegisterLessOrEqual = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "LessOrEqual",
	}
	RegisterLessOrEqualTotalOrder = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "LessOrEqualTotalOrder",
	}
	RegisterLessThan = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "LessThan",
	}
	RegisterLessThanTotalOrder = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "LessThanTotalOrder",
	}
	RegisterLog = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Log",
	}
	RegisterLog1p = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Log1p",
	}
	RegisterLogicalAnd = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "LogicalAnd",
	}
	RegisterLogicalNot = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "LogicalNot",
	}
	RegisterLogicalOr = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "LogicalOr",
	}
	RegisterLogicalXor = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "LogicalXor",
	}
	RegisterLogistic = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Logistic",
	}
	RegisterMax = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Max",
	}
	RegisterMin = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Min",
	}
	RegisterMul = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Mul",
	}
	RegisterNeg = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Neg",
	}
	RegisterNotEqual = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "NotEqual",
	}
	RegisterNotEqualTotalOrder = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "NotEqualTotalOrder",
	}
	RegisterOptimizationBarrier = OpHandlerRegistration[func(f *Function, operands ...compute.Value) ([]compute.Value, error)]{
		Method: "OptimizationBarrier",
	}
	RegisterPad = OpHandlerRegistration[func(f *Function, x compute.Value, fillValue compute.Value, axesConfig ...compute.PadAxis) (compute.Value, error)]{
		Method: "Pad",
	}
	RegisterPow = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Pow",
	}
	RegisterQuantizedEmbeddingLookup = OpHandlerRegistration[func(f *Function, data compute.Value, indices compute.Value, dataQuantization *compute.Quantization) (compute.Value, error)]{
		Method: "QuantizedEmbeddingLookup",
	}
	RegisterReal = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Real",
	}
	RegisterReduceBitwiseAnd = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceBitwiseAnd",
	}
	RegisterReduceBitwiseOr = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceBitwiseOr",
	}
	RegisterReduceBitwiseXor = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceBitwiseXor",
	}
	RegisterReduceLogicalAnd = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceLogicalAnd",
	}
	RegisterReduceLogicalOr = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceLogicalOr",
	}
	RegisterReduceLogicalXor = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceLogicalXor",
	}
	RegisterReduceMax = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceMax",
	}
	RegisterReduceMin = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceMin",
	}
	RegisterReduceProduct = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceProduct",
	}
	RegisterReduceSum = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceSum",
	}
	RegisterReduceWindow = OpHandlerRegistration[func(f *Function, input compute.Value, reductionType compute.ReduceOpType, windowDimensions []int, strides []int, inputDilations []int, windowDilations []int, paddings [][2]int) (compute.Value, error)]{
		Method: "ReduceWindow",
	}
	RegisterRem = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Rem",
	}
	RegisterReshape = OpHandlerRegistration[func(f *Function, x compute.Value, dimensions ...int) (compute.Value, error)]{
		Method: "Reshape",
	}
	RegisterReverse = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "Reverse",
	}
	RegisterRNGBitGenerator = OpHandlerRegistration[func(f *Function, state compute.Value, shape shapes.Shape) (newState compute.Value, values compute.Value, err error)]{
		Method: "RNGBitGenerator",
	}
	RegisterRound = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Round",
	}
	RegisterRsqrt = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Rsqrt",
	}
	RegisterScatterMax = OpHandlerRegistration[func(f *Function, operand compute.Value, scatterIndices compute.Value, updates compute.Value, indexVectorAxis int, updateWindowAxes []int, insertedWindowAxes []int, scatterAxesToOperandAxes []int, indicesAreSorted bool, uniqueIndices bool) (compute.Value, error)]{
		Method: "ScatterMax",
	}
	RegisterScatterMin = OpHandlerRegistration[func(f *Function, operand compute.Value, scatterIndices compute.Value, updates compute.Value, indexVectorAxis int, updateWindowAxes []int, insertedWindowAxes []int, scatterAxesToOperandAxes []int, indicesAreSorted bool, uniqueIndices bool) (compute.Value, error)]{
		Method: "ScatterMin",
	}
	RegisterScatterSum = OpHandlerRegistration[func(f *Function, operand compute.Value, scatterIndices compute.Value, updates compute.Value, indexVectorAxis int, updateWindowAxes []int, insertedWindowAxes []int, scatterAxesToOperandAxes []int, indicesAreSorted bool, uniqueIndices bool) (compute.Value, error)]{
		Method: "ScatterSum",
	}
	RegisterSchedulingBarrier = OpHandlerRegistration[func(f *Function, operand compute.Value, dependencies ...compute.Value) (compute.Value, error)]{
		Method: "SchedulingBarrier",
	}
	RegisterSelectAndScatterMax = OpHandlerRegistration[func(f *Function, operand compute.Value, source compute.Value, windowDimensions []int, windowStrides []int, paddings [][2]int) (compute.Value, error)]{
		Method: "SelectAndScatterMax",
	}
	RegisterSelectAndScatterMin = OpHandlerRegistration[func(f *Function, operand compute.Value, source compute.Value, windowDimensions []int, windowStrides []int, paddings [][2]int) (compute.Value, error)]{
		Method: "SelectAndScatterMin",
	}
	RegisterShiftLeft = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "ShiftLeft",
	}
	RegisterShiftRightArithmetic = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "ShiftRightArithmetic",
	}
	RegisterShiftRightLogical = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "ShiftRightLogical",
	}
	RegisterSign = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Sign",
	}
	RegisterSin = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Sin",
	}
	RegisterSlice = OpHandlerRegistration[func(f *Function, x compute.Value, starts []int, limits []int, strides []int) (compute.Value, error)]{
		Method: "Slice",
	}
	RegisterSort = OpHandlerRegistration[func(f *Function, comparator compute.Function, axis int, isStable bool, inputs ...compute.Value) ([]compute.Value, error)]{
		Method: "Sort",
	}
	RegisterSqrt = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Sqrt",
	}
	RegisterSub = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Sub",
	}
	RegisterTanh = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Tanh",
	}
	RegisterTranspose = OpHandlerRegistration[func(f *Function, x compute.Value, permutation ...int) (compute.Value, error)]{
		Method: "Transpose",
	}
	RegisterWhere = OpHandlerRegistration[func(f *Function, condition compute.Value, onTrue compute.Value, onFalse compute.Value) (compute.Value, error)]{
		Method: "Where",
	}
	RegisterWhile = OpHandlerRegistration[func(f *Function, cond compute.Function, body compute.Function, initialState ...compute.Value) ([]compute.Value, error)]{
		Method: "While",
	}
)

Registration variables for the op handlers.

View Source
var Capabilities = compute.Capabilities{
	Functions:     true,
	DynamicAxes:   true,
	DynamicShapes: compute.DynamicShapesNative,

	Operations: map[compute.OpType]bool{

		compute.OpTypeParameter: true,
		compute.OpTypeConstant:  true,

		compute.OpTypeAbs:        true,
		compute.OpTypeBitCount:   true,
		compute.OpTypeBitwiseNot: true,
		compute.OpTypeCeil:       true,
		compute.OpTypeClz:        true,
		compute.OpTypeCos:        true,
		compute.OpTypeErf:        true,
		compute.OpTypeExp:        true,
		compute.OpTypeExpm1:      true,
		compute.OpTypeFloor:      true,
		compute.OpTypeIsFinite:   true,
		compute.OpTypeIsNaN:      true,
		compute.OpTypeLog1p:      true,
		compute.OpTypeLog:        true,
		compute.OpTypeLogicalNot: true,
		compute.OpTypeLogistic:   true,
		compute.OpTypeNeg:        true,
		compute.OpTypeRound:      true,
		compute.OpTypeRsqrt:      true,
		compute.OpTypeSign:       true,
		compute.OpTypeSin:        true,
		compute.OpTypeSqrt:       true,
		compute.OpTypeTanh:       true,

		compute.OpTypeAdd:        true,
		compute.OpTypeBitwiseAnd: true,
		compute.OpTypeBitwiseOr:  true,
		compute.OpTypeBitwiseXor: true,
		compute.OpTypeDiv:        true,
		compute.OpTypeLogicalAnd: true,
		compute.OpTypeLogicalOr:  true,
		compute.OpTypeLogicalXor: true,
		compute.OpTypeMax:        true,
		compute.OpTypeMin:        true,
		compute.OpTypeMul:        true,
		compute.OpTypePow:        true,
		compute.OpTypeRem:        true,
		compute.OpTypeSub:        true,

		compute.OpTypeEqual:          true,
		compute.OpTypeNotEqual:       true,
		compute.OpTypeGreaterOrEqual: true,
		compute.OpTypeGreaterThan:    true,
		compute.OpTypeLessOrEqual:    true,
		compute.OpTypeLessThan:       true,

		compute.OpTypeArgMinMax:             true,
		compute.OpTypeBitcast:               true,
		compute.OpTypeBroadcastInDim:        true,
		compute.OpTypeDynamicBroadcastInDim: true,
		compute.OpTypeConcatenate:           true,
		compute.OpTypeConvertDType:          true,
		compute.OpTypeCumSum:                true,
		compute.OpTypeDot:                   true,
		compute.OpTypeDotGeneral:            true,
		compute.OpTypeGather:                true,
		compute.OpTypeIdentity:              true,
		compute.OpTypeIota:                  true,
		compute.OpTypeDynamicIota:           true,
		compute.OpTypePad:                   true,
		compute.OpTypeDynamicPad:            true,
		compute.OpTypeDynamicDimensionSize:  true,
		compute.OpTypeDynamicShape:          true,
		compute.OpTypeReduceBitwiseAnd:      true,
		compute.OpTypeReduceBitwiseOr:       true,
		compute.OpTypeReduceBitwiseXor:      true,
		compute.OpTypeReduceLogicalAnd:      true,
		compute.OpTypeReduceLogicalOr:       true,
		compute.OpTypeReduceLogicalXor:      true,
		compute.OpTypeReduceMax:             true,
		compute.OpTypeReduceMin:             true,
		compute.OpTypeReduceProduct:         true,
		compute.OpTypeReduceSum:             true,
		compute.OpTypeReduceWindow:          true,
		compute.OpTypeReshape:               true,
		compute.OpTypeDynamicReshape:        true,
		compute.OpTypeReverse:               true,
		compute.OpTypeRNGBitGenerator:       true,
		compute.OpTypeScatterMax:            true,
		compute.OpTypeScatterMin:            true,
		compute.OpTypeScatterSum:            true,
		compute.OpTypeShiftLeft:             true,
		compute.OpTypeShiftRightArithmetic:  true,
		compute.OpTypeShiftRightLogical:     true,
		compute.OpTypeSlice:                 true,
		compute.OpTypeTranspose:             true,
		compute.OpTypeWhere:                 true,
		compute.OpTypeConvGeneral:           true,
		compute.OpTypeOptimizationBarrier:   true,
		compute.OpTypeSchedulingBarrier:     true,

		compute.OpTypeCall:  true,
		compute.OpTypeIf:    true,
		compute.OpTypeWhile: true,
		compute.OpTypeSort:  true,

		compute.OpTypeFusedSoftmax:   true,
		compute.OpTypeFusedLayerNorm: true,
		compute.OpTypeFusedGelu:      true,
		compute.OpTypeFusedDense:     true,

		compute.OpTypeFusedScaledDotProductAttention: false,
		compute.OpTypeFusedAttentionQKVProjection:    true,
		compute.OpTypeFusedQuantizedDense:            true,
		compute.OpTypeQuantizedEmbeddingLookup:       true,

		compute.OpTypeSelectAndScatterMax: true,
		compute.OpTypeSelectAndScatterMin: true,
	},

	DTypes: map[dtypes.DType]bool{
		dtypes.Bool:     true,
		dtypes.Int2:     true,
		dtypes.Uint2:    true,
		dtypes.Int4:     true,
		dtypes.Uint4:    true,
		dtypes.Int8:     true,
		dtypes.Int16:    true,
		dtypes.Int32:    true,
		dtypes.Int64:    true,
		dtypes.Uint8:    true,
		dtypes.Uint16:   true,
		dtypes.Uint32:   true,
		dtypes.Uint64:   true,
		dtypes.Float16:  true,
		dtypes.Float32:  true,
		dtypes.Float64:  true,
		dtypes.BFloat16: true,
	},
}

Capabilities of the Go backend: the set of supported operations and data types.

View Source
var ErrBackendAlreadyFinalized = stderrors.New("backend already exists")

ErrBackendAlreadyFinalized is returned when attempting to register or initialize a backend that already exists.

View Source
var GetBackend = sync.OnceValue(func() compute.Backend {
	backend, err := New("")
	if err != nil {
		panic(err)
	}
	return backend
})

GetBackend returns a singleton backend for Go backend, created with the default configuration. The backend is only created at the first call of the function.

The singleton is never destroyed.

View Source
var KnownOptionsSetters = make(map[string]func(b *Backend, key string) error)

KnownOptionsSetters registers handlers for backend configuration options. These allow any sub-package to register option setters.

The key is the name of the option: it can't take any values yet.

NumericDTypes is the list of numeric data types supported by the Go backend. This excludes Bool and is used for operations like DotGeneral that only work on numeric types.

Functions

func CheckClosureParams

func CheckClosureParams(opName, closureName string, fn *Function, expected []*Node) error

CheckClosureParams verifies that a closure's parameters match expected shapes.

func CopyFlat

func CopyFlat(flatDst, flatSrc any)

CopyFlat assumes both flat slices are of the same underlying type. Fast paths for common dtypes avoid reflection overhead.

func DataEqual

func DataEqual(a, b any) bool

DataEqual compares node data for equality.

If the node data field implements NodeDataComparable interface, it uses the EqualNodeData method for comparison.

Otherwise it has fallback for the primitive types int, []int strucs (using shallow equal "==") and pointers to structs.

func MutableBytesGeneric

func MutableBytesGeneric[T SupportedTypesConstraints](b *Buffer) ([]byte, error)

MutableBytesGeneric is the generic implementation of mutableBytes.

func New

func New(config string) (compute.Backend, error)

New constructs a new Go backend. There are no configurations, the string is simply ignored.

func RegisterTransformation

func RegisterTransformation(priority int, transformation GraphTransformation)

RegisterTransformation registers a graph transformation to be executed during compilation.

This should be called in init() functions only, it must not be called after the program starts.

func ScheduleStrategyStrings

func ScheduleStrategyStrings() []string

ScheduleStrategyStrings returns a slice of all String values of the enum

func SetNodeExecutor

func SetNodeExecutor(opType compute.OpType, priority RegisterPriority, executor NodeExecutor)

SetNodeExecutor sets the node executor for the given operation type with the specified priority. If the priority is lower than the current priority for the operation type, the executor is ignored.

Types

type Backend

type Backend struct {
	Workers *workerspool.Pool

	NumLiveExecutions atomic.Int32

	// OpsExecutionType defines how to execute the ops of a computation.
	OpsExecutionType OpsExecutionType

	// SchedulingStrategy
	SchedulingStrategy ScheduleStrategy
	// contains filtered or unexported fields
}

Backend implements the compute.Backend interface.

func (*Backend) BufferFromFlatData

func (b *Backend) BufferFromFlatData(deviceNum compute.DeviceNum, flat any, shape shapes.Shape) (compute.Buffer,
	error)

BufferFromFlatData transfers data from Go given as a flat slice (of the type corresponding to the shape DType) to the deviceNum, and returns the corresponding compute.Buffer.

func (*Backend) Builder

func (b *Backend) Builder(name string) compute.Builder

Builder creates a new builder used to construct a named computation.

func (*Backend) Capabilities

func (b *Backend) Capabilities() compute.Capabilities

Capabilities method returns information about what is supported by this backend.

func (*Backend) CloneBuffer

func (b *Backend) CloneBuffer(buffer *Buffer) (*Buffer, error)

CloneBuffer using the pool to allocate a new one.

func (*Backend) Description

func (b *Backend) Description() string

Description is a longer description of the Backend that can be used to pretty-print.

func (*Backend) DeviceDescription

func (b *Backend) DeviceDescription(_ compute.DeviceNum) string

DeviceDescription returns a description of the device with the given deviceNum.

func (*Backend) Finalize

func (b *Backend) Finalize()

Finalize releases all the associated resources immediately, and makes the backend invalid.

func (*Backend) GetBuffer

func (b *Backend) GetBuffer(shape shapes.Shape) (*Buffer, error)

GetBuffer with the corresponding shape from the backend pool of buffers if possible, or it allocates a new one.

It returns ErrBackendAlreadyFinalized if the backend is already finalized.

Important: it's not necessarily initialized with zero, since it can reuse old buffers.

See also Buffer.Zeros to initialize it with zeros, if needed.

func (*Backend) HasSharedBuffers

func (b *Backend) HasSharedBuffers() bool

HasSharedBuffers returns whether the backend supports "shared buffers": these are buffers that can be used directly by the engine and has a local address that can be read or mutated directly by the client.

func (*Backend) IsFinalized

func (b *Backend) IsFinalized() bool

IsFinalized returns true if the backend has been isFinalized.

func (*Backend) Name

func (b *Backend) Name() string

Name returns the short name of the backend. E.g.: "xla" for the Xla/PJRT plugin.

func (*Backend) NewBuffer

func (b *Backend) NewBuffer(shape shapes.Shape) *Buffer

NewBuffer creates the buffer with a newly allocated flat space.

TODO: should we study the possibility to change the signature with an error?

func (*Backend) NewSharedBuffer

func (b *Backend) NewSharedBuffer(deviceNum compute.DeviceNum, shape shapes.Shape) (buffer compute.Buffer,
	flat any, err error)

NewSharedBuffer returns a "shared buffer" that can be both used as input for execution of computations and directly read or mutated by the clients.

It panics if the backend doesn't support shared buffers -- see HasSharedBuffer.

The shared buffer should not be mutated while it is used by an execution. Also, the shared buffer cannot be "donated" during execution.

When done, to release the memory, call BufferFinalized on the returned buffer.

It returns a handle to the buffer and a slice of the corresponding data type pointing to the shared data.

func (*Backend) NumDevices

func (b *Backend) NumDevices() int

NumDevices return the number of devices available for this Backend.

func (*Backend) PutBuffer

func (b *Backend) PutBuffer(buffer *Buffer)

PutBuffer back into the backend pool of buffers. After this any references to buffer should be dropped.

func (*Backend) String

func (b *Backend) String() string

String implement compute.Backend.

type BroadcastIterator

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

BroadcastIterator allows iteration over the flat indices of the target shape of a broadcast (where some axis dimensions grow)

It is used by implicit broadcasting in binary ops and by the BroadcastInDim.

func NewBroadcastIterator

func NewBroadcastIterator(srcShape, tgtShape shapes.Shape) *BroadcastIterator

NewBroadcastIterator returns an iterator contructor over the flat indices of the target shape of a broadcast (where some axis dimensions grow).

Pre-requisite: srcShape.Rank() == tgtShape.Rank().

It is used by implicit broadcasting in binary ops and by the BroadcastInDim.

func (*BroadcastIterator) IterFlatIndices

func (bi *BroadcastIterator) IterFlatIndices() iter.Seq2[int, int]

IterFlatIndices iterate over the source and target flat indices for broadcast. Notice since we are broadcasting, the target index will always be incremented by 1, while the source index may repeat (when it is being broadcast).

type Buffer

type Buffer struct {
	RawBackend *Backend
	RawShape   shapes.Shape

	// InUse is set to false when the buffer is finalized and moved back to the pool.
	InUse bool

	// RawBytes is the underlying storage for the buffer.
	// Its length is always >= requested size in bytes.
	RawBytes []byte

	// Flat is always a slice of the underlying data type (shape.DType).
	// It is a re-casting of RawBytes.
	Flat any
	// contains filtered or unexported fields
}

Buffer for the Go backend holds a shape and a reference to the flat data.

The flat data may be shared -- for temporary buffers from compiled graphs they are taken from larger blobs of bytes allocated in one Go -- or owned by the buffer.

func (*Buffer) Backend

func (buffer *Buffer) Backend() compute.Backend

Backend returns the backend that owns this buffer.

func (*Buffer) Check

func (buffer *Buffer) Check() error

Check does a sanity-check on the buffer. Returns a corresponding error if something is wrong.

Used only for debugging.

func (*Buffer) CopyToDevice

func (buffer *Buffer) CopyToDevice(deviceNum compute.DeviceNum) (compute.Buffer, error)

BufferCopyToDevice implements the compute.Backend interface. CopyToDevice implements the compute.Buffer interface.

func (*Buffer) Data

func (buffer *Buffer) Data() (flat any, err error)

BufferData returns a slice pointing to the buffer storage memory directly.

This only works if HasSharedBuffer is true, that is, if the backend engine runs on CPU, or shares CPU memory.

The returned slice becomes invalid after the buffer is destroyed. Data returns a slice pointing to the buffer storage memory directly.

func (*Buffer) DeviceNum

func (buffer *Buffer) DeviceNum() (compute.DeviceNum, error)

BufferDeviceNum returns the deviceNum for the buffer. DeviceNum returns the deviceNum for the buffer.

func (*Buffer) EqualNodeData

func (b *Buffer) EqualNodeData(other NodeDataComparable) bool

EqualNodeData implements nodeDataComparable for Buffer. For Constants, this compares the shape and the actual data values.

func (*Buffer) Fill

func (b *Buffer) Fill(value any) error

Fill the buffer with the given value. It returns an error if the value type doesn't correspond to the buffer dtype.

As a special case, if value is nil, it will fill the buffer with zeroes for the corresponding DType.

func (*Buffer) Finalize

func (buffer *Buffer) Finalize() error

Finalize allows the client to inform the backend that the buffer is no longer needed and associated resources can be freed immediately.

A isFinalized buffer should never be used again. Preferably, the caller should set its references to it to nil. Finalize allows the client to inform the backend that the buffer is no longer needed and associated resources can be freed immediately.

func (*Buffer) MutableBytes

func (b *Buffer) MutableBytes() ([]byte, error)

MutableBytes returns the slice of the bytes used by the flat given -- it works with any of the supported data types for buffers.

func (*Buffer) Ones

func (b *Buffer) Ones() *Buffer

Ones fills the buffer with ones.

It returns a reference to the buffer to allow cascading calls.

func (*Buffer) Shape

func (buffer *Buffer) Shape() (shapes.Shape, error)

BufferShape returns the shape for the buffer. Shape returns the shape for the buffer.

func (*Buffer) ToFlatData

func (buffer *Buffer) ToFlatData(flat any) error

BufferToFlatData transfers the flat values of the buffer to the Go flat array. The slice flat must have the exact number of elements required to store the compute.Buffer shape.

See also FlatDataToBuffer, BufferShape, and shapes.Shape.Size. ToFlatData transfers the flat values of the buffer to the Go flat array.

func (*Buffer) Zeros

func (b *Buffer) Zeros() *Buffer

Zeros fills the buffer with zeros.

It returns a reference to the buffer to allow cascading calls.

type Builder

type Builder struct {
	notimplemented.Builder

	Backend    *Backend
	IsCompiled bool

	// MainFn is the main function of the computation.
	// Each function (including MainFn and closures) has its own nodes slice.
	MainFn *Function

	// Functions are all functions created within this builder, in order of creation.
	// It includes the main function.
	Functions []*Function
	// contains filtered or unexported fields
}

Builder keeps track of the computation graph being defined.

func (*Builder) Compile

func (b *Builder) Compile() (compute.Executable, error)

Compile implements compute.Builder.

func (*Builder) DAGSort

func (b *Builder) DAGSort() error

DAGSort stably sorts the nodes in all functions topologically. It preserves the original creation order as much as possible.

func (*Builder) Finalize

func (b *Builder) Finalize()

Finalize immediately releases the resources associated with the Builder.

func (*Builder) Main

func (b *Builder) Main() compute.Function

Main returns the main function of this computation.

func (*Builder) Name

func (b *Builder) Name() string

Name implements compute.Builder.

func (*Builder) NewFunction

func (b *Builder) NewFunction(name string) (compute.Function, error)

NewFunction creates a new named function within this builder. Named functions can be called with Call() and are independent of the main function.

func (*Builder) OpShape

func (b *Builder) OpShape(op compute.Value) (shapes.Shape, error)

OpShape returns the shape of a computation Op.

func (*Builder) Optimize

func (b *Builder) Optimize() error

func (*Builder) String

func (b *Builder) String() string

String returns a multi-line string with the output of each function.

type ClosureInputs

type ClosureInputs struct {
	// Buffers are the captured input buffers for the closure.
	Buffers []*Buffer
	// Owned indicates which captured inputs can be donated to the closure.
	// If Owned[i] is true, the closure takes ownership of Buffers[i].
	Owned []bool
}

ClosureInputs holds the captured inputs and their ownership for a single closure. This is used to pass captured values to closure-calling operations (If, While, Sort).

type DTypeMap

type DTypeMap struct {
	Name     string
	Map      [MaxDTypes]any
	Priority [MaxDTypes]RegisterPriority
}

DTypeMap manages registering of an arbitrary value per dtype. See NewDTypeMap for more information, including how to auto-generation registration for various classes of dtypes (ints, uints, floats, half).

func NewDTypeMap

func NewDTypeMap(name string) *DTypeMap

NewDTypeMap creates a new DTypeMap.

To automatically create code to register Go-generic functions to handle those dtypes, you can use the generator in internal/cmd/gobackend_dtypemap and add annotations (comments) before the DTypeMap variable declaration, like the example:

//gobackend:dtypemap MyGeneric ints,uints,floats,half
var myDTypeMap = gobackend.NewDTypeMap("myDTypeMap")

This will automatically trigger the generation of registration calls in `gen_dtypemaps_registration.go` with content like:

myDTypeMap.Register(dtypes.Int8, gobackend.PriorityGeneric, MyGeneric[int8])
myDTypeMap.Register(dtypes.Int16, gobackend.PriorityGeneric, MyGeneric[int16])
myDTypeMap.Register(dtypes.Int32, gobackend.PriorityGeneric, MyGeneric[int32])
myDTypeMap.Register(dtypes.Int64, gobackend.PriorityGeneric, MyGeneric[int64])
myDTypeMap.Register(dtypes.Uint8, gobackend.PriorityGeneric, MyGeneric[uint8])
myDTypeMap.Register(dtypes.Uint16, gobackend.PriorityGeneric, MyGeneric[uint16])
myDTypeMap.Register(dtypes.Uint32, gobackend.PriorityGeneric, MyGeneric[uint32])
myDTypeMap.Register(dtypes.Uint64, gobackend.PriorityGeneric, MyGeneric[uint64])
myDTypeMap.Register(dtypes.Float32, gobackend.PriorityGeneric, MyGeneric[float32])
myDTypeMap.Register(dtypes.Float64, gobackend.PriorityGeneric, MyGeneric[float64])
myDTypeMap.Register(dtypes.BFloat16, gobackend.PriorityGeneric, MyGeneric[bfloat16.BFloat16])
myDTypeMap.Register(dtypes.Float16, gobackend.PriorityGeneric, MyGeneric[float16.Float16])

func (*DTypeMap) Get

func (d *DTypeMap) Get(dtype dtypes.DType) (any, error)

Get retrieves the value for the given dtype, or return an error if none was registered.

func (*DTypeMap) Register

func (d *DTypeMap) Register(dtype dtypes.DType, priority RegisterPriority, value any)

Register a value for a dtype with the specified priority. If the priority is lower than the current priority for the dtype, the value is ignored.

type DTypePairMap

type DTypePairMap struct {
	Name     string
	Map      [MaxDTypes][MaxDTypes]any
	Priority [MaxDTypes][MaxDTypes]RegisterPriority
}

DTypePairMap manages registering of an arbitrary value per dtype pair.

func NewDTypePairMap

func NewDTypePairMap(name string) *DTypePairMap

NewDTypePairMap creates a new DTypePairMap.

Similar to NewDTypeMap, you can add annotations to generate code to register generic functions. Example:

//gobackend:dtypemap_pair callImplementationGeneric ints same
//gobackend:dtypemap_pair callImplementationGeneric ints int32,int64
//gobackend:dtypemap_pair callImplementationGeneric uints same
//gobackend:dtypemap_pair callImplementationGeneric uints uint32,uint64
//gobackend:dtypemap_pair callImplementationGeneric floats floats
//gobackend:dtypemap_pair callImplementationGeneric half float32
callImplementationDTypePairMap = gobackend.NewDTypePairMap("callImplementationGeneric")

func (*DTypePairMap) Get

func (d *DTypePairMap) Get(dtype1, dtype2 dtypes.DType) (any, error)

Get retrieves the value for the given dtype pair, or return an error if none was registered.

func (*DTypePairMap) Register

func (d *DTypePairMap) Register(dtype1, dtype2 dtypes.DType, priority RegisterPriority, value any)

Register a value for a dtype pair with the specified priority. If the priority is lower than the current priority for the dtype pair, the value is ignored.

type Executable

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

Executable holds a frozen Builder. It assumes the graph in Builder is valid and has been properly checked that all the shapes and data types are valid.

If any inconsistencies are found, please fix in the Builder, so Executable can be written without the need of any duplicate checks.

func (*Executable) Execute

func (e *Executable) Execute(inputs []compute.Buffer, donate []bool, _ compute.DeviceNum) ([]compute.Buffer, error)

Execute the executable on the default device (0). The number and shapes of the inputs must match those returned by Inputs.

The inputs marked in `donate` will become invalid after use. This is useful if the input buffer is no longer needed or if updating a variable so its Buffer space can be reused as an output Buffer.

Donated buffers are no longer valid after the call. If donate is nil, it is assumed to be false for all buffers, and no buffer is donated.

func (*Executable) Finalize

func (e *Executable) Finalize()

Finalize immediately frees resources associated with the executable.

TODO: Race-condition where calling Finalize will make execution crash, if finalized while executing.

Make Finalize wait for all the current executions to exit, before finalizing.
And add a latch indicating Finalize has been called, to tell the executions to exit immediately
without finishing. Finally, remove the `e.builder == nil` checks, that won't be necessary anymore,
since e.builder will never be set to nil while there is an execution alive.

func (*Executable) Inputs

func (e *Executable) Inputs() (names []string, inputShapes []shapes.Shape)

Inputs returns the list of parameters names and shapes, in order created by the Builder.Parameter calls.

func (*Executable) Outputs

func (e *Executable) Outputs() (outputShapes []shapes.Shape)

Outputs returns the output shapes of the computation, in order given to the Builder.Compile call.

type Function

type Function struct {
	notimplemented.Function

	RawBuilder *Builder

	// RawParent is the parent function if this is a closure.
	// For top-level functions (including main), this is nil.
	RawParent *Function

	// IsReturned indicates Return() was called.
	IsReturned bool

	// Nodes are all Nodes created within this function, in DAG order.
	// Each node's idx field is its index in this slice.
	Nodes []*Node

	// Outputs stores the return values set by Return().
	Outputs []*Node

	// Parameters stores the parameter nodes for this function.
	Parameters []*Node

	// CapturedParentNodes stores nodes from parent scopes that are captured by this closure.
	// The order matches capturedLocalNodes - CapturedParentNodes[i] is the parent node for capturedLocalNodes[i].
	CapturedParentNodes []*Node

	// CapturedLocalNodes stores the proxy nodes in this closure for captured values.
	// These are OpTypeCapturedValue nodes that receive their values at execution time.
	CapturedLocalNodes []*Node

	// compiled holds pre-compiled execution info.
	// This is set during Return() to allow efficient execution.
	Compiled *FunctionExecutable
	// contains filtered or unexported fields
}

Function implements compute.Function for the Go backend.

func (*Function) Abs

func (f *Function) Abs(x compute.Value) (compute.Value, error)

Stub methods that converts compute.Value to *Node and dispatches to the corresponding op handler.

func (*Function) Add

func (f *Function) Add(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) AllReduce

func (f *Function) AllReduce(_ []compute.Value, _ compute.ReduceOpType, _ [][]int) ([]compute.Value, error)

AllReduce implements the compute.CollectiveOps interface.

func (*Function) ArgMinMax

func (f *Function) ArgMinMax(x compute.Value, axis int, outputDType dtypes.DType, isMin bool) (compute.Value, error)

func (*Function) Atan2

func (f *Function) Atan2(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) BatchNormForInference

func (f *Function) BatchNormForInference(operand compute.Value, scale compute.Value, offset compute.Value, mean compute.Value, variance compute.Value, epsilon float32, featureAxis int) (compute.Value, error)

func (*Function) BatchNormForTraining

func (f *Function) BatchNormForTraining(operand compute.Value, scale compute.Value, offset compute.Value, epsilon float32, featureAxis int) (normalized compute.Value, batchMean compute.Value, batchVariance compute.Value, err error)

func (*Function) BatchNormGradient

func (f *Function) BatchNormGradient(operand compute.Value, scale compute.Value, mean compute.Value, variance compute.Value, gradOutput compute.Value, epsilon float32, featureAxis int) (gradOperand compute.Value, gradScale compute.Value, gradOffset compute.Value, err error)

func (*Function) BitCount

func (f *Function) BitCount(operand compute.Value) (compute.Value, error)

func (*Function) Bitcast

func (f *Function) Bitcast(operand compute.Value, targetDType dtypes.DType) (compute.Value, error)

func (*Function) BitwiseAnd

func (f *Function) BitwiseAnd(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) BitwiseNot

func (f *Function) BitwiseNot(x compute.Value) (compute.Value, error)

func (*Function) BitwiseOr

func (f *Function) BitwiseOr(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) BitwiseXor

func (f *Function) BitwiseXor(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) BroadcastInDim

func (f *Function) BroadcastInDim(operand compute.Value, outputShape shapes.Shape, broadcastAxes []int) (compute.Value, error)

func (*Function) Builder

func (f *Function) Builder() compute.Builder

Builder returns the builder for this function.

func (*Function) Call

func (f *Function) Call(fn compute.Function, inputs ...compute.Value) ([]compute.Value, error)

func (*Function) Ceil

func (f *Function) Ceil(x compute.Value) (compute.Value, error)

func (*Function) CheckValid

func (f *Function) CheckValid() error

CheckValid returns an error if the builder or the function are not ok.

func (*Function) Clamp

func (f *Function) Clamp(min compute.Value, x compute.Value, max compute.Value) (compute.Value, error)

func (*Function) Closure

func (f *Function) Closure() (compute.Function, error)

Closure creates a new closure function within this function. Closures can access values from their parent function's scope.

func (*Function) Clz

func (f *Function) Clz(x compute.Value) (compute.Value, error)

func (*Function) Complex

func (f *Function) Complex(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) Concatenate

func (f *Function) Concatenate(axis int, operands ...compute.Value) (compute.Value, error)

func (*Function) Conj

func (f *Function) Conj(x compute.Value) (compute.Value, error)

func (*Function) Constant

func (f *Function) Constant(flat any, dims ...int) (compute.Value, error)

Constant creates a constant in the function with the given flat values and the shape defined by the dimensions.

func (*Function) ConvGeneral

func (f *Function) ConvGeneral(input compute.Value, kernel compute.Value, axes compute.ConvolveAxesConfig, strides []int, paddings [][2]int, inputDilations []int, kernelDilations []int, channelGroupCount int, batchGroupCount int) (compute.Value, error)

func (*Function) ConvertDType

func (f *Function) ConvertDType(x compute.Value, dtype dtypes.DType) (compute.Value, error)

func (*Function) Cos

func (f *Function) Cos(x compute.Value) (compute.Value, error)

func (*Function) CumSum added in v0.1.5

func (f *Function) CumSum(operand compute.Value, axis int, options compute.CumSumOptions) (compute.Value, error)

func (*Function) DAGSort

func (f *Function) DAGSort() error

DAGSort stably sorts the nodes in the function topologically.

func (*Function) Div

func (f *Function) Div(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) DotGeneral

func (f *Function) DotGeneral(lhs compute.Value, lhsContractingAxes []int, lhsBatchAxes []int, rhs compute.Value, rhsContractingAxes []int, rhsBatchAxes []int, config compute.DotGeneralConfig) (compute.Value, error)

func (*Function) DynamicBroadcastInDim added in v0.1.5

func (f *Function) DynamicBroadcastInDim(operand compute.Value, broadcastAxes []int, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)

func (*Function) DynamicDimensionSize

func (f *Function) DynamicDimensionSize(operand compute.Value, axis int) (compute.Value, error)

func (*Function) DynamicIota added in v0.1.5

func (f *Function) DynamicIota(dtype dtypes.DType, iotaAxis int, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)

func (*Function) DynamicPad added in v0.1.5

func (f *Function) DynamicPad(x compute.Value, fillValue compute.Value, axesConfig ...compute.DynamicPadAxis) (compute.Value, error)

func (*Function) DynamicReshape added in v0.1.1

func (f *Function) DynamicReshape(operand compute.Value, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)

func (*Function) DynamicShape

func (f *Function) DynamicShape(operand compute.Value) (compute.Value, error)

func (*Function) DynamicSlice

func (f *Function) DynamicSlice(operand compute.Value, startIndices []compute.Value, sliceDims []int) (compute.Value, error)

func (*Function) DynamicUpdateSlice

func (f *Function) DynamicUpdateSlice(operand compute.Value, update compute.Value, startIndices []compute.Value) (compute.Value, error)

func (*Function) Equal

func (f *Function) Equal(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) EqualTotalOrder

func (f *Function) EqualTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) Erf

func (f *Function) Erf(x compute.Value) (compute.Value, error)

func (*Function) Exp

func (f *Function) Exp(x compute.Value) (compute.Value, error)

func (*Function) Expm1

func (f *Function) Expm1(x compute.Value) (compute.Value, error)

func (*Function) FFT

func (f *Function) FFT(operand compute.Value, fftType compute.FFTType, fftLength []int) (compute.Value, error)

func (*Function) Floor

func (f *Function) Floor(x compute.Value) (compute.Value, error)

func (*Function) FusedAttentionQKVProjection

func (f *Function) FusedAttentionQKVProjection(x compute.Value, wQKV compute.Value, biasQ compute.Value, biasK compute.Value, biasV compute.Value, queryDim int, keyValueDim int) (query compute.Value, key compute.Value, value compute.Value, err error)

func (*Function) FusedDense

func (f *Function) FusedDense(x compute.Value, weight compute.Value, bias compute.Value, options compute.DenseConfig) (compute.Value, error)

func (*Function) FusedGelu

func (f *Function) FusedGelu(x compute.Value, exact bool) (compute.Value, error)

func (*Function) FusedLayerNorm

func (f *Function) FusedLayerNorm(x compute.Value, axes []int, epsilon float64, gamma compute.Value, beta compute.Value) (compute.Value, error)

func (*Function) FusedQuantizedDense

func (f *Function) FusedQuantizedDense(x compute.Value, weights compute.Value, bias compute.Value, weightsQuantization *compute.Quantization, activation compute.ActivationType) (compute.Value, error)

func (*Function) FusedScaledDotProductAttention

func (f *Function) FusedScaledDotProductAttention(query compute.Value, key compute.Value, value compute.Value, axesLayout compute.AttentionAxesLayout, options *compute.ScaledDotProductAttentionConfig) (output compute.Value, statesForVJP []compute.Value, err error)

func (*Function) FusedScaledDotProductAttentionVJP

func (f *Function) FusedScaledDotProductAttentionVJP(query compute.Value, key compute.Value, value compute.Value, axesLayout compute.AttentionAxesLayout, options *compute.ScaledDotProductAttentionConfig, output compute.Value, statesForVJP []compute.Value, dOutput compute.Value) (dQuery compute.Value, dKey compute.Value, dValue compute.Value, err error)

func (*Function) FusedSoftmax

func (f *Function) FusedSoftmax(x compute.Value, axis int) (compute.Value, error)

func (*Function) Gather

func (f *Function) Gather(operand compute.Value, startIndices compute.Value, indexVectorAxis int, offsetOutputAxes []int, collapsedSliceAxes []int, startIndexMap []int, sliceSizes []int, indicesAreSorted bool) (compute.Value, error)

func (*Function) GetOrCreateCaptureNode

func (f *Function) GetOrCreateCaptureNode(parentNode *Node) *Node

GetOrCreateCaptureNode returns a capture node for the given parent node. If the parent node has already been captured, returns the existing capture node. Otherwise, creates a new capture node and adds it to the captured values list.

For nested closures (grandparent captures), this recursively propagates the capture through intermediate closures. For example, if closure C (child of B, child of A) wants to capture a value from A, this will: 1. Have B capture the value from A 2. Have C capture B's capture node

This ensures that when If/While/Sort ops are built, they can properly set up their capturedInputs by looking at the closure's capturedParentNodes.

func (*Function) GetOrCreateNode

func (f *Function) GetOrCreateNode(
	opType compute.OpType, shape shapes.Shape, inputs []*Node, data any) (
	n *Node, found bool)

GetOrCreateNode attempts to find a node with the content (opType, shape, inputs, data). If found, it returns the node. If not, it creates a new node with the filled fields, and returns found=false.

It also validates that all input nodes belong to this function or one of its ancestors. Using nodes from an ancestor function (closure capture) is not yet supported.

func (*Function) GreaterOrEqual

func (f *Function) GreaterOrEqual(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) GreaterOrEqualTotalOrder

func (f *Function) GreaterOrEqualTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) GreaterThan

func (f *Function) GreaterThan(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) GreaterThanTotalOrder

func (f *Function) GreaterThanTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) Identity

func (f *Function) Identity(x compute.Value) (compute.Value, error)

func (*Function) If

func (f *Function) If(pred compute.Value, trueBranch compute.Function, falseBranch compute.Function) ([]compute.Value, error)

func (*Function) Imag

func (f *Function) Imag(x compute.Value) (compute.Value, error)

func (*Function) Iota

func (f *Function) Iota(shape shapes.Shape, iotaAxis int) (compute.Value, error)

func (*Function) IsAncestorOf

func (f *Function) IsAncestorOf(leafFunc *Function) bool

IsAncestorOf checks whether f is an ancestor of leafFunc. It returns true if f == leafFunc.

Typically, leafFunc will be a closure.

func (*Function) IsFinite

func (f *Function) IsFinite(x compute.Value) (compute.Value, error)

func (*Function) IsNaN

func (f *Function) IsNaN(x compute.Value) (compute.Value, error)

func (*Function) KnownDynamicAxisNames

func (f *Function) KnownDynamicAxisNames() sets.Set[string]

KnownDynamicAxisNames returns the set of dynamically defined axis names known by the function.

func (*Function) LessOrEqual

func (f *Function) LessOrEqual(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) LessOrEqualTotalOrder

func (f *Function) LessOrEqualTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) LessThan

func (f *Function) LessThan(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) LessThanTotalOrder

func (f *Function) LessThanTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) Log

func (f *Function) Log(x compute.Value) (compute.Value, error)

func (*Function) Log1p

func (f *Function) Log1p(x compute.Value) (compute.Value, error)

func (*Function) LogicalAnd

func (f *Function) LogicalAnd(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) LogicalNot

func (f *Function) LogicalNot(x compute.Value) (compute.Value, error)

func (*Function) LogicalOr

func (f *Function) LogicalOr(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) LogicalXor

func (f *Function) LogicalXor(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) Logistic

func (f *Function) Logistic(x compute.Value) (compute.Value, error)

func (*Function) Max

func (f *Function) Max(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) Min

func (f *Function) Min(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) Mul

func (f *Function) Mul(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) Name

func (f *Function) Name() string

Name returns the name of this function. For closures, this returns "".

func (*Function) Neg

func (f *Function) Neg(x compute.Value) (compute.Value, error)

func (*Function) NewMultiOutputsNode

func (f *Function) NewMultiOutputsNode(
	opType compute.OpType,
	outputShapes []shapes.Shape,
	inputs ...*Node,
) (node *Node)

NewMultiOutputsNode creates the multi-outputs node, and its "select nodes", one per output. The node.multiOutputsNodes will be set with the individual outputs and can be used by the Builder to return to the user. Nodes are added to the function's nodes slice.

Note: no de-duplication of multi-output nodes.

func (*Function) NewNode

func (f *Function) NewNode(opType compute.OpType, shape shapes.Shape, inputs ...*Node) *Node

NewNode adds a new node of the given opType and shape to the function's graph. It's used by the other ops when creating new nodes. Nodes are added to the function's nodes slice.

Use getOrCreateNode instead for most operations.

func (*Function) NotEqual

func (f *Function) NotEqual(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) NotEqualTotalOrder

func (f *Function) NotEqualTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) OptimizationBarrier

func (f *Function) OptimizationBarrier(operands ...compute.Value) ([]compute.Value, error)

func (*Function) Pad

func (f *Function) Pad(x compute.Value, fillValue compute.Value, axesConfig ...compute.PadAxis) (compute.Value, error)

func (*Function) Parameter

func (f *Function) Parameter(name string, shape shapes.Shape, sharding *compute.ShardingSpec) (compute.Value, error)

Parameter creates an input parameter for this function.

func (*Function) Parent

func (f *Function) Parent() compute.Function

Parent returns the parent function if this is a closure. Returns nil for top-level functions (including main).

func (*Function) Pow

func (f *Function) Pow(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) QuantizedEmbeddingLookup

func (f *Function) QuantizedEmbeddingLookup(data compute.Value, indices compute.Value, dataQuantization *compute.Quantization) (compute.Value, error)

func (*Function) RNGBitGenerator

func (f *Function) RNGBitGenerator(state compute.Value, shape shapes.Shape) (newState compute.Value, values compute.Value, err error)

func (*Function) Real

func (f *Function) Real(x compute.Value) (compute.Value, error)

func (*Function) ReduceBitwiseAnd

func (f *Function) ReduceBitwiseAnd(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceBitwiseOr

func (f *Function) ReduceBitwiseOr(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceBitwiseXor

func (f *Function) ReduceBitwiseXor(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceLogicalAnd

func (f *Function) ReduceLogicalAnd(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceLogicalOr

func (f *Function) ReduceLogicalOr(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceLogicalXor

func (f *Function) ReduceLogicalXor(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceMax

func (f *Function) ReduceMax(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceMin

func (f *Function) ReduceMin(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceProduct

func (f *Function) ReduceProduct(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceSum

func (f *Function) ReduceSum(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceWindow

func (f *Function) ReduceWindow(input compute.Value, reductionType compute.ReduceOpType, windowDimensions []int, strides []int, inputDilations []int, windowDilations []int, paddings [][2]int) (compute.Value, error)

func (*Function) Rem

func (f *Function) Rem(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) Reshape

func (f *Function) Reshape(x compute.Value, dimensions ...int) (compute.Value, error)

func (*Function) Return

func (f *Function) Return(outputs []compute.Value, shardings []*compute.ShardingSpec) error

Return marks the outputs of this function.

func (*Function) Reverse

func (f *Function) Reverse(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) Round

func (f *Function) Round(x compute.Value) (compute.Value, error)

func (*Function) Rsqrt

func (f *Function) Rsqrt(x compute.Value) (compute.Value, error)

func (*Function) ScatterMax

func (f *Function) ScatterMax(operand compute.Value, scatterIndices compute.Value, updates compute.Value, indexVectorAxis int, updateWindowAxes []int, insertedWindowAxes []int, scatterAxesToOperandAxes []int, indicesAreSorted bool, uniqueIndices bool) (compute.Value, error)

func (*Function) ScatterMin

func (f *Function) ScatterMin(operand compute.Value, scatterIndices compute.Value, updates compute.Value, indexVectorAxis int, updateWindowAxes []int, insertedWindowAxes []int, scatterAxesToOperandAxes []int, indicesAreSorted bool, uniqueIndices bool) (compute.Value, error)

func (*Function) ScatterSum

func (f *Function) ScatterSum(operand compute.Value, scatterIndices compute.Value, updates compute.Value, indexVectorAxis int, updateWindowAxes []int, insertedWindowAxes []int, scatterAxesToOperandAxes []int, indicesAreSorted bool, uniqueIndices bool) (compute.Value, error)

func (*Function) SchedulingBarrier

func (f *Function) SchedulingBarrier(operand compute.Value, dependencies ...compute.Value) (compute.Value, error)

func (*Function) SelectAndScatterMax

func (f *Function) SelectAndScatterMax(operand compute.Value, source compute.Value, windowDimensions []int, windowStrides []int, paddings [][2]int) (compute.Value, error)

func (*Function) SelectAndScatterMin

func (f *Function) SelectAndScatterMin(operand compute.Value, source compute.Value, windowDimensions []int, windowStrides []int, paddings [][2]int) (compute.Value, error)

func (*Function) Shape

func (f *Function) Shape(v compute.Value) (shapes.Shape, error)

Shape returns the shape of a value in the function.

func (*Function) ShiftLeft

func (f *Function) ShiftLeft(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) ShiftRightArithmetic

func (f *Function) ShiftRightArithmetic(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) ShiftRightLogical

func (f *Function) ShiftRightLogical(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) Sign

func (f *Function) Sign(x compute.Value) (compute.Value, error)

func (*Function) Sin

func (f *Function) Sin(x compute.Value) (compute.Value, error)

func (*Function) Slice

func (f *Function) Slice(x compute.Value, starts []int, limits []int, strides []int) (compute.Value, error)

func (*Function) Sort

func (f *Function) Sort(comparator compute.Function, axis int, isStable bool, inputs ...compute.Value) ([]compute.Value, error)

func (*Function) Sqrt

func (f *Function) Sqrt(x compute.Value) (compute.Value, error)

func (*Function) String

func (f *Function) String() string

String returns a multi-line string with one line per node.

func (*Function) Sub

func (f *Function) Sub(lhs compute.Value, rhs compute.Value) (compute.Value, error)

func (*Function) Tanh

func (f *Function) Tanh(x compute.Value) (compute.Value, error)

func (*Function) Transpose

func (f *Function) Transpose(x compute.Value, permutation ...int) (compute.Value, error)

func (*Function) ValidateClosure

func (f *Function) ValidateClosure(opName, closureName string, closure compute.Function) (*Function, error)

ValidateClosure validates that a compute.Function is a compiled closure of the current function.

func (*Function) VerifyAndCastValues

func (f *Function) VerifyAndCastValues(name string, values ...compute.Value) ([]*Node, error)

VerifyAndCastValues sanity checks that the values (compute.Op) are valid and created with this builder. If a node belongs to a parent function, it creates a capture node to access the value. It returns the underlying *Node of the values (with capture nodes substituted for parent values).

func (*Function) Where

func (f *Function) Where(condition compute.Value, onTrue compute.Value, onFalse compute.Value) (compute.Value, error)

func (*Function) While

func (f *Function) While(cond compute.Function, body compute.Function, initialState ...compute.Value) ([]compute.Value, error)

type FunctionExecutable

type FunctionExecutable struct {
	Backend *Backend
	Builder *Builder

	// Function is the source Function this was compiled from.
	Function *Function

	// NumNodesToProcess is the max(outputs.idx)+1.
	// Arrays are sized to this to allow direct idx indexing.
	NumNodesToProcess int

	// Schedule represents the order in which nodes should be executed.
	// This should be optimized to minimize the latency/temporary memory.
	Schedule []int

	// NumUses tracks how many times each node's result is used (indexed by idx).
	NumUses []int

	// Dependents maps each node (by idx) to the list of dependent node idxs.
	Dependents [][]int

	// OutputNodes are the nodes that produce the function's outputs.
	OutputNodes []*Node

	// MaxInputs is the maximum number of inputs any node has.
	MaxInputs int

	// ExecutionBuffersPool allows reuse of execution buffers.
	ExecutionBuffersPool sync.Pool
}

FunctionExecutable contains pre-compiled execution information for any function. This is used for both the main function and closures, unifying their execution model.

func (*FunctionExecutable) CreationOrderSchedule

func (fe *FunctionExecutable) CreationOrderSchedule()

CreationOrderSchedule schedule nodes in creation order: a trivial sequentially increasing order.

func (*FunctionExecutable) DependencyOrderSchedule

func (fe *FunctionExecutable) DependencyOrderSchedule()

DependencyOrderSchedule schedules nodes in topological order, based on dependencies.

It schedules those with the longest path to an output first. If there are multiple nodes with the same longest path to an output, it will schedule them in creation order.

func (*FunctionExecutable) EstimatedTemporaryMemory

func (fe *FunctionExecutable) EstimatedTemporaryMemory() int64

EstimatedTemporaryMemory estimates the memory used for the function if executed sequentially.

It assumes temporary memory is used for every node output (using Shape.ByteSize()), and released everytime one node output is no longer needed (its output has been used fe.NumUses[nodeIdx] times). It does not actually execute the nodes, just simulates the execution to report back the maximum temporary memory live at any time.

func (*FunctionExecutable) Execute

func (fe *FunctionExecutable) Execute(backend *Backend, inputs []*Buffer, donate []bool, capturedInputs []*Buffer,
	donateCaptures []bool, spec *ShapeSpecialization) ([]*Buffer, error)

Execute runs the compiled function with the given inputs. The inputs must match the function's parameters in count and shape. capturedInputs are the values captured from parent scopes (for closures). donateCaptures indicates which captured inputs can be donated to the closure. If donateCaptures is nil, no captured inputs will be donated. spec is the shape specialization for the current execution, or nil for static graphs.

func (*FunctionExecutable) InitSchedule

func (fe *FunctionExecutable) InitSchedule()

InitSchedule initializes the execution schedule.

type GraphTransformation

type GraphTransformation interface {
	// Apply takes the current graph state and returns an optimized version.
	//
	// It should return dagModified=true, if new nodes were create out-of-order (at the end) and hence the DAG
	// order would have been broken, requiring a re-sort after the pass.
	Apply(builder *Builder) (dagModified bool, err error)
	Name() string
}

GraphTransformation is an optimizer of the graph, to be executed during compilation.

type Node

type Node struct {
	// Index is the index of this node in its function's nodes slice.
	Index  int
	Inputs []*Node

	// CapturedInputs holds nodes from parent scopes that are used by closures
	// called by this node (for ops like If, While, Sort that use closures).
	// Each inner slice corresponds to one closure's captured values.
	// These are treated as additional inputs for dependency tracking and lifetime management.
	CapturedInputs [][]*Node

	// shape of the output.
	OpType  compute.OpType
	Shape   shapes.Shape
	Builder *Builder

	// Function is the Function in which this node was created.
	// This is used to detect cross-Function node usage.
	Function *Function

	// MultiOutputsShapes are set for a few specialized nodes.
	// For most nodes this is set to nil.
	MultiOutputsShapes []shapes.Shape
	MultiOutputsNodes  []*Node
	IsNodeSelectOutput bool
	SelectOutputIdx    int

	// Data for the specific node type.
	Data any
}

Node in the Go backend computation graph.

func (*Node) AddNodeCapturedInputs

func (n *Node) AddNodeCapturedInputs(closure *Function)

AddNodeCapturedInputs adds captured inputs from a closure to this node. This should be called when building ops like If, While, Sort that use closures. For ops with multiple closures, call this once for each closure. Each closure's captured values are stored as a separate slice in node.capturedInputs, preserving the per-closure grouping for execution.

For nested closures, if the closure captures values from a grandparent, those values are propagated to the parent closure's required captures.

func (*Node) IsMultiOutputs

func (n *Node) IsMultiOutputs() bool

IsMultiOutputs returns whether this node yields multiple outputs.

func (*Node) MultiOutputValues

func (node *Node) MultiOutputValues() []compute.Value

MultiOutputValues converts a multi-output node's outputs to []compute.Value.

type NodeDataComparable

type NodeDataComparable interface {
	// EqualNodeData returns true if this data is semantically equivalent to other.
	// The other parameter is guaranteed to be the same concrete type.
	EqualNodeData(other NodeDataComparable) bool
}

NodeDataComparable is implemented by node data types that support de-duplication. Implementing this interface allows the Builder to automatically de-duplicate nodes with matching inputs and equivalent data.

type NodeDedupKey

type NodeDedupKey struct {
	OpType     compute.OpType
	InputCount int
	FirstInput *Node // nil if there are no inputs.
}

NodeDedupKey is used to index into the de-duplication map. It provides fast lookup for candidate nodes with the same operation type and input structure.

func MakeNodeDedupKey

func MakeNodeDedupKey(opType compute.OpType, inputs []*Node) NodeDedupKey

MakeNodeDedupKey creates a de-duplication key for a node with the given opType and inputs.

type NodeExecutor

type NodeExecutor func(backend *Backend, node *Node, inputs []*Buffer, inputsOwned []bool) (*Buffer, error)

NodeExecutor for the given operation type.

It is given the buffers for its inputs, and a reserved buffer where to store its output, already with the shape pre-calculated.

type NodeParameter

type NodeParameter struct {
	Name     string
	InputIdx int
}

NodeParameter data.

func (*NodeParameter) EqualNodeData

func (n *NodeParameter) EqualNodeData(other NodeDataComparable) bool

EqualNodeData implements nodeDataComparable for nodeParameter.

type OpHandlerRegistration

type OpHandlerRegistration[FN any] struct {
	Method   string
	Priority RegisterPriority
	Fn       FN
}

OpHandlerRegistration is a generic registration handler type for Function methods.

FN represents the function type, which should take as first parameter always the Function. Example for the op "Max(lhs, rhs Value) (Value, error)", FN would take the form "func(f *Function, lhs, rhs *Node) (*Node, error)".

func (*OpHandlerRegistration[FN]) Register

func (handler *OpHandlerRegistration[FN]) Register(fn FN, priority RegisterPriority)

Register registers a handler with the given priority. It will only override the op if the given priority is higher than the current one.

type OpsExecutionType

type OpsExecutionType int
const (
	OpsExecutionDynamic OpsExecutionType = iota
	OpsExecutionParallel
	OpsExecutionSequential
)

type PODBooleanConstraints

type PODBooleanConstraints interface {
	bool
}

PODBooleanConstraints is a simple placeholder for the gen_exec_binary.go generated code.

type PODFloatConstraints

type PODFloatConstraints interface {
	float32 | float64
}

PODFloatConstraints are used for generics for the Golang pod (plain-old-data) types. BFloat16 and Float16 are not included because they are specialized types, not natively supported by Go.

type PODIntegerConstraints

type PODIntegerConstraints interface {
	int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
}

PODIntegerConstraints are used for generics for the Golang pod (plain-old-data) types.

type PODNumericConstraints

type PODNumericConstraints interface {
	int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | float32 | float64
}

PODNumericConstraints are used for generics for the Golang pod (plain-old-data) types. BFloat16 is not included because it is a specialized type, not natively supported by Go.

type PODSignedNumericConstraints

type PODSignedNumericConstraints interface {
	int8 | int16 | int32 | int64 | float32 | float64
}

PODSignedNumericConstraints are used for generics for the Golang pod (plain-old-data) types. BFloat16 and Float16 are not included because they are specialized types, not natively supported by Go.

type PODUnsignedConstraints

type PODUnsignedConstraints interface {
	uint8 | uint16 | uint32 | uint64
}

PODUnsignedConstraints are used for generics for the Golang pod (plain-old-data) types.

type RecomputableNodeData

type RecomputableNodeData interface {
	// Recompute shape-dependent metadata from the resolved input shapes.
	// Returns a new Data object (or the same one if it's mutable and updated in-place).
	Recompute(backend *Backend, resolvedNodes []*Node, originalNode *Node) (any, error)
}

RecomputableNodeData is an interface that can be implemented by the Data field of a Node to allow recomputing shape-dependent metadata when specializing a dynamic graph.

type RegisterPriority

type RegisterPriority int

RegisterPriority defines the priority of a node executor. Highest priority takes precedence. Anything with priority < 0 is ignored.

const (
	PriorityGeneric RegisterPriority = 0
	PriorityTyped   RegisterPriority = 1   // Specialized typed implementation.
	PriorityArch    RegisterPriority = 10  // Specialized architecture implementation.
	PriorityUser    RegisterPriority = 100 // Custom user overrides.
)

type ScheduleStrategy

type ScheduleStrategy int

ScheduleStrategy defines the scheduling strategy to execute functions.

const (
	DependencyOrderSchedule ScheduleStrategy = iota
	CreationOrderSchedule
)

func ScheduleStrategyString

func ScheduleStrategyString(s string) (ScheduleStrategy, error)

ScheduleStrategyString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func ScheduleStrategyValues

func ScheduleStrategyValues() []ScheduleStrategy

ScheduleStrategyValues returns all values of the enum

func (ScheduleStrategy) IsAScheduleStrategy

func (i ScheduleStrategy) IsAScheduleStrategy() bool

IsAScheduleStrategy returns "true" if the value is listed in the enum definition. "false" otherwise

func (ScheduleStrategy) String

func (i ScheduleStrategy) String() string

type ShapeSpecialization

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

ShapeSpecialization holds a resolved-shape copy of the graph nodes for a specific set of axis bindings. Each specialization is created lazily on first execution with a given binding and cached for reuse.

The resolvedNodes are shallow copies of the original Function.nodes. Only the shape field (and multiOutputsShapes for multi-output nodes) is resolved; all other fields (inputs, capturedInputs, opType, etc.) are shared with the originals. This allows executor functions to read node.Shape and get concrete values without any signature changes.

type SupportedTypesConstraints

type SupportedTypesConstraints interface {
	bool | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | float32 | float64 |
		bfloat16.BFloat16 | float16.Float16
}

SupportedTypesConstraints enumerates the types supported by the Go backend.

type ZipIterator

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

ZipIterator allows iteration over the flat indices of the target shape of a broadcast (where some axis dimensions grow) for two input shapes (LHS and RHS).

It implements the implicit broadcasting for binary ops like Add, Sub, Mul, Div, etc.

func NewZippedBroadcastIterator

func NewZippedBroadcastIterator(lhsShape, rhsShape, tgtShape shapes.Shape) *ZipIterator

NewZippedBroadcastIterator returns an iterator constructor over the flat indices of the target shape of a broadcast (where some axis dimensions grow) for two input shapes (LHS and RHS).

Pre-requisite: lhsShape.Rank() == tgtShape.Rank() && rhsShape.Rank() == tgtShape.Rank().

It implements the implicit broadcasting for binary ops like Add, Sub, Mul, Div, etc.

func (*ZipIterator) EqualNodeData

func (z *ZipIterator) EqualNodeData(other NodeDataComparable) bool

EqualNodeData implements NodeDataComparable, so this can be used as NodeData -- the comparison is used for deduping repeated nodes during model building.

func (*ZipIterator) IterFlatIndices

func (zi *ZipIterator) IterFlatIndices() iter.Seq[ZippedIndices]

IterFlatIndices iterate over the lhs, rhs and target flat indices for broadcast. Notice since we are broadcasting, the target index will always be incremented by 1, while the source indices may repeat (when it is being broadcast).

type ZippedIndices

type ZippedIndices struct {
	LHSFlatIdx, RHSFlatIdx int
	TgtFlatIdx             int
}

ZippedIndices of two BroadcastIterators.

Directories

Path Synopsis
Package defaultpkgs imports all the sub-packages that implement the gobackend.
Package defaultpkgs imports all the sub-packages that implement the gobackend.
dot
Package dot implements a general-purpose "dot product" ("Einsum") computation.
Package dot implements a general-purpose "dot product" ("Einsum") computation.
matmul
package matmul provides the base implementations of matrx multiply for DotGeneral.
package matmul provides the base implementations of matrx multiply for DotGeneral.
Package ops has the base implementation for most operations for the Go backend.
Package ops has the base implementation for most operations for the Go backend.

Jump to

Keyboard shortcuts

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