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
- Variables
- func CheckClosureParams(opName, closureName string, fn *Function, expected []*Node) error
- func CopyFlat(flatDst, flatSrc any)
- func DataEqual(a, b any) bool
- func MutableBytesGeneric[T SupportedTypesConstraints](b *Buffer) ([]byte, error)
- func New(config string) (compute.Backend, error)
- func RegisterTransformation(priority int, transformation GraphTransformation)
- func ScheduleStrategyStrings() []string
- func SetNodeExecutor(opType compute.OpType, priority RegisterPriority, executor NodeExecutor)
- type Backend
- func (b *Backend) BufferFromFlatData(deviceNum compute.DeviceNum, flat any, shape shapes.Shape) (compute.Buffer, error)
- func (b *Backend) Builder(name string) compute.Builder
- func (b *Backend) Capabilities() compute.Capabilities
- func (b *Backend) CloneBuffer(buffer *Buffer) (*Buffer, error)
- func (b *Backend) Description() string
- func (b *Backend) DeviceDescription(_ compute.DeviceNum) string
- func (b *Backend) Finalize()
- func (b *Backend) GetBuffer(shape shapes.Shape) (*Buffer, error)
- func (b *Backend) HasSharedBuffers() bool
- func (b *Backend) IsFinalized() bool
- func (b *Backend) Name() string
- func (b *Backend) NewBuffer(shape shapes.Shape) *Buffer
- func (b *Backend) NewSharedBuffer(deviceNum compute.DeviceNum, shape shapes.Shape) (buffer compute.Buffer, flat any, err error)
- func (b *Backend) NumDevices() int
- func (b *Backend) PutBuffer(buffer *Buffer)
- func (b *Backend) String() string
- type BroadcastIterator
- type Buffer
- func (buffer *Buffer) Backend() compute.Backend
- func (buffer *Buffer) Check() error
- func (buffer *Buffer) CopyToDevice(deviceNum compute.DeviceNum) (compute.Buffer, error)
- func (buffer *Buffer) Data() (flat any, err error)
- func (buffer *Buffer) DeviceNum() (compute.DeviceNum, error)
- func (b *Buffer) EqualNodeData(other NodeDataComparable) bool
- func (b *Buffer) Fill(value any) error
- func (buffer *Buffer) Finalize() error
- func (b *Buffer) MutableBytes() ([]byte, error)
- func (b *Buffer) Ones() *Buffer
- func (buffer *Buffer) Shape() (shapes.Shape, error)
- func (buffer *Buffer) ToFlatData(flat any) error
- func (b *Buffer) Zeros() *Buffer
- type Builder
- func (b *Builder) Compile() (compute.Executable, error)
- func (b *Builder) DAGSort() error
- func (b *Builder) Finalize()
- func (b *Builder) Main() compute.Function
- func (b *Builder) Name() string
- func (b *Builder) NewFunction(name string) (compute.Function, error)
- func (b *Builder) OpShape(op compute.Value) (shapes.Shape, error)
- func (b *Builder) Optimize() error
- func (b *Builder) String() string
- type ClosureInputs
- type DTypeMap
- type DTypePairMap
- type Executable
- type Function
- func (f *Function) Abs(x compute.Value) (compute.Value, error)
- func (f *Function) Add(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) AllReduce(_ []compute.Value, _ compute.ReduceOpType, _ [][]int) ([]compute.Value, error)
- func (f *Function) ArgMinMax(x compute.Value, axis int, outputDType dtypes.DType, isMin bool) (compute.Value, error)
- func (f *Function) Atan2(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) BatchNormForInference(operand compute.Value, scale compute.Value, offset compute.Value, ...) (compute.Value, error)
- func (f *Function) BatchNormForTraining(operand compute.Value, scale compute.Value, offset compute.Value, ...) (normalized compute.Value, batchMean compute.Value, batchVariance compute.Value, ...)
- func (f *Function) BatchNormGradient(operand compute.Value, scale compute.Value, mean compute.Value, ...) (gradOperand compute.Value, gradScale compute.Value, gradOffset compute.Value, ...)
- func (f *Function) BitCount(operand compute.Value) (compute.Value, error)
- func (f *Function) Bitcast(operand compute.Value, targetDType dtypes.DType) (compute.Value, error)
- func (f *Function) BitwiseAnd(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) BitwiseNot(x compute.Value) (compute.Value, error)
- func (f *Function) BitwiseOr(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) BitwiseXor(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) BroadcastInDim(operand compute.Value, outputShape shapes.Shape, broadcastAxes []int) (compute.Value, error)
- func (f *Function) Builder() compute.Builder
- func (f *Function) Call(fn compute.Function, inputs ...compute.Value) ([]compute.Value, error)
- func (f *Function) Ceil(x compute.Value) (compute.Value, error)
- func (f *Function) CheckValid() error
- func (f *Function) Clamp(min compute.Value, x compute.Value, max compute.Value) (compute.Value, error)
- func (f *Function) Closure() (compute.Function, error)
- func (f *Function) Clz(x compute.Value) (compute.Value, error)
- func (f *Function) Complex(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) Concatenate(axis int, operands ...compute.Value) (compute.Value, error)
- func (f *Function) Conj(x compute.Value) (compute.Value, error)
- func (f *Function) Constant(flat any, dims ...int) (compute.Value, error)
- func (f *Function) ConvGeneral(input compute.Value, kernel compute.Value, axes compute.ConvolveAxesConfig, ...) (compute.Value, error)
- func (f *Function) ConvertDType(x compute.Value, dtype dtypes.DType) (compute.Value, error)
- func (f *Function) Cos(x compute.Value) (compute.Value, error)
- func (f *Function) CumSum(operand compute.Value, axis int, options compute.CumSumOptions) (compute.Value, error)
- func (f *Function) DAGSort() error
- func (f *Function) Div(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) DotGeneral(lhs compute.Value, lhsContractingAxes []int, lhsBatchAxes []int, ...) (compute.Value, error)
- func (f *Function) DynamicBroadcastInDim(operand compute.Value, broadcastAxes []int, ...) (compute.Value, error)
- func (f *Function) DynamicDimensionSize(operand compute.Value, axis int) (compute.Value, error)
- func (f *Function) DynamicIota(dtype dtypes.DType, iotaAxis int, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)
- func (f *Function) DynamicPad(x compute.Value, fillValue compute.Value, axesConfig ...compute.DynamicPadAxis) (compute.Value, error)
- func (f *Function) DynamicReshape(operand compute.Value, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)
- func (f *Function) DynamicShape(operand compute.Value) (compute.Value, error)
- func (f *Function) DynamicSlice(operand compute.Value, startIndices []compute.Value, sliceDims []int) (compute.Value, error)
- func (f *Function) DynamicUpdateSlice(operand compute.Value, update compute.Value, startIndices []compute.Value) (compute.Value, error)
- func (f *Function) Equal(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) EqualTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) Erf(x compute.Value) (compute.Value, error)
- func (f *Function) Exp(x compute.Value) (compute.Value, error)
- func (f *Function) Expm1(x compute.Value) (compute.Value, error)
- func (f *Function) FFT(operand compute.Value, fftType compute.FFTType, fftLength []int) (compute.Value, error)
- func (f *Function) Floor(x compute.Value) (compute.Value, error)
- func (f *Function) FusedAttentionQKVProjection(x compute.Value, wQKV compute.Value, biasQ compute.Value, biasK compute.Value, ...) (query compute.Value, key compute.Value, value compute.Value, err error)
- func (f *Function) FusedDense(x compute.Value, weight compute.Value, bias compute.Value, ...) (compute.Value, error)
- func (f *Function) FusedGelu(x compute.Value, exact bool) (compute.Value, error)
- func (f *Function) FusedLayerNorm(x compute.Value, axes []int, epsilon float64, gamma compute.Value, ...) (compute.Value, error)
- func (f *Function) FusedQuantizedDense(x compute.Value, weights compute.Value, bias compute.Value, ...) (compute.Value, error)
- func (f *Function) FusedScaledDotProductAttention(query compute.Value, key compute.Value, value compute.Value, ...) (output compute.Value, statesForVJP []compute.Value, err error)
- func (f *Function) FusedScaledDotProductAttentionVJP(query compute.Value, key compute.Value, value compute.Value, ...) (dQuery compute.Value, dKey compute.Value, dValue compute.Value, err error)
- func (f *Function) FusedSoftmax(x compute.Value, axis int) (compute.Value, error)
- func (f *Function) Gather(operand compute.Value, startIndices compute.Value, indexVectorAxis int, ...) (compute.Value, error)
- func (f *Function) GetOrCreateCaptureNode(parentNode *Node) *Node
- func (f *Function) GetOrCreateNode(opType compute.OpType, shape shapes.Shape, inputs []*Node, data any) (n *Node, found bool)
- func (f *Function) GreaterOrEqual(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) GreaterOrEqualTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) GreaterThan(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) GreaterThanTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) Identity(x compute.Value) (compute.Value, error)
- func (f *Function) If(pred compute.Value, trueBranch compute.Function, falseBranch compute.Function) ([]compute.Value, error)
- func (f *Function) Imag(x compute.Value) (compute.Value, error)
- func (f *Function) Iota(shape shapes.Shape, iotaAxis int) (compute.Value, error)
- func (f *Function) IsAncestorOf(leafFunc *Function) bool
- func (f *Function) IsFinite(x compute.Value) (compute.Value, error)
- func (f *Function) IsNaN(x compute.Value) (compute.Value, error)
- func (f *Function) KnownDynamicAxisNames() sets.Set[string]
- func (f *Function) LessOrEqual(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) LessOrEqualTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) LessThan(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) LessThanTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) Log(x compute.Value) (compute.Value, error)
- func (f *Function) Log1p(x compute.Value) (compute.Value, error)
- func (f *Function) LogicalAnd(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) LogicalNot(x compute.Value) (compute.Value, error)
- func (f *Function) LogicalOr(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) LogicalXor(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) Logistic(x compute.Value) (compute.Value, error)
- func (f *Function) Max(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) Min(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) Mul(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) Name() string
- func (f *Function) Neg(x compute.Value) (compute.Value, error)
- func (f *Function) NewMultiOutputsNode(opType compute.OpType, outputShapes []shapes.Shape, inputs ...*Node) (node *Node)
- func (f *Function) NewNode(opType compute.OpType, shape shapes.Shape, inputs ...*Node) *Node
- func (f *Function) NotEqual(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) NotEqualTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) OptimizationBarrier(operands ...compute.Value) ([]compute.Value, error)
- func (f *Function) Pad(x compute.Value, fillValue compute.Value, axesConfig ...compute.PadAxis) (compute.Value, error)
- func (f *Function) Parameter(name string, shape shapes.Shape, sharding *compute.ShardingSpec) (compute.Value, error)
- func (f *Function) Parent() compute.Function
- func (f *Function) Pow(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) QuantizedEmbeddingLookup(data compute.Value, indices compute.Value, ...) (compute.Value, error)
- func (f *Function) RNGBitGenerator(state compute.Value, shape shapes.Shape) (newState compute.Value, values compute.Value, err error)
- func (f *Function) Real(x compute.Value) (compute.Value, error)
- func (f *Function) ReduceBitwiseAnd(x compute.Value, axes ...int) (compute.Value, error)
- func (f *Function) ReduceBitwiseOr(x compute.Value, axes ...int) (compute.Value, error)
- func (f *Function) ReduceBitwiseXor(x compute.Value, axes ...int) (compute.Value, error)
- func (f *Function) ReduceLogicalAnd(x compute.Value, axes ...int) (compute.Value, error)
- func (f *Function) ReduceLogicalOr(x compute.Value, axes ...int) (compute.Value, error)
- func (f *Function) ReduceLogicalXor(x compute.Value, axes ...int) (compute.Value, error)
- func (f *Function) ReduceMax(x compute.Value, axes ...int) (compute.Value, error)
- func (f *Function) ReduceMin(x compute.Value, axes ...int) (compute.Value, error)
- func (f *Function) ReduceProduct(x compute.Value, axes ...int) (compute.Value, error)
- func (f *Function) ReduceSum(x compute.Value, axes ...int) (compute.Value, error)
- func (f *Function) ReduceWindow(input compute.Value, reductionType compute.ReduceOpType, ...) (compute.Value, error)
- func (f *Function) Rem(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) Reshape(x compute.Value, dimensions ...int) (compute.Value, error)
- func (f *Function) Return(outputs []compute.Value, shardings []*compute.ShardingSpec) error
- func (f *Function) Reverse(x compute.Value, axes ...int) (compute.Value, error)
- func (f *Function) Round(x compute.Value) (compute.Value, error)
- func (f *Function) Rsqrt(x compute.Value) (compute.Value, error)
- func (f *Function) ScatterMax(operand compute.Value, scatterIndices compute.Value, updates compute.Value, ...) (compute.Value, error)
- func (f *Function) ScatterMin(operand compute.Value, scatterIndices compute.Value, updates compute.Value, ...) (compute.Value, error)
- func (f *Function) ScatterSum(operand compute.Value, scatterIndices compute.Value, updates compute.Value, ...) (compute.Value, error)
- func (f *Function) SchedulingBarrier(operand compute.Value, dependencies ...compute.Value) (compute.Value, error)
- func (f *Function) SelectAndScatterMax(operand compute.Value, source compute.Value, windowDimensions []int, ...) (compute.Value, error)
- func (f *Function) SelectAndScatterMin(operand compute.Value, source compute.Value, windowDimensions []int, ...) (compute.Value, error)
- func (f *Function) Shape(v compute.Value) (shapes.Shape, error)
- func (f *Function) ShiftLeft(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) ShiftRightArithmetic(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) ShiftRightLogical(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) Sign(x compute.Value) (compute.Value, error)
- func (f *Function) Sin(x compute.Value) (compute.Value, error)
- func (f *Function) Slice(x compute.Value, starts []int, limits []int, strides []int) (compute.Value, error)
- func (f *Function) Sort(comparator compute.Function, axis int, isStable bool, inputs ...compute.Value) ([]compute.Value, error)
- func (f *Function) Sqrt(x compute.Value) (compute.Value, error)
- func (f *Function) String() string
- func (f *Function) Sub(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f *Function) Tanh(x compute.Value) (compute.Value, error)
- func (f *Function) Transpose(x compute.Value, permutation ...int) (compute.Value, error)
- func (f *Function) ValidateClosure(opName, closureName string, closure compute.Function) (*Function, error)
- func (f *Function) VerifyAndCastValues(name string, values ...compute.Value) ([]*Node, error)
- func (f *Function) Where(condition compute.Value, onTrue compute.Value, onFalse compute.Value) (compute.Value, error)
- func (f *Function) While(cond compute.Function, body compute.Function, initialState ...compute.Value) ([]compute.Value, error)
- type FunctionExecutable
- func (fe *FunctionExecutable) CreationOrderSchedule()
- func (fe *FunctionExecutable) DependencyOrderSchedule()
- func (fe *FunctionExecutable) EstimatedTemporaryMemory() int64
- func (fe *FunctionExecutable) Execute(backend *Backend, inputs []*Buffer, donate []bool, capturedInputs []*Buffer, ...) ([]*Buffer, error)
- func (fe *FunctionExecutable) InitSchedule()
- type GraphTransformation
- type Node
- type NodeDataComparable
- type NodeDedupKey
- type NodeExecutor
- type NodeParameter
- type OpHandlerRegistration
- type OpsExecutionType
- type PODBooleanConstraints
- type PODFloatConstraints
- type PODIntegerConstraints
- type PODNumericConstraints
- type PODSignedNumericConstraints
- type PODUnsignedConstraints
- type RecomputableNodeData
- type RegisterPriority
- type ScheduleStrategy
- type ShapeSpecialization
- type SupportedTypesConstraints
- type ZipIterator
- type ZippedIndices
Constants ¶
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" )
const BackendName = "go"
BackendName to be used in GOMLX_BACKEND to specify this backend.
const MaxDTypes = 32
Variables ¶
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 )
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.
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.
var ErrBackendAlreadyFinalized = stderrors.New("backend already exists")
ErrBackendAlreadyFinalized is returned when attempting to register or initialize a backend that already exists.
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.
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.
var NumericDTypes = []dtypes.DType{ dtypes.Int8, dtypes.Int16, dtypes.Int32, dtypes.Int64, dtypes.Uint8, dtypes.Uint16, dtypes.Uint32, dtypes.Uint64, dtypes.Float16, dtypes.Float32, dtypes.Float64, dtypes.BFloat16, }
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 ¶
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 ¶
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 ¶
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) Capabilities ¶
func (b *Backend) Capabilities() compute.Capabilities
Capabilities method returns information about what is supported by this backend.
func (*Backend) CloneBuffer ¶
CloneBuffer using the pool to allocate a new one.
func (*Backend) Description ¶
Description is a longer description of the Backend that can be used to pretty-print.
func (*Backend) DeviceDescription ¶
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 ¶
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 ¶
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 ¶
IsFinalized returns true if the backend has been isFinalized.
func (*Backend) Name ¶
Name returns the short name of the backend. E.g.: "xla" for the Xla/PJRT plugin.
func (*Backend) NewBuffer ¶
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 ¶
NumDevices return the number of devices available for this 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) Check ¶
Check does a sanity-check on the buffer. Returns a corresponding error if something is wrong.
Used only for debugging.
func (*Buffer) CopyToDevice ¶
BufferCopyToDevice implements the compute.Backend interface. CopyToDevice implements the compute.Buffer interface.
func (*Buffer) Data ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Ones fills the buffer with ones.
It returns a reference to the buffer to allow cascading calls.
func (*Buffer) Shape ¶
BufferShape returns the shape for the buffer. Shape returns the shape for the buffer.
func (*Buffer) ToFlatData ¶
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.
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 ¶
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) NewFunction ¶
NewFunction creates a new named function within this builder. Named functions can be called with Call() and are independent of the main 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 ¶
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])
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 ¶
Stub methods that converts compute.Value to *Node and dispatches to the corresponding op handler.
func (*Function) AllReduce ¶
func (f *Function) AllReduce(_ []compute.Value, _ compute.ReduceOpType, _ [][]int) ([]compute.Value, error)
AllReduce implements the compute.CollectiveOps interface.
func (*Function) BatchNormForInference ¶
func (*Function) BatchNormForTraining ¶
func (*Function) BatchNormGradient ¶
func (*Function) BitwiseAnd ¶
func (*Function) BitwiseXor ¶
func (*Function) BroadcastInDim ¶
func (*Function) CheckValid ¶
CheckValid returns an error if the builder or the function are not ok.
func (*Function) Closure ¶
Closure creates a new closure function within this function. Closures can access values from their parent function's scope.
func (*Function) Concatenate ¶
func (*Function) Constant ¶
Constant creates a constant in the function with the given flat values and the shape defined by the dimensions.
func (*Function) ConvGeneral ¶
func (*Function) ConvertDType ¶
func (*Function) DotGeneral ¶
func (*Function) DynamicBroadcastInDim ¶ added in v0.1.5
func (*Function) DynamicDimensionSize ¶
func (*Function) DynamicIota ¶ added in v0.1.5
func (*Function) DynamicPad ¶ added in v0.1.5
func (*Function) DynamicReshape ¶ added in v0.1.1
func (*Function) DynamicShape ¶
func (*Function) DynamicSlice ¶
func (*Function) DynamicUpdateSlice ¶
func (*Function) EqualTotalOrder ¶
func (*Function) FusedAttentionQKVProjection ¶
func (*Function) FusedDense ¶
func (*Function) FusedLayerNorm ¶
func (*Function) FusedQuantizedDense ¶
func (*Function) FusedScaledDotProductAttention ¶
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 (*Function) GetOrCreateCaptureNode ¶
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 (*Function) GreaterOrEqualTotalOrder ¶
func (*Function) GreaterThan ¶
func (*Function) GreaterThanTotalOrder ¶
func (*Function) IsAncestorOf ¶
IsAncestorOf checks whether f is an ancestor of leafFunc. It returns true if f == leafFunc.
Typically, leafFunc will be a closure.
func (*Function) KnownDynamicAxisNames ¶
KnownDynamicAxisNames returns the set of dynamically defined axis names known by the function.
func (*Function) LessOrEqual ¶
func (*Function) LessOrEqualTotalOrder ¶
func (*Function) LessThanTotalOrder ¶
func (*Function) LogicalAnd ¶
func (*Function) LogicalXor ¶
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 ¶
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) NotEqualTotalOrder ¶
func (*Function) OptimizationBarrier ¶
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 ¶
Parent returns the parent function if this is a closure. Returns nil for top-level functions (including main).
func (*Function) QuantizedEmbeddingLookup ¶
func (*Function) RNGBitGenerator ¶
func (*Function) ReduceBitwiseAnd ¶
func (*Function) ReduceBitwiseOr ¶
func (*Function) ReduceBitwiseXor ¶
func (*Function) ReduceLogicalAnd ¶
func (*Function) ReduceLogicalOr ¶
func (*Function) ReduceLogicalXor ¶
func (*Function) ReduceProduct ¶
func (*Function) ReduceWindow ¶
func (*Function) ScatterMax ¶
func (*Function) ScatterMin ¶
func (*Function) ScatterSum ¶
func (*Function) SchedulingBarrier ¶
func (*Function) SelectAndScatterMax ¶
func (*Function) SelectAndScatterMin ¶
func (*Function) ShiftRightArithmetic ¶
func (*Function) ShiftRightLogical ¶
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 ¶
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).
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 ¶
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 ¶
IsMultiOutputs returns whether this node yields multiple outputs.
func (*Node) MultiOutputValues ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ZippedIndices of two BroadcastIterators.
Source Files
¶
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. |
|
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. |