Documentation
¶
Overview ¶
Package graph is the core package for GoMLX. It is used to create and run computation graphs on different compute.
The graph package also includes an automatic differentiation system and many useful higher-level operations.
The main elements in the package (or related) are:
Exec is the driver that manages the lifecycle (Graph creation, compilation, caching, and execution) across different input shapes. This is where most use cases start.
Graph is the blueprint for a specific computation with specific input shapes. It's usually created by an Exec object, built by an ExecGraphFn, and then cached and executed by the Exec.
Node represents a symbolic value in the computation. This can be an input parameter, a variable/constant, or the result of an operation ("op" for short, e.g.: Add, Sub, Mul, Sigmoid, Reshape, etc.). Each node has a fixed shape known in "graph building time" (see discussion below).
Compute Backends ¶
Graphs created by this package eventually translate to a lower-level "backend" responsible to JIT-compiling and then executing the graph. The default backend is XLA/PJRT (using github.com/gomlx/go-xla), the same backend used by JAX, TensorFlow and optionally also PyTorch. There is also a pure Go backend that is much slower, but functional for many use cases and very portable (e.g., it works in WebAssembly in a browser). Other backends are in the plans, and one can implement their own custom backends -- only the operations one uses.
You have to import the backend(s) you are going to support. You can also import the default selection with:
import _ "github.com/gomlx/gomlx/backends/default"
Error Handling ¶
Graph (and its Node's) methods "throw" errors with panic(). This prevents having to manage error returning for every operation (Add, Sub, Mul, etc.) and makes the code more readable. It always throws meaningful error messages, with the full stacktrace, to ease tracking bugs and solve issues.
The convention when writing graph building functions is to follow the same pattern: throw (panic) errors with stack traces (and useful actionable messages).
Notice that unfortunately, there is no way to statically, in compile time, check for many of the errors that for a human would be relatively easy to spot without running the program. But typically compilation of the computation graph happens early in the execution of a program, so such errors are caught early. Here we commonly further split the usual "compile time / runtime" into "compile time / graph building time / runtime", where "graph building time" is when the graph for a model is built and compiled, before it's executed and used. It is similar to the compilation of regexps or templates in Go.
Writing Code With Graphs ¶
When using ML frameworks, it's convenient to split the usual "compile time / runtime" into 3 phases:
Compile time: this is during Go compilation. Some amount of type checking is done here, but most of the tensor shape compatibility (adding tensors of different shapes types of errors) cannot be done statically here, unfortunately.
Graph building time: this is when one is building a computation Graph, using the various ops (Add, Sub, Mul, ReduceSum, etc.). No actual computation happens here; all is symbolic manipulation of Node (virtual tensors if you will), that will be executed later. This happens in "runtime", meaning after the Go program is compiled, but usually very early in a program. Here shapes are checked and useful errors (with stack-traces) are reported back. This means that development often involves coding and then running the Graph building to see if shapes are correct and what one wants -- graph building is very fast, since no data is actually manipulated. Creating tests that just build the graph is the recommended way to develop -- or have it happen very early in the program. Quick sketching of code can be done conveniently on a Jupyter Notebook — see [1] for Jupyter notebook support for the Go language.
Training/Evaluation/Runtime: this happens after the Graph is built and compiled, and all one does is feed values in and get the computation out -- using a very fast just-in-time compiled code. Error reports here are terser and harder to debug (they come from the underlying C++ library), but usually most of the issues are caught during the graph building time. One hard issue that occurs while training models are `NaN` (due to explosion of gradients), which is unrelated to the library itself, but rather the math. Under the package graph there is a `nanlogger` library that helps identify where `NaN` or `Inf` first appears in the middle of computation.
TODO: provide annotations and a linter to validate shapes pre-compilation. Alternatively, create an intermediary language with proper shape checking.
[1]: Jupyter Notebook kernel for Go: https://github.com/janpfeifer/gonb
Functions ¶
When the Graph is created a "main" function is automatically associated with it and everything goes into it. Typically, a model will be a giant "main" function.
Some backends support other top-level functions (uniquely named) and closures (functions that can capture variables from the parent scope). See NewFunction and NewClosure to create those, and Call to execute top-level functions.
The graph has a field associated to the CurrentFunction(), on which define some operations like Parameters and Const will be created. It is initialized to the "main" function, and it is only temporarily changed inside NewFunction and NewClosure.
Index ¶
- Constants
- Variables
- func BackendFusedScaledDotProductAttention(query, key, value *Node, axesLayout compute.AttentionAxesLayout, ...) (output *Node, statesForVJP []*Node)
- func CallOnce[F ExecGraphFnOneOutput](backend compute.Backend, graphFn F, args ...any) (*tensors.Tensor, error)
- func CallOnceN[F ExecGraphFn](backend compute.Backend, graphFn F, args ...any) ([]*tensors.Tensor, error)
- func DefaultNodeLogger(g *Graph, messages []string, values []*tensors.Tensor, nodes []NodeId)
- func DonateTensorBuffer(t *tensors.Tensor, backend compute.Backend, deviceNum compute.DeviceNum) (any, error)
- func ExecOnce[F ExecGraphFnOneOutput](backend compute.Backend, graphFn F, args ...any) (*tensors.Tensor, error)deprecated
- func ExecOnceN[F ExecGraphFn](backend compute.Backend, graphFn F, args ...any) ([]*tensors.Tensor, error)deprecated
- func InternalBackendOutputs(n *Node) []compute.Value
- func MustAdjustAxis(axis int, operand shapes.HasShape) int
- func MustExecOnce[F ExecGraphFnOneOutput](backend compute.Backend, graphFn F, args ...any) *tensors.Tensor
- func MustExecOnceN[F ExecGraphFn](backend compute.Backend, graphFn F, args ...any) []*tensors.Tensor
- func NodeTypeStrings() []string
- func RNGState() (*tensors.Tensor, error)
- func RNGStateFromSeed(seed int64) (*tensors.Tensor, error)
- type CanonicalExecGraphFn
- type ConvolutionBuilder
- func (conv *ConvolutionBuilder) AxesConfig(axes ConvolveAxesConfig) *ConvolutionBuilder
- func (conv *ConvolutionBuilder) BatchGroupCount(groupCount int) *ConvolutionBuilder
- func (conv *ConvolutionBuilder) ChannelGroupCount(groupCount int) *ConvolutionBuilder
- func (conv *ConvolutionBuilder) ChannelsAxis(channelsAxisConfig timage.ChannelsAxisConfig) *ConvolutionBuilder
- func (conv *ConvolutionBuilder) DilationPerAxis(dilations ...int) *ConvolutionBuilder
- func (conv *ConvolutionBuilder) DilationPerDim(dilations ...int) *ConvolutionBuilderdeprecated
- func (conv *ConvolutionBuilder) Dilations(dilation int) *ConvolutionBuilder
- func (conv *ConvolutionBuilder) Done() *Node
- func (conv *ConvolutionBuilder) FeatureGroupCount(groupCount int) *ConvolutionBuilderdeprecated
- func (conv *ConvolutionBuilder) InputDilationPerAxis(dilations ...int) *ConvolutionBuilder
- func (conv *ConvolutionBuilder) NoPadding() *ConvolutionBuilder
- func (conv *ConvolutionBuilder) PadSame() *ConvolutionBuilder
- func (conv *ConvolutionBuilder) PaddingPerDim(paddings [][2]int) *ConvolutionBuilder
- func (conv *ConvolutionBuilder) StridePerAxis(strides ...int) *ConvolutionBuilder
- func (conv *ConvolutionBuilder) StridePerDim(strides ...int) *ConvolutionBuilderdeprecated
- func (conv *ConvolutionBuilder) Strides(strides int) *ConvolutionBuilder
- type ConvolveAxesConfig
- type CumSumOptions
- type DimensionSpec
- func DimensionSpecFor(x *Node, axis int) DimensionSpec
- func DimensionSpecsFor(x *Node) []DimensionSpec
- func DynamicDim(dim *Node) DimensionSpec
- func InferredDim() DimensionSpec
- func NamedDynamicDim(name string, dim *Node) DimensionSpec
- func NamedInferredDim(name string) DimensionSpec
- func StaticDim(dim int) DimensionSpec
- func (s DimensionSpec) AxisName() string
- func (s DimensionSpec) Clone() DimensionSpec
- func (s DimensionSpec) Dynamic() *Node
- func (s DimensionSpec) IsDynamic() bool
- func (s DimensionSpec) IsInferred() bool
- func (s DimensionSpec) IsStatic() bool
- func (s DimensionSpec) Static() int
- func (s DimensionSpec) String() string
- func (s DimensionSpec) WithName(name string) DimensionSpec
- type DistributedOps
- type DotBuilder
- func (b *DotBuilder) Einsum(equation string) *Node
- func (b *DotBuilder) EinsumAxes(contractingAxes, batchAxes [][2]int) (output *Node)
- func (b *DotBuilder) General(lhsContractingAxes, lhsBatchAxes []int, rhsContractingAxes, rhsBatchAxes []int) *Node
- func (b *DotBuilder) MatMul() *Node
- func (b *DotBuilder) Product() *Node
- func (b *DotBuilder) WithAccumulatorDType(dtype dtypes.DType) *DotBuilder
- func (b *DotBuilder) WithOutputDType(dtype dtypes.DType) *DotBuilder
- type DynamicPadAxisSpec
- type Exec
- func MustNewExec[F ExecGraphFn](backend compute.Backend, graphFn F) *Exec
- func MustNewExecCanonical(backend compute.Backend, graphFn CanonicalExecGraphFn, ...) *Exec
- func NewExec[F ExecGraphFn](backend compute.Backend, graphFn F) (*Exec, error)
- func NewExecCanonical(backend compute.Backend, graphFn CanonicalExecGraphFn, ...) (*Exec, error)
- func (e *Exec) AggregateShards(shards []*tensors.Tensor) ([]*dtensor.Tensor, error)
- func (e *Exec) AutoSharding(meshes ...*distributed.DeviceMesh) *Exec
- func (e *Exec) Call(args ...any) ([]*tensors.Tensor, error)
- func (e *Exec) Call1(args ...any) (*tensors.Tensor, error)
- func (e *Exec) Call2(args ...any) (*tensors.Tensor, *tensors.Tensor, error)
- func (e *Exec) Call3(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, error)
- func (e *Exec) Call4(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, *tensors.Tensor, error)
- func (e *Exec) CallOnDevice(defaultDevice compute.DeviceNum, args ...any) ([]*tensors.Tensor, error)
- func (e *Exec) CallWithGraph(args ...any) ([]*tensors.Tensor, *Graph, error)
- func (e *Exec) CallWithGraphOnDevice(defaultDevice compute.DeviceNum, args ...any) ([]*tensors.Tensor, *Graph, error)
- func (e *Exec) Compile(inputShapes ...shapes.Shape) (*Graph, error)
- func (e *Exec) DeviceAssignment() []compute.DeviceNum
- func (e *Exec) DistributedCall(args ...any) ([]*dtensor.Tensor, error)
- func (e *Exec) DistributedExec(args ...any) ([]*dtensor.Tensor, error)deprecated
- func (e *Exec) DistributionStrategy() distributed.Strategy
- func (e *Exec) Exec(args ...any) ([]*tensors.Tensor, error)deprecated
- func (e *Exec) Exec1(args ...any) (*tensors.Tensor, error)deprecated
- func (e *Exec) Exec2(args ...any) (*tensors.Tensor, *tensors.Tensor, error)deprecated
- func (e *Exec) Exec3(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, error)deprecated
- func (e *Exec) Exec4(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, *tensors.Tensor, error)deprecated
- func (e *Exec) ExecOnDevice(defaultDevice compute.DeviceNum, args ...any) ([]*tensors.Tensor, error)deprecated
- func (e *Exec) ExecWithGraph(args ...any) ([]*tensors.Tensor, *Graph, error)deprecated
- func (e *Exec) ExecWithGraphOnDevice(defaultDevice compute.DeviceNum, args ...any) ([]*tensors.Tensor, *Graph, error)deprecated
- func (e *Exec) Finalize()
- func (e *Exec) GetNodeLogger() LoggerFn
- func (e *Exec) Meshes() []*distributed.DeviceMesh
- func (e *Exec) MustCall(args ...any) []*tensors.Tensor
- func (e *Exec) MustCall1(args ...any) *tensors.Tensor
- func (e *Exec) MustCall2(args ...any) (*tensors.Tensor, *tensors.Tensor)
- func (e *Exec) MustCall3(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor)
- func (e *Exec) MustCall4(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, *tensors.Tensor)
- func (e *Exec) MustCallWithGraph(args ...any) ([]*tensors.Tensor, *Graph)
- func (e *Exec) MustExec(args ...any) []*tensors.Tensordeprecated
- func (e *Exec) MustExec1(args ...any) *tensors.Tensordeprecated
- func (e *Exec) MustExec2(args ...any) (*tensors.Tensor, *tensors.Tensor)deprecated
- func (e *Exec) MustExec3(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor)deprecated
- func (e *Exec) MustExec4(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, *tensors.Tensor)deprecated
- func (e *Exec) MustExecWithGraph(args ...any) ([]*tensors.Tensor, *Graph)deprecated
- func (e *Exec) Name() string
- func (e *Exec) NumDevices() int
- func (e *Exec) SPMD(mesh *distributed.DeviceMesh) *Exec
- func (e *Exec) SetMaxCache(maxCacheSize int) *Exec
- func (e *Exec) SetNodeLogger(loggerFn LoggerFn)
- func (e *Exec) SetSideParamsHook(fn SideParamsFn) *Exec
- func (e *Exec) WithDeviceAssignment(devices []compute.DeviceNum) *Exec
- func (e *Exec) WithDynamicAxes(axisNames ...[]string) *Exec
- func (e *Exec) WithInputShardingSpecs(specs ...*distributed.ShardingSpec) *Exec
- func (e *Exec) WithName(name string) *Exec
- func (e *Exec) WithOutputShardingSpecs(specs ...*distributed.ShardingSpec) *Exec
- type ExecGraphFn
- type ExecGraphFnOneOutput
- type ExecGraphFnSliceOutputs
- type ExecGraphFnThreeOutputs
- type ExecGraphFnTwoOutputs
- type ExecOneOutput
- type ExecThreeOutputs
- type ExecTwoOutputs
- type Function
- func NewClosure(g *Graph, funcDef func(g *Graph) []*Node) *Function
- func NewClosureWithSharding(g *Graph, funcDef func(g *Graph) ([]*Node, []*distributed.ShardingSpec)) *Function
- func NewFunction(g *Graph, name string, funcDef func(g *Graph) []*Node) *Function
- func NewFunctionWithSharding(g *Graph, name string, ...) *Function
- func (f *Function) Call(inputs ...*Node) []*Node
- func (f *Function) IsAncestorOf(leafFunc *Function) bool
- func (f *Function) IsClosure() bool
- func (f *Function) IsMain() bool
- func (f *Function) Name() string
- func (f *Function) Parent() *Function
- func (f *Function) Path() string
- func (f *Function) Return(outputs []*Node, outputShardings []*distributed.ShardingSpec)
- type Graph
- func (g *Graph) AssertBuilding()
- func (g *Graph) AssertCompiled()
- func (g *Graph) AssertConfiguring()
- func (g *Graph) AssertNotReturned()
- func (g *Graph) AssertValid()
- func (g *Graph) AttachState(key any, value any)
- func (g *Graph) Backend() compute.Backend
- func (g *Graph) CheckValid() error
- func (g *Graph) Compile(outputs ...*Node) error
- func (g *Graph) CompileWithSharding(outputs []*Node, outputShardings []*distributed.ShardingSpec) error
- func (g *Graph) CurrentFunc() *Function
- func (g *Graph) DeviceMeshes() []*distributed.DeviceMesh
- func (g *Graph) Distributed() *DistributedOps
- func (g *Graph) DistributedStrategy() distributed.Strategy
- func (g *Graph) DynamicDimDType() dtypes.DType
- func (g *Graph) Executable() compute.Executable
- func (g *Graph) Finalize()
- func (g *Graph) GetNodeByAlias(alias string) *Node
- func (g *Graph) GetParameterByHandle(handle ParameterHandle) *Node
- func (g *Graph) GetParameterByName(name string) (node *Node)
- func (g *Graph) Graph() *Graph
- func (g *Graph) GraphId() GraphId
- func (g *Graph) IsBuilding() bool
- func (g *Graph) IsCompiled() bool
- func (g *Graph) IsMainFunc() bool
- func (g *Graph) IsValid() bool
- func (g *Graph) IterAliasedNodes() iter.Seq2[string, *Node]
- func (g *Graph) LastNode() *Node
- func (g *Graph) LoggedNodes() (nodes []*Node)
- func (g *Graph) Name() string
- func (g *Graph) NodeById(id NodeId) *Node
- func (g *Graph) Nodes() []*Node
- func (g *Graph) NumDevices() int
- func (g *Graph) NumParameters() int
- func (g *Graph) PopAliasScope()
- func (g *Graph) PushAliasScope(scope string)
- func (g *Graph) Run(inputs ...any) (outputs []*tensors.Tensor)
- func (g *Graph) RunOnDevice(defaultDeviceNum compute.DeviceNum, inputs ...any) (outputs []*tensors.Tensor)
- func (g *Graph) RunWithBuffers(inputs []compute.Buffer, donate []bool, defaultDevice compute.DeviceNum) (outputs []*tensors.Tensor)
- func (g *Graph) RunWithMap(inputs ParamsMap) (outputs []*tensors.Tensor)deprecated
- func (g *Graph) SetAutoSharding(meshes ...*distributed.DeviceMesh) error
- func (g *Graph) SetDeviceAssignment(devices []compute.DeviceNum) error
- func (g *Graph) SetSPMD(mesh *distributed.DeviceMesh) error
- func (g *Graph) SetTraced(traced bool)
- func (g *Graph) State(key any) any
- func (g *Graph) String() string
- func (g *Graph) UniqueName(base string) string
- func (g *Graph) WithName(name string) *Graph
- type GraphId
- type GraphProvider
- type InterpolationConfig
- func (c *InterpolationConfig) AlignCorner(alignCorner bool) *InterpolationConfig
- func (c *InterpolationConfig) Bilinear() *InterpolationConfig
- func (c *InterpolationConfig) Done() (output *Node)
- func (c *InterpolationConfig) HalfPixelCenters(halfPixelCenters bool) *InterpolationConfig
- func (c *InterpolationConfig) Nearest() *InterpolationConfig
- type LoggerFn
- type Node
- func Abs(x *Node) (node *Node)
- func Acosh(x *Node) *Node
- func Add(lhs *Node, rhs *Node) (node *Node)
- func AddScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
- func And(lhs, rhs *Node) *Node
- func ArgMax(x *Node, axis int, outputDType ...dtypes.DType) (output *Node)
- func ArgMin(x *Node, axis int, outputDType ...dtypes.DType) (output *Node)
- func Asinh(x *Node) *Node
- func Atan2(lhs *Node, rhs *Node) (node *Node)
- func Atanh(x *Node) *Node
- func BackendFusedActivation(x *Node, cfg compute.ActivationConfig) *Node
- func BackendFusedActivationVJP(y, x, dOutput *Node, cfg compute.ActivationConfig) *Node
- func BackendFusedAttentionQKVProjection(x, wQKV, biasQ, biasK, biasV *Node, queryDim, keyValueDim int) (query, key, value *Node)
- func BackendFusedDense(x, weight, bias *Node, options compute.DenseConfig) *Node
- func BackendFusedDenseVJP(x, weight, bias, y, dOutput *Node, options compute.DenseConfig) (dx, dWeight, dBias *Node)
- func BackendFusedLayerNorm(x *Node, axes []int, epsilon float64, gamma, beta *Node) *Node
- func BackendFusedQuantizedDense(x, weights, bias *Node, wq *Quantization, activation compute.ActivationType) *Node
- func BackendFusedSoftmax(x *Node, axis int) *Node
- func BackendGather(operand *Node, startIndices *Node, indexVectorAxis int, offsetAxes []int, ...) (node *Node)
- func BackendQuantizedEmbeddingLookup(data, indices *Node, tq *Quantization) *Node
- func BackendReduceWindow(x *Node, reductionType ReduceOpType, ...) *Node
- func BackendScatterMax(operand, indices, updates *Node, indexVectorAxis int, ...) *Node
- func BackendScatterMin(operand, indices, updates *Node, indexVectorAxis int, ...) *Node
- func BackendScatterSum(operand, indices, updates *Node, indexVectorAxis int, ...) *Node
- func BitCount(operand *Node) (node *Node)
- func Bitcast(operand *Node, targetDType dtypes.DType) (node *Node)
- func BitwiseAnd(lhs *Node, rhs *Node) (node *Node)
- func BitwiseNot(x *Node) (node *Node)
- func BitwiseOr(lhs *Node, rhs *Node) (node *Node)
- func BitwiseShiftLeft(x, n *Node) *Node
- func BitwiseShiftLeftScalar[T gotype.NumericNotComplex](x *Node, n T) *Node
- func BitwiseShiftRightArithmetic(x, n *Node) *Node
- func BitwiseShiftRightArithmeticScalar[T gotype.NumericNotComplex](x *Node, n T) *Node
- func BitwiseShiftRightLogical(x, n *Node) *Node
- func BitwiseShiftRightLogicalScalar[T gotype.NumericNotComplex](x *Node, n T) *Node
- func BitwiseXor(lhs *Node, rhs *Node) (node *Node)
- func BottomK(x *Node, k int, axis int) (values, indices *Node)
- func BroadcastLike(operand, reference *Node, broadcastAxes ...int) *Node
- func BroadcastPrefix(x *Node, prefixDims ...int) *Node
- func BroadcastToDims(x *Node, dimensions ...int) *Node
- func BroadcastToShape(x *Node, shape shapes.Shape) *Node
- func Ceil(x *Node) *Node
- func Clamp(min *Node, x *Node, max *Node) (node *Node)
- func Clip(x, min, max *Node) *Node
- func ClipScalar(x *Node, min, max float64) *Node
- func Clz(x *Node) (node *Node)
- func Complex(lhs *Node, rhs *Node) (node *Node)
- func Concatenate(operands []*Node, axis int) *Node
- func Conj(x *Node) (node *Node)
- func ConsecutiveDifference(x *Node, axis int, preserveShape bool) *Node
- func Const(g *Graph, x any) *Node
- func ConstAs(base *Node, x any) *Node
- func ConstAsDType(g *Graph, dtype dtypes.DType, x any) *Node
- func ConstCachedTensor(g *Graph, t *tensors.Tensor) *Node
- func ConstTensor(g *Graph, t *tensors.Tensor) (node *Node)
- func ConvGeneral(input, kernel *Node, axes ConvolveAxesConfig, strides []int, paddings [][2]int, ...) *Node
- func ConvertDType(x *Node, dtype dtypes.DType) (node *Node)
- func ConvertType(x *Node, dtype dtypes.DType) *Node
- func Cos(x *Node) (node *Node)
- func Cosh(x *Node) *Node
- func CosineSimilarity(lhs *Node, rhs *Node, axis int) *Node
- func CrossCosineSimilarity(lhs *Node, rhs *Node, constractingAxis, crossAxis int) *Node
- func CumSum(x *Node, axis int, options ...*CumSumOptions) *Node
- func Diagonal(g *Graph, dim int) *Node
- func DiagonalWithValue(scalar *Node, dim int) *Node
- func DimensionSize(x *Node, axis int) *Node
- func Div(lhs *Node, rhs *Node) (node *Node)
- func DivScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
- func DotGeneral(lhs *Node, lhsContractingAxes, lhsBatchAxes []int, rhs *Node, ...) *Node
- func DotProduct(lhs, rhs *Node) *Node
- func DynamicBroadcastInDim(operand *Node, broadcastAxes []int, axisSpecs ...DimensionSpec) *Node
- func DynamicBroadcastLike(operand, reference *Node, broadcastAxes ...int) *Node
- func DynamicBroadcastToDims(operand *Node, axisSpecs ...DimensionSpec) *Node
- func DynamicBroadcastToShape(x *Node, shape shapes.Shape) *Node
- func DynamicIota(g *Graph, dtype dtypes.DType, iotaAxis int, axisSpecs ...DimensionSpec) *Node
- func DynamicPad(x, fillValue *Node, axesConfig ...DynamicPadAxisSpec) *Node
- func DynamicReshape(operand *Node, axisSpecs ...DimensionSpec) *Node
- func DynamicReshapeLike(operand, reference *Node) *Node
- func DynamicShape(operand *Node) (node *Node)
- func DynamicSlice(operand *Node, startIndices []*Node, sliceDims []int) (node *Node)
- func DynamicUpdateSlice(operand *Node, update *Node, startIndices []*Node) (node *Node)
- func Einsum(equation string, lhs, rhs *Node) *Node
- func EinsumAxes(lhs, rhs *Node, contractingAxes, batchAxes [][2]int) (output *Node)
- func Equal(lhs *Node, rhs *Node) (node *Node)
- func EqualTotalOrder(lhs *Node, rhs *Node) (node *Node)
- func Erf(x *Node) (node *Node)
- func Exp(x *Node) (node *Node)
- func ExpandAndBroadcast(x *Node, newDimensions []int, expandedAxes []int) (output *Node)
- func ExpandAxes(x *Node, newAxes ...int) *Node
- func ExpandDims(x *Node, beforeAxes ...int) *Nodedeprecated
- func ExpandLeftToRank(x *Node, newRank int) (output *Node)
- func Expm1(x *Node) (node *Node)
- func FFT(operand *Node, fftLengths ...int) *Node
- func FillScalar(g *Graph, shape shapes.Shape, value float64) *Node
- func Floor(x *Node) *Node
- func Gather(params, indices *Node, indicesAreSorted ...bool) *Node
- func GatherSlices(input *Node, slicedAxes []int, start *Node, sizes []int, indicesAreSorted bool) (gathered *Node)
- func Gradient(output *Node, gradientNodes ...*Node) []*Node
- func GreaterOrEqual(lhs *Node, rhs *Node) (node *Node)
- func GreaterOrEqualTotalOrder(lhs *Node, rhs *Node) (node *Node)
- func GreaterThan(lhs *Node, rhs *Node) (node *Node)
- func GreaterThanTotalOrder(lhs *Node, rhs *Node) (node *Node)
- func GrowLeft(x *Node, axis int, n int, fillValue float64) *Node
- func GrowRight(x *Node, axis int, n int, fillValue float64) *Node
- func Identity(x *Node) (node *Node)
- func IdentityWithCustomGradient(x *Node, gradientFn func(x, v *Node) *Node) *Node
- func If(pred *Node, trueBranch, falseBranch *Function) []*Node
- func Imag(x *Node) (node *Node)
- func IndicesForShape(g *Graph, shape shapes.Shape) *Node
- func Infinity(g *Graph, dtype dtypes.DType, sign int) *Node
- func InsertAxes(x *Node, beforeAxes ...int) *Node
- func InternalBatchNormForInference(operand *Node, scale *Node, offset *Node, mean *Node, variance *Node, ...) (node *Node)
- func InternalBatchNormForTraining(operand *Node, scale *Node, offset *Node, epsilon float32, axis int) (normalized, batchMean, batchVariance *Node)
- func InternalBatchNormGradient(operand *Node, scale *Node, mean *Node, variance *Node, gradOutput *Node, ...) (gradOperand, gradScale, gradOffset *Node)
- func InternalFusedOpCaller(fused, decomposed func() *Node, useDecomposedAlternateVJP bool) (output *Node, opFused bool)
- func InternalFusedOpCallerMulti(fused, decomposed func() []*Node, useDecomposedAlternateVJP bool) (outputs []*Node, opFused bool)
- func Inverse(x *Node) *Nodedeprecated
- func InverseFFT(operand *Node, fftLengths ...int) *Node
- func InverseRealFFT(operand *Node, fftLengths ...int) *Node
- func Iota(g *Graph, shape shapes.Shape, iotaAxis int) *Node
- func IotaFull(g *Graph, shape shapes.Shape) *Node
- func IotaLike(reference *Node, iotaAxis int) *Node
- func IsFinite(x *Node) (node *Node)
- func IsNaN(x *Node) (node *Node)
- func IsNegative(x *Node) *Node
- func IsNonNegative(x *Node) *Node
- func IsNonPositive(x *Node) *Node
- func IsPositive(x *Node) *Node
- func IsZero(x *Node) *Node
- func L1Norm(x *Node, reduceAxes ...int) *Node
- func L2Norm(x *Node, reduceAxes ...int) *Node
- func L2NormSquare(x *Node, reduceAxes ...int) *Node
- func L2Normalize(x *Node, reduceAxis int, moreReduceAxes ...int) *Node
- func L2NormalizeWithEpsilon(x *Node, epsilon float64, reduceAxis int, moreReduceAxes ...int) *Node
- func LessOrEqual(lhs *Node, rhs *Node) (node *Node)
- func LessOrEqualTotalOrder(lhs *Node, rhs *Node) (node *Node)
- func LessThan(lhs *Node, rhs *Node) (node *Node)
- func LessThanTotalOrder(lhs *Node, rhs *Node) (node *Node)
- func Log(x *Node) (node *Node)
- func Log1P(x *Node) *Node
- func Log1p(x *Node) (node *Node)
- func LogAddExp(x, y *Node) *Node
- func LogSoftmax(logits *Node, axes ...int) *Node
- func LogicalAll(x *Node, reduceAxes ...int) *Node
- func LogicalAnd(lhs *Node, rhs *Node) (node *Node)
- func LogicalAny(x *Node, reduceAxes ...int) *Node
- func LogicalNot(x *Node) (node *Node)
- func LogicalOr(lhs *Node, rhs *Node) (node *Node)
- func LogicalXor(lhs *Node, rhs *Node) (node *Node)
- func Logistic(x *Node) (node *Node)
- func LowerTriangular(g *Graph, dim int) *Node
- func MaskedLogSoftmax(logits, mask *Node, axes ...int) *Node
- func MaskedReduceAllMax(x, mask *Node) *Node
- func MaskedReduceAllMean(x, mask *Node) *Node
- func MaskedReduceAllMin(x, mask *Node) *Node
- func MaskedReduceAllSum(x, mask *Node) *Node
- func MaskedReduceAndKeep(operand, mask *Node, ...) *Node
- func MaskedReduceMax(x, mask *Node, reduceAxes ...int) *Node
- func MaskedReduceMean(x, mask *Node, reduceAxes ...int) *Node
- func MaskedReduceMin(x, mask *Node, reduceAxes ...int) *Node
- func MaskedReduceSum(x, mask *Node, reduceAxes ...int) *Node
- func MaskedSoftmax(logits, mask *Node, axes ...int) *Node
- func MatMul(lhs, rhs *Node) *Node
- func Max(lhs *Node, rhs *Node) (node *Node)
- func MaxScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
- func Min(lhs *Node, rhs *Node) (node *Node)
- func MinScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
- func MinusOne(x *Node) *Node
- func MirroredLog1p(x *Node) *Node
- func Mod(x, y *Node) *Node
- func ModScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
- func Mul(lhs *Node, rhs *Node) (node *Node)
- func MulScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
- func Neg(x *Node) (node *Node)
- func NegativeIndicator(x *Node) *Node
- func NonNegativeIndicator(x *Node) *Node
- func NonPositiveIndicator(x *Node) *Node
- func NormalizeIndices(data, indices *Node, axis int) *Node
- func Not(x *Node) *Node
- func NotEqual(lhs *Node, rhs *Node) (node *Node)
- func NotEqualTotalOrder(lhs *Node, rhs *Node) (node *Node)
- func OneHot(indices *Node, depth int, dtype dtypes.DType) *Node
- func OneMinus(x *Node) *Node
- func OnePlus(x *Node) *Node
- func Ones(g *Graph, shape shapes.Shape) *Node
- func OnesLike(x *Node) *Node
- func OptimizationBarrier(operand *Node) *Node
- func OptimizationBarriers(operands ...*Node) []*Node
- func Or(lhs, rhs *Node) *Node
- func Pad(x *Node, fillValue *Node, axesConfig ...compute.PadAxis) (node *Node)
- func Parameter(g *Graph, name string, shape shapes.Shape) (node *Node)
- func PositiveIndicator(x *Node) *Node
- func Pow(lhs *Node, rhs *Node) (node *Node)
- func PowScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
- func RNGStateForGraph(g *Graph) *Node
- func RNGStateFromSeedForGraph(g *Graph, seed int64) *Node
- func RNGStateSplit(rngState *Node) (newRNGState1, newRNGState2 *Node)
- func RandomIntN[IntT interface{ ... }](rngState *Node, N IntT, shape shapes.Shape) (newRNGState, values *Node)
- func RandomNormal(rngState *Node, shape shapes.Shape) (newRNGState, values *Node)
- func RandomUniform(rngState *Node, shape shapes.Shape) (newRNGState, values *Node)
- func Real(x *Node) (node *Node)
- func RealFFT(operand *Node, fftLengths ...int) *Node
- func Reciprocal(x *Node) *Node
- func ReduceAllMax(x *Node) *Node
- func ReduceAllMean(x *Node) *Node
- func ReduceAllMin(x *Node) *Node
- func ReduceAllMultiply(x *Node) *Node
- func ReduceAllSum(x *Node) *Node
- func ReduceAndKeep(operand *Node, reduceFn func(operand *Node, reduceAxes ...int) *Node, ...) *Node
- func ReduceBitwiseAnd(x *Node, reduceAxes ...int) *Node
- func ReduceBitwiseOr(x *Node, reduceAxes ...int) *Node
- func ReduceBitwiseXor(x *Node, reduceAxes ...int) *Node
- func ReduceLogicalAnd(x *Node, reduceAxes ...int) *Node
- func ReduceLogicalOr(x *Node, reduceAxes ...int) *Node
- func ReduceLogicalXor(x *Node, reduceAxes ...int) *Node
- func ReduceMax(x *Node, reduceAxes ...int) *Node
- func ReduceMean(x *Node, reduceAxes ...int) *Node
- func ReduceMin(x *Node, reduceAxes ...int) *Node
- func ReduceMultiply(x *Node, reduceAxes ...int) *Node
- func ReduceSkewness(x *Node, axes ...int) *Node
- func ReduceSum(x *Node, reduceAxes ...int) *Node
- func ReduceVariance(x *Node, axes ...int) *Node
- func Rem(lhs *Node, rhs *Node) (node *Node)
- func Reshape(x *Node, dimensions ...int) *Node
- func ReshapeLike(operand, reference *Node) *Node
- func ReshapeWithShape(x *Node, shape shapes.Shape) *Node
- func Reverse(x *Node, axes ...int) *Node
- func Round(x *Node) (node *Node)
- func Rsqrt(x *Node) (node *Node)
- func Scalar[N gotype.NumericNotComplex](g *Graph, dtype dtypes.DType, value N) *Node
- func ScalarOne(g *Graph, dtype dtypes.DType) *Node
- func ScalarZero(g *Graph, dtype dtypes.DType) *Node
- func Scatter(indices, updates *Node, shape shapes.Shape, sorted, unique bool) *Node
- func ScatterAdd(operand, indices, updates *Node, sorted, unique bool) *Nodedeprecated
- func ScatterMax(operand, indices, updates *Node, sorted, unique bool) *Node
- func ScatterMin(operand, indices, updates *Node, sorted, unique bool) *Node
- func ScatterSum(operand, indices, updates *Node, sorted, unique bool) *Node
- func ScatterUpdate(operand, indices, updates *Node, sorted, unique bool) *Node
- func SchedulingBarrier(operand *Node, dependencies ...*Node) (node *Node)
- func ShapedLowerTriangular(g *Graph, rows, column, k int) *Node
- func ShardedParameter(g *Graph, name string, shape shapes.Shape, sharding *distributed.ShardingSpec) (node *Node)
- func Shift(x *Node, axis int, shiftDir ShiftDirection, n int) *Node
- func ShiftLeft(x *Node, n int, fill float64) *Node
- func ShiftRight(x *Node, n int, fill float64) *Node
- func ShiftWithScalar(x *Node, axis int, shiftDir ShiftDirection, n int, fill float64) *Node
- func ShiftWithValue(x *Node, axis int, shiftDir ShiftDirection, n int, value *Node) *Node
- func Sigmoid(x *Node) *Node
- func Sign(x *Node) *Node
- func SignPlusOrMinus(x *Node) *Node
- func Sin(x *Node) (node *Node)
- func Sinh(x *Node) *Node
- func Skewness(x *Node, axes ...int) *Node
- func Slice(x *Node, axesSpec ...SliceAxisSpec) *Node
- func SliceAxis(x *Node, axis int, axisSpec SliceAxisSpec) *Node
- func Softmax(logits *Node, axes ...int) *Node
- func Softplus(x *Node) *Node
- func Sort(input *Node, axis int, ascending bool) *Node
- func SortFunc(comparator *Function, axis int, isStable bool, inputs ...*Node) []*Node
- func Split(x *Node, axis int, numSplits int) []*Node
- func Sqrt(x *Node) (node *Node)
- func Square(x *Node) *Node
- func Squeeze(x *Node, axes ...int) *Node
- func Stack(operands []*Node, axis int) *Node
- func StopGradient(x *Node) *Node
- func Sub(lhs *Node, rhs *Node) (node *Node)
- func SubScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
- func TakeLowerTriangular(x *Node, k int) *Node
- func TakeUpperTriangular(x *Node, k int) *Node
- func Tanh(x *Node) (node *Node)
- func TopK(x *Node, k int, axis int) (values, indices *Node)
- func TopKMask(x *Node, k int, axis int) *Node
- func Transpose(x *Node, axisA, axisB int) *Node
- func TransposeAllAxes(x *Node, permutations ...int) *Node
- func TransposeAllDims(x *Node, permutations ...int) *Nodedeprecated
- func UpperTriangular(g *Graph, dim int) *Node
- func Variance(x *Node, axes ...int) *Node
- func Where(condition, onTrue, onFalse *Node) *Node
- func While(cond, body *Function, initialState ...*Node) []*Node
- func Zeros(g *Graph, shape shapes.Shape) *Node
- func ZerosLike(x *Node) *Node
- func (n *Node) AssertDims(dimensions ...int)
- func (n *Node) AssertRank(rank int)
- func (n *Node) AssertScalar()
- func (n *Node) AssertValid()
- func (n *Node) Checkpoint() *Node
- func (n *Node) CloneWithInputs(newInputs ...*Node) *Node
- func (n *Node) ConstantValue() *tensors.Tensor
- func (n *Node) CustomGradient() VJP
- func (n *Node) DType() dtypes.DType
- func (n *Node) Function() *Function
- func (n *Node) GetAlias() string
- func (n *Node) GetParameterHandle() ParameterHandle
- func (n *Node) GetParameterName() string
- func (n *Node) Graph() *Graph
- func (n *Node) Id() NodeId
- func (n *Node) Inputs() []*Node
- func (n *Node) IsConstantExpression() bool
- func (n *Node) IsLogged() bool
- func (n *Node) IsScalar() bool
- func (n *Node) LogMessage() string
- func (n *Node) NumOutputs() int
- func (n *Node) Rank() int
- func (n *Node) SetLogged(message string)
- func (n *Node) SetLoggedf(format string, args ...any)
- func (n *Node) Shape() shapes.Shape
- func (n *Node) StopCheckpoint() *Node
- func (n *Node) StopGradient() bool
- func (n *Node) String() (str string)
- func (n *Node) Trace() error
- func (n *Node) Type() NodeType
- func (n *Node) WithAlias(alias string) *Node
- type NodeId
- type NodeInputs
- type NodeType
- func (i NodeType) IsANodeType() bool
- func (i NodeType) MarshalJSON() ([]byte, error)
- func (i NodeType) MarshalText() ([]byte, error)
- func (i NodeType) MarshalYAML() (interface{}, error)
- func (i NodeType) String() string
- func (i *NodeType) UnmarshalJSON(data []byte) error
- func (i *NodeType) UnmarshalText(text []byte) error
- func (i *NodeType) UnmarshalYAML(unmarshal func(interface{}) error) error
- func (NodeType) Values() []string
- type NodeXlaHandle
- type PadAxis
- type ParameterHandle
- type ParamsMap
- type PoolBuilder
- func (pool *PoolBuilder) ChannelsAxis(channelsAxisConfig images.ChannelsAxisConfig) *PoolBuilder
- func (pool *PoolBuilder) Done() *Node
- func (pool *PoolBuilder) FullShape() *PoolBuilder
- func (pool *PoolBuilder) NoPadding() *PoolBuilder
- func (pool *PoolBuilder) PadSame() *PoolBuilder
- func (pool *PoolBuilder) PaddingPerDim(paddings [][2]int) *PoolBuilder
- func (pool *PoolBuilder) StridePerAxis(strides ...int) *PoolBuilder
- func (pool *PoolBuilder) Strides(strides int) *PoolBuilder
- func (pool *PoolBuilder) Window(windowSize int) *PoolBuilder
- func (pool *PoolBuilder) WindowPerAxis(sizes ...int) *PoolBuilder
- type Quantization
- type Ragged2D
- type ReduceOpType
- type ReshapeDimensionSpecdeprecated
- type ShiftDirection
- type SideParamsFn
- type SingleOutputVJP
- type SliceAxisSpec
- type VJP
Constants ¶
const AliasScopeSeparator = "/"
AliasScopeSeparator is the string used to join the individual alias scope parts as well as the alias itself. So if the scope is currently ["a", "b"] and an alias "output" is created, it will be renamed "/a/b/output".
const DefaultExecMaxCacheSize = 32
DefaultExecMaxCacheSize is the value used to initialize the max cache size of new Exec objects.
const FusionEnv = "GOMLX_FUSION"
FusionEnv is the name of the environment variable that controls whether fused ops are used. The default value is true.
const InvalidNodeId = NodeId(-1)
InvalidNodeId indicates a node that failed to be created.
const InvalidParameterHandle = ParameterHandle(-1)
InvalidParameterHandle represents an invalid (or non-existent) parameter.
const MainName = compute.MainName
MainName is the name of the main function -- the default function created when the Graph is created.
const (
MaxSizeToPrint = 5
)
const NoInterpolation = int(-1)
NoInterpolation can be used for the outputSizes of the Interpolation call.
Variables ¶
var ConvGeneralDilated = ConvGeneral
ConvGeneralDilated is a deprecated an alias to ConvGeneral.
Deprecated: use ConvGeneral instead.
var ErrExecFinalized = errors.New("exec is finalized")
Exec creates and executes computation graphs as needed based on the inputs shapes.
It simplifies the process of executing a graph building function with real values. For example, assume you wrote:
func L2Norm(x *Node) *Node {
return Sqrt(ReduceAllSum(Mul(x, x)))
}
To use it with actual values (tensors.Tensor's), one needs to build the computation graph for the specific shape of x, and then execute it.
While this is straight forward, it's lots of boilerplate code -- JIT compilation makes things faster, but it imposes some bureaucracy.
With Exec one can do:
var l2NormExec = MustNewExec(compute.New(), L2Norm)
x0 := []float32{2}
fmt.Printf("L2Norm(%v) = %s\n", x0, l2NormExec.MustExec1(x0)) // -> 2
x1 := []float64{4, 3}
fmt.Printf("L2Norm(%v) = %s\n", x1, l2NormExec.MustExec1(x1)) // -> 5
Notice that both calls to l2NormExec.MustExec1 will need to create different graphs (because they have different input shapes). These JIT-compiled computation graphs are cached, and if the same shapes are used in MustExec1 again, the cached version is reused.
For "ergonomics", we provide variations of the same API, depending on if you want errors to be returned, or simply panic, and on how many outputs you expect:
- Use NewExec or MustNewExec to create new executors.
- Exec returns a slice of outputs and errors. Exec1 to Exec4 return 1 to 4 outputs exactly, plus an error.
- MustExec returns a slice of outputs and panics on error. MustExec1 to MustExec4 1 to 4 outputs exactly, and panics on error.
- ExecOnce and MustExecOnce merge NewExec (or MustNewExec), Exec1 (or MustExec1) and then Finalize methods in one convenient call, for when executing the graph only once. There are also ExecOnceN and MustExecOnceN variations that return a slice of outputs.
If there are no inputs for the graph function (for instance, for some initialization function), then one needs to take a *Graph as the first parameter of the graph function (graphFn).
Inside graph building functions, one is expected to panic with an error. The executor captures (recovers) from panics and returns the error.
Example using `ExecOnce`, which compiles the graph and immediately runs it.
iotaMatrix, err := ExecOnce(backend, func (g *Graph) *Node {
return IotaFull(g, shapes.Make(dtype.Float32, 3, 3))
})
if err != nil { ... }
fmt.Printf("IotaFull(3x3 matrix, float32)=%v\n", iotaMatrix) // -> [[0 1 2] [3 4 5] [6 7 8]]
Example using `ExecOnceN`, which returning 2 values:
iotaMatrices, err := ExecOnceN(backend, func (g *Graph) []*Node {
return []*Node{
IotaFull(g, shapes.Make(dtype.Float32, 2, 2)),
IotaFull(g, shapes.Make(dtype.Float32, 3, 3))}
})
Considerations of inputs of different shapes: ¶
The need to build different graphs for different shapes can be expensive when the inputs' shapes vary a lot. The usual solution is to use shapes with dimensions in a power scale (for instance, powers of 2) and use padding and masking of tensors for unused slices of the input.
For safety concerns, there are a maximum number of different instantiations of the graph. It can be set or disabled with SetMaxCache.
Logging: ¶
The executor can log nodes marked for logging during execution, which is very handy for debugging, plotting, etc. One marks a computation (any Node) for logging with Node.SetLogged (or Node.SetLoggedf). And one can have specialized loggers by setting use Exec.SetNodeLogger: they can be set in cascading fashion, so there can be different logger types (printing, plotting, NaN detection, etc.) being used simultaneously.
Distributed execution: ¶
- User controlled (the default): the user can choose the device to use for execution with WithDevice. Only one device is used (see Exec.WithDevice), but the user can create multiple executors for different devices and execute code in parallel. No communication (distributed operations) available among the executors.
- SPMD (Single Program Multiple Data): automatically replicates the computation across devices, see Exec.SPMD. The devices are organized in an arbitrary mesh. Usually, it's a 1D list of devices, but they can be organized in multiple axes. One uses Graph.Distributed() for the synchronization operations (like AllReduce, AllGather, etc.), which need to be organized by the user.
Concurrency ¶
Exec compiles graphs for different input shapes concurrently. The provided graphFn must be safe for concurrent invocation — each call receives its own Graph and Node arguments, but graphFn must not mutate external shared state without its own synchronization.
Lifecycle and Finalization ¶
When an Exec is no longer needed, call Exec.Finalize to immediately release backend and device resources. Exec.Finalize coordinates with active operations: it waits for any in-flight Call or Compile operations to finish before freeing cached graphs, while causing any new operations initiated after finalization starts to return ErrExecFinalized immediately.
ErrExecFinalized is returned when an operation (such as Call or Compile) is attempted on an Exec instance that has been finalized.
var MinConstValueSizeToKeep = 32
MinConstValueSizeToKeep defines a size below which constant values (see Const, ConstTensor) are kept in the Node/Graph for printing/debugging purposes
If set to 0, no value is kept.
var ( // RNGStateShape is the default shape for random number generators state, used // in all Random* functions. // It dependents on the algorithm, but for now we use the Philox algorithm only. RNGStateShape = compute.RNGStateShape )
var ReduceAndKeepMasked = MaskedReduceAndKeep
ReduceAndKeepMasked is an alias for MaskedReduceAndKeep.
Deprecated: all functions that take mask are prefixed with `Masked...`
var VJPRegistration = map[NodeType]VJP{
NodeTypeInvalid: vjpForSingleOutput(noOpVJP),
NodeTypeConstant: vjpForSingleOutput(nilVJP),
NodeTypeParameter: vjpForSingleOutput(nilVJP),
NodeTypeConvertDType: vjpForSingleOutput(convertDTypeVJP),
NodeTypeWhere: vjpForSingleOutput(whereVJP),
NodeTypeNeg: vjpForSingleOutput(negVJP),
NodeTypeAbs: vjpForSingleOutput(absVJP),
NodeTypeExp: vjpForSingleOutput(expVJP),
NodeTypeExpm1: vjpForSingleOutput(expm1VJP),
NodeTypeLog: vjpForSingleOutput(logVJP),
NodeTypeLog1p: vjpForSingleOutput(log1pVJP),
NodeTypeCos: vjpForSingleOutput(cosVJP),
NodeTypeSin: vjpForSingleOutput(sinVJP),
NodeTypeTanh: vjpForSingleOutput(tanhVJP),
NodeTypeAdd: vjpForSingleOutput(addVJP),
NodeTypeSub: vjpForSingleOutput(subVJP),
NodeTypeMul: vjpForSingleOutput(mulVJP),
NodeTypeDiv: vjpForSingleOutput(divVJP),
NodeTypePow: vjpForSingleOutput(powVJP),
NodeTypeSqrt: vjpForSingleOutput(sqrtVJP),
NodeTypeErf: vjpForSingleOutput(erfVJP),
NodeTypeBatchNormForTraining: batchNormForTrainingVJP,
NodeTypeFusedDense: vjpForSingleOutput(fusedDenseVJP),
NodeTypeFusedActivation: vjpForSingleOutput(fusedActivationVJP),
NodeTypeFusedScaledDotProductAttention: fusedScaledDotProductAttentionVJP,
NodeTypeLogicalAnd: vjpForSingleOutput(zeroVJP),
NodeTypeLogicalOr: vjpForSingleOutput(zeroVJP),
NodeTypeLogicalXor: vjpForSingleOutput(zeroVJP),
NodeTypeLogicalNot: vjpForSingleOutput(zeroVJP),
NodeTypeBitwiseAnd: vjpForSingleOutput(zeroVJP),
NodeTypeBitwiseOr: vjpForSingleOutput(zeroVJP),
NodeTypeBitwiseXor: vjpForSingleOutput(zeroVJP),
NodeTypeBitwiseNot: vjpForSingleOutput(zeroVJP),
NodeTypeReal: vjpForSingleOutput(realVJP),
NodeTypeImag: vjpForSingleOutput(imagVJP),
NodeTypeConj: vjpForSingleOutput(conjVJP),
NodeTypeComplex: vjpForSingleOutput(complexVJP),
NodeTypeMax: vjpForSingleOutput(minMaxVJP),
NodeTypeMin: vjpForSingleOutput(minMaxVJP),
NodeTypeReshape: vjpForSingleOutput(reshapeVJP),
NodeTypeReduceSum: vjpForSingleOutput(reduceSumVJP),
NodeTypeReduceMax: vjpForSingleOutput(reduceMaxVJP),
NodeTypeReduceMin: vjpForSingleOutput(reduceMinVJP),
NodeTypeLogistic: vjpForSingleOutput(logisticVJP),
NodeTypeDotGeneral: vjpForSingleOutput(dotGeneralVJP),
NodeTypeSlice: vjpForSingleOutput(sliceVJP),
NodeTypeGather: vjpForSingleOutput(gatherVJP),
NodeTypeScatterSum: vjpForSingleOutput(scatterSumVJP),
NodeTypeScatterMax: vjpForSingleOutput(scatterMaxOrMinVJP),
NodeTypeScatterMin: vjpForSingleOutput(scatterMaxOrMinVJP),
NodeTypeConcatenate: vjpForSingleOutput(concatenateVJP),
NodeTypeConvGeneral: vjpForSingleOutput(convGeneralVJP),
NodeTypeReduceWindow: vjpForSingleOutput(reduceWindowVJP),
NodeTypeTranspose: vjpForSingleOutput(transposeVJP),
NodeTypeBroadcastInDim: vjpForSingleOutput(broadcastInDimVJP),
NodeTypeDynamicBroadcastInDim: vjpForSingleOutput(dynamicBroadcastInDimVJP),
NodeTypeFFT: vjpForSingleOutput(fftVJP),
NodeTypeDynamicSlice: vjpForSingleOutput(dynamicSliceVJP),
NodeTypeDynamicUpdateSlice: vjpForSingleOutput(dynamicUpdateSliceVJP),
NodeTypeDynamicDimensionSize: vjpForSingleOutput(zeroVJP),
NodeTypeDynamicReshape: vjpForSingleOutput(dynamicReshapeVJP),
NodeTypeDynamicShape: vjpForSingleOutput(zeroVJP),
NodeTypeCumSum: vjpForSingleOutput(cumSumVJP),
NodeTypePad: vjpForSingleOutput(padVJP),
NodeTypeDynamicPad: vjpForSingleOutput(dynamicPadVJP),
NodeTypeIota: vjpForSingleOutput(zeroVJP),
NodeTypeDynamicIota: vjpForSingleOutput(zeroVJP),
NodeTypeReverse: vjpForSingleOutput(reverseVJP),
NodeTypeOptimizationBarrier: vjpOptimizationBarrier,
NodeTypeSchedulingBarrier: vjpForSingleOutput(vjpSchedulingBarrier),
}
VJPRegistration maps each node type to its implementation of VJP. If implementing a new outputOps, or for experimentation, one can dynamically change this.
Notice xla.GetTupleElementNode is specialized inside the main reverse autodiff code, and is not in the table here.
Functions ¶
func BackendFusedScaledDotProductAttention ¶
func BackendFusedScaledDotProductAttention(query, key, value *Node, axesLayout compute.AttentionAxesLayout, options *compute.ScaledDotProductAttentionConfig) (output *Node, statesForVJP []*Node)
BackendFusedScaledDotProductAttention computes multi-head scaled dot-product attention via the backend's fused op. It returns the attention output plus statesForVJP: the backend-specific state tensors the fused backward consumes (the cuDNN flash softmax stats today; a slice so other backends can carry a different set, e.g. an extra workspace tensor). statesForVJP is empty when the backend has no fused backward. The gradient is the registered VJP (fusedScaledDotProductAttentionVJP), which threads statesForVJP into the fused backward so the [B,H,S,S] scores never materialize in either pass. Backends without the fused op panic with a wrapped compute.ErrNotImplemented, so callers fall back.
Internal: prefer to use the package ml/layers/attention instead, which provides the standard (and stable) API for attention layers. This is an internal API that may change without notice.
func CallOnce ¶
func CallOnce[F ExecGraphFnOneOutput](backend compute.Backend, graphFn F, args ...any) (*tensors.Tensor, error)
CallOnce builds the graph and calls it with the given arguments and returns the one output.
It's short for a call to MustNewExec, Exec.Call1 and Exec.Finalize for functions that return only one output.
func CallOnceN ¶
func CallOnceN[F ExecGraphFn](backend compute.Backend, graphFn F, args ...any) ([]*tensors.Tensor, error)
CallOnceN builds the graph and calls it with the given arguments and returns the various outputs.
It's short for a call to MustNewExec, Exec.Call and Exec.Finalize for functions that return only one output.
See ExecOnce for a more convenient version if you have only one output. Also, see MustExecOnceN or MustExecOnce if you want it to panic on error.
func DefaultNodeLogger ¶
DefaultNodeLogger for nodes marked to be logged. It prints the message and the node value for each logged node.
It accepts special prefixes on message name that affects the printing:
- "#full ": prints full tensor value (as opposed to abbreviated).
func DonateTensorBuffer ¶
func DonateTensorBuffer(t *tensors.Tensor, backend compute.Backend, deviceNum compute.DeviceNum) (any, error)
DonateTensorBuffer can be used by Graph.Run, Graph.RunOnDevice, or as input to Exec.Call, and it marks the Tensor to donate its on-device buffer to the execution.
This allows the accelerator (GPU) to reuse the space of the donated buffer, which saves space if the original value is no longer used. In particular, this is very useful when updating some state (variable) in a loop.
If the tensor uses shared buffers (usually CPU backends, see Tensor.IsShared), the tensor will be invalidated after the donation, since there is no separate local copy.
Example:
myBuf, err := myState.DonateBuffer(backend, deviceNum) myState, err := myExec.Call(myBuf)[0]
It requires the backend and the deviceNum (defaults to 0) of the device buffer to donate.
Notice that after this, t's value in the device becomes invalid.
func InternalBackendOutputs ¶
InternalBackendOutputs retrieves the unexported backend outputs of a node.
WARNING: This is an internal GoMLX API. It is exposed specifically for layer packages (like `attention`) that need to access backend details to stitch together fused operations (e.g., FusedScaledDotProductAttention).
End-users building standard computation graphs should never need to call this.
func MustAdjustAxis ¶
MustAdjustAxis returns the positive axis to the operand shapes, adjusting in case the axis given is negative.
It panics if axis given is not in the operand's rank range.
func MustExecOnce ¶
func MustExecOnce[F ExecGraphFnOneOutput](backend compute.Backend, graphFn F, args ...any) *tensors.Tensor
MustExecOnce builds the graph and calls it with the given arguments and returns the one output.
It's short for a call to MustNewExec, Exec.MustExec and Exec.Finalize for functions that return only one output. It panics on error.
See MustExecOnceN if you have multiple outputs. Also, see ExecOnceN or ExecOnce if you want any errors returned.
func MustExecOnceN ¶
func MustExecOnceN[F ExecGraphFn](backend compute.Backend, graphFn F, args ...any) []*tensors.Tensor
MustExecOnceN builds the graph and calls it with the given arguments, and returns various outputs.
It's short for a call to MustNewExec, Exec.MustExec and Exec.Finalize. It panics on error.
See MustExecOnce for a more convenient version if you have only one output. Also, see ExecOnceN or ExecOnce if you want any errors returned.
func NodeTypeStrings ¶
func NodeTypeStrings() []string
NodeTypeStrings returns a slice of all String values of the enum
func RNGState ¶
RNGState creates a random number generator (RNG) state initialized using the OS's cryptographically secure random number generator, if available. If the OS's cryptographically secure random number generator is not available, it will use the current time as seed.
This is not a graph building function: it returns a concrete tensor value, and it returns an error if something fails. The returned value can be used as a Const or to set a variable to be used in a graph.
A typical use case would be to use like:
rngState, err := Const(g, RNGState())
func RNGStateFromSeed ¶
RNGStateFromSeed creates a random number generator (RNG) state based on the static seed.
Notice it returns a concrete tensor value and an error.
If you want it as a constant in the graph, use RNGStateFromSeedForGraph.
Types ¶
type CanonicalExecGraphFn ¶
type ConvolutionBuilder ¶
type ConvolutionBuilder struct {
// contains filtered or unexported fields
}
ConvolutionBuilder is a helper to build a convolution computation. Create it with Convolve, set the desired parameters and when set, call `IsNil()`.
func Convolve ¶
func Convolve(x, kernel *Node) *ConvolutionBuilder
Convolve prepares a convolution on x with the given kernel for an arbitrary number of spatial dimensions (1D, 2D, 3D, etc.).
It returns a ConvolutionBuilder object that can be further configured. Once the configuration is finished, call ConvolutionBuilder.Done, and it will return the convolved x. Browse through ConvolutionBuilder to see its capabilities and defaults.
* Shapes:
The shape of x should be [batch, <spatial_dimensions...>, input_channels] if configured with ConvolutionBuilder.ChannelsAxis(timage.ChannelsLast), the default. If one sets ConvolutionBuilder.ChannelsAxis(timage.ChannelsFirst), then the shape should be [batch, input_channels, <spatial_dimensions...>] instead.
Note: package timage refers to package github.com/gomlx/gomlx/core/tensors/images.
Alternatively, it provides the method ConvolutionBuilder.AxesConfig which allows arbitrary shape (axes order) configuration of x and the kernel.
The shape of the kernel should be [<spatial_dimensions...>, input_channels, output_channels] if configured with ConvolutionBuilder.ChannelsAxis(timage.ChannelsLast), the default. If one sets ConvolutionBuilder.ChannelsAxis(timage.ChannelsFirst), the shape should be [input_channels, output_channels, <spatial_dimensions...>] instead.
Notice x and kernel must have the same rank.
We follow the Keras convention of calling "channels" the axis that is sometimes referred to by "features" or "depth". The "kernel" is also referred to as "filters" by some.
Additional features:
- Group operations: Use ConvolutionBuilder.ChannelGroupCount to split channels or BatchGroupCount to split batches into independent processing groups. When using either feature, the kernel's shape changes.
func (*ConvolutionBuilder) AxesConfig ¶
func (conv *ConvolutionBuilder) AxesConfig(axes ConvolveAxesConfig) *ConvolutionBuilder
AxesConfig specify the exact configuration of the axes on the input (x/input and kernel) and output of the Convolve operation. This is advanced (and may not be supported in every backend), but it's powerful. Consider using `ConvolutionBuilder.ChannelsAxis` instead.
The default is `ChannelsAxis(timage.ChannelsLast)`.
func (*ConvolutionBuilder) BatchGroupCount ¶
func (conv *ConvolutionBuilder) BatchGroupCount(groupCount int) *ConvolutionBuilder
BatchGroupCount splits batches into independent processing groups. Used for cross-batch interactions like ShuffleNet's channel shuffle.
When BatchGroupCount != 1, the kernel's shape changes: the batch dimension of the input is divided by the group count, creating separate convolution groups where each group processes a subset of the batch. The kernel output channels dimensions must be divisible by the batch group count, each slice applies to one batch, and they are concatenated in the end.
The output shape will have the same spatial dimensions as a regular convolution but with the batch dimension divided by groupCount.
Reference: https://www.tensorflow.org/api_docs/python/tf/data/Dataset#batch
func (*ConvolutionBuilder) ChannelGroupCount ¶
func (conv *ConvolutionBuilder) ChannelGroupCount(groupCount int) *ConvolutionBuilder
ChannelGroupCount splits input/output channels into independent groups. Equivalent to TensorFlow's "groups" parameter in tf.nn.convNd operations.
When groupCount != 1, the kernel's shape changes: the input channels dimension of the kernel must equal (input_channels / group_count). This effectively creates separate convolution groups where each group processes a subset of input channels and produces a subset of output channels.
For depthwise convolution, set groups = input_channels (see tf.nn.depthwise_conv2d). The output shape will have the same spatial dimensions as a regular convolution but with channel dimensions affected by the grouping.
Side effects:
- Kernel shape: The kernel's input channel dimension becomes (input_channels / group_count)
- Output shape: The output maintains the same spatial dimensions as regular convolution, but each group independently maps its input channels to output channels
- Performance: Can reduce computation cost by limiting connections between channels
- Memory usage: Reduces the number of parameters in the kernel
Reference: https://www.tensorflow.org/api_docs/python/tf/data/Dataset#group_by_window
func (*ConvolutionBuilder) ChannelsAxis ¶
func (conv *ConvolutionBuilder) ChannelsAxis(channelsAxisConfig timage.ChannelsAxisConfig) *ConvolutionBuilder
ChannelsAxis configures the axis for the channels (aka. "depth" or "features") dimension. The default is `timage.ChannelsLast`, meaning the "channels" dimension comes last.
Note: `timage` refers to the package github.com/gomlx/gomlx/core/tensors/images
For more fine-control, see AxesConfig.
It returns the modified Config object, so calls can be cascaded.
func (*ConvolutionBuilder) DilationPerAxis ¶
func (conv *ConvolutionBuilder) DilationPerAxis(dilations ...int) *ConvolutionBuilder
DilationPerAxis sets the kernel's dilations for each spatial dimension of the convolution.
The default is 1 for every axis. A value > 1 is also called "atrous convolution".
It specifies the kernel's up-sampling rate. In the literature, the same parameter is sometimes called input stride or dilation. The effective kernel size used for the convolution will be `kernel_shape + (kernel_shape - 1) * (dilation - 1)`, obtained by inserting (dilation-1) zeros between consecutive elements of the original kernel in the spatial dimension.
One cannot use strides and dilation at the same time.
func (*ConvolutionBuilder) DilationPerDim
deprecated
func (conv *ConvolutionBuilder) DilationPerDim(dilations ...int) *ConvolutionBuilder
DilationPerDim sets the kernel's dilations for each spatial dimension of the convolution.
Deprecated: Use DilationPerAxis instead.
func (*ConvolutionBuilder) Dilations ¶
func (conv *ConvolutionBuilder) Dilations(dilation int) *ConvolutionBuilder
Dilations sets the dilations of the convolution: the same value is used for every dimension.
The default is 1. A value > 1 is also called "atrous convolution".
It specifies the kernel's up-sampling rate. In the literature, the same parameter is sometimes called input stride or kernel dilation. The effective kernel size used for the convolution will be `kernel_shape + (kernel_shape - 1) * (dilation - 1)`, obtained by inserting (dilation-1) zeros between consecutive elements of the original kernel in the spatial dimension.
One cannot use strides and dilation at the same time.
func (*ConvolutionBuilder) Done ¶
func (conv *ConvolutionBuilder) Done() *Node
Done indicates that the convolve operation is finished being configured, and it updates the computation graph with convolution and returns the resulting Node.
func (*ConvolutionBuilder) FeatureGroupCount
deprecated
func (conv *ConvolutionBuilder) FeatureGroupCount(groupCount int) *ConvolutionBuilder
FeatureGroupCount is an alias for ChannelGroupCount.
Deprecated: Use ChannelGroupCount instead.
func (*ConvolutionBuilder) InputDilationPerAxis ¶
func (conv *ConvolutionBuilder) InputDilationPerAxis(dilations ...int) *ConvolutionBuilder
InputDilationPerAxis virtually inserts zeros between input values, making the input effectively larger.
func (*ConvolutionBuilder) NoPadding ¶
func (conv *ConvolutionBuilder) NoPadding() *ConvolutionBuilder
NoPadding removes any paddings, so if the kernel spatial dimensions > 1, the output shapes will be reduced on the edges. This is the default.
See also PadSame and PaddingPerDim.
func (*ConvolutionBuilder) PadSame ¶
func (conv *ConvolutionBuilder) PadSame() *ConvolutionBuilder
PadSame adds paddings on the edges of x such that in the end the output of the convolution has the same shapes as the input (assuming strides=1).
The default is no padding. See also NoPadding and PaddingPerDim.
func (*ConvolutionBuilder) PaddingPerDim ¶
func (conv *ConvolutionBuilder) PaddingPerDim(paddings [][2]int) *ConvolutionBuilder
PaddingPerDim specifies the paddings at the start and at the end to use per spatial dimension, that means one pair ([2]int) per spatial dimension.
If a nil value for paddings is given, this has no effect.
The default is no padding. See also NoPadding and PadSame.
func (*ConvolutionBuilder) StridePerAxis ¶
func (conv *ConvolutionBuilder) StridePerAxis(strides ...int) *ConvolutionBuilder
StridePerAxis sets the strides for each spatial dimension of the convolution. The default is 1 for every dimension.
The stride is how many steps to move after a convolution. A value of 2 will halve the input size, since a convolution will be done at every other position, and so on. It can be defined separately per dimension.
One cannot use strides and dilation at the same time.
func (*ConvolutionBuilder) StridePerDim
deprecated
func (conv *ConvolutionBuilder) StridePerDim(strides ...int) *ConvolutionBuilder
StridePerDim sets the strides for each spatial dimension of the convolution.
Deprecated: Use StridePerAxis instead.
func (*ConvolutionBuilder) Strides ¶
func (conv *ConvolutionBuilder) Strides(strides int) *ConvolutionBuilder
Strides sets the strides of the convolution. It sets the same value for every dimension. The default is 1.
The stride is how many steps to move after a convolution. A value of 2 will halve the input size, since a convolution will be done at every other position, and so on. It can be defined separately per dimension.
One cannot use strides and dilation at the same time.
type ConvolveAxesConfig ¶
type ConvolveAxesConfig = compute.ConvolveAxesConfig
ConvolveAxesConfig defines the interpretation of the input/kernel/output tensor axes. There must be the same number of spatial dimensions (axes) for each of the 3 tensors. Input and output have batch and channels axes. Filters have "inputChannels" and "outputChannels" axes.
type CumSumOptions ¶ added in v0.28.5
type CumSumOptions = compute.CumSumOptions
CumSumOptions are options for the CumSum operation.
type DimensionSpec ¶ added in v0.28.5
type DimensionSpec struct {
// contains filtered or unexported fields
}
DimensionSpec specifies how the dimension of an axis is defined in dynamic shape operations like DynamicReshape and DynamicBroadcastInDim.
It can be created with one of:
- StaticDim(int): the dimension is a constant known at graph building time.
- DynamicDim(*Node): the dimension is given by the input node, and the resulting axis has an anonymous dynamic dimension.
- NamedDynamicDim(name, *Node): the dimension is given by the input node and is named.
- InferredDim(): the dimension is automatically inferred to preserve total tensor size (can ONLY be used for at most one axis in DynamicReshape, and nowhere else).
- NamedInferredDim(name): the dimension is automatically inferred and named (can ONLY be used for at most one axis in DynamicReshape, and nowhere else).
- DimensionSpecFor(x, axis): extracts the dimension specification for the given axis of x.
- DimensionSpecsFor(x): extracts dimension specifications for all axes of x.
func DimensionSpecFor ¶ added in v0.28.5
func DimensionSpecFor(x *Node, axis int) DimensionSpec
DimensionSpecFor returns the DimensionSpec corresponding to the given axis of x. If the axis has a static dimension, it returns StaticDim(dim). If the axis has a dynamic dimension, it extracts DimensionSize(x, axis) and returns NamedDynamicDim(name, sizeNode).
func DimensionSpecsFor ¶ added in v0.28.5
func DimensionSpecsFor(x *Node) []DimensionSpec
DimensionSpecsFor returns a slice of DimensionSpecs for all axes of x. Static dimensions produce StaticDim, and dynamic dimensions produce NamedDynamicDim with their runtime *Node values.
func DynamicDim ¶ added in v0.28.2
func DynamicDim(dim *Node) DimensionSpec
DynamicDim specifies a dynamic dimension whose value is given by the input node.
Use this with DynamicReshape, DynamicBroadcastInDim, and DynamicIota.
func InferredDim ¶ added in v0.28.2
func InferredDim() DimensionSpec
InferredDim specifies that the dimension of the axis is automatically inferred to preserve the total size of the tensor.
Note: Inferred dimensions can ONLY be used for at most one axis in DynamicReshape. They cannot be used with DynamicBroadcast operations or DynamicIota.
func NamedDynamicDim ¶ added in v0.28.2
func NamedDynamicDim(name string, dim *Node) DimensionSpec
NamedDynamicDim specifies a dynamic dimension whose value is given by the input node and is named.
Use this with DynamicReshape, DynamicBroadcastInDim, and DynamicIota.
func NamedInferredDim ¶ added in v0.28.2
func NamedInferredDim(name string) DimensionSpec
NamedInferredDim specifies that the dimension of the axis is automatically inferred and named to preserve the total size of the tensor.
Note: Inferred dimensions can ONLY be used for at most one axis in DynamicReshape. They cannot be used with DynamicBroadcast operations or DynamicIota.
func StaticDim ¶ added in v0.28.2
func StaticDim(dim int) DimensionSpec
StaticDim specifies a static dimension. The dimension is a constant known at graph building time.
Use this with DynamicReshape, DynamicBroadcastInDim, and DynamicIota.
func (DimensionSpec) AxisName ¶ added in v0.28.5
func (s DimensionSpec) AxisName() string
AxisName returns the name associated with this dimension (or "" / shapes.AnonymousAxis).
func (DimensionSpec) Clone ¶ added in v0.28.5
func (s DimensionSpec) Clone() DimensionSpec
Clone returns a copy of the DimensionSpec.
func (DimensionSpec) Dynamic ¶ added in v0.28.5
func (s DimensionSpec) Dynamic() *Node
Dynamic returns the *Node representing the dynamic dimension, or nil if static or inferred.
func (DimensionSpec) IsDynamic ¶ added in v0.28.5
func (s DimensionSpec) IsDynamic() bool
IsDynamic returns true if the dimension is given by a dynamic *Node.
func (DimensionSpec) IsInferred ¶ added in v0.28.5
func (s DimensionSpec) IsInferred() bool
IsInferred returns true if the dimension is automatically inferred.
func (DimensionSpec) IsStatic ¶ added in v0.28.5
func (s DimensionSpec) IsStatic() bool
IsStatic returns true if the dimension is a constant known at graph building time.
func (DimensionSpec) Static ¶ added in v0.28.5
func (s DimensionSpec) Static() int
Static returns the static dimension size, or shapes.DynamicDim (-1) if dynamic or inferred.
func (DimensionSpec) String ¶ added in v0.28.5
func (s DimensionSpec) String() string
String implements fmt.Stringer for nice debug and error printing.
func (DimensionSpec) WithName ¶ added in v0.28.5
func (s DimensionSpec) WithName(name string) DimensionSpec
WithName returns a copy of the DimensionSpec with the specified axis name.
type DistributedOps ¶
type DistributedOps struct {
// contains filtered or unexported fields
}
DistributedOps provides a namespace for all distributed and collective operations on a graph. It is accessed via graph.Graph.Distributed().
It also acts as a builder, allowing optional parameters (like mesh axes) to be set via chaining.
func (*DistributedOps) AllReduce ¶
func (d *DistributedOps) AllReduce(operands []*Node, reductionType compute.ReduceOpType) []*Node
AllReduce performs a reduce operation across the devices specified in the chained options.
It takes a collection of operands and reduces each of them across the devices as outputs. So the output shapes are the same as the operand shapes.
If no device axes were specified via DistributedOps.Along(), it performs the operation across *all* devices in the mesh.
func (*DistributedOps) AllReduceOne ¶
func (d *DistributedOps) AllReduceOne(input *Node, reductionType compute.ReduceOpType) *Node
AllReduceOne performs a reduce operation across the devices specified in the chained options. So the output shapes are the same as the operand shapes.
If no device axes were specified via DistributedOps.Along(), it performs the operation across *all* devices in the mesh.
func (*DistributedOps) Along ¶
func (d *DistributedOps) Along(meshAxes ...string) *DistributedOps
Along specifies which DeviceMeshes axes the *next* collective operation should apply to.
For example:
g.Distributed().Along("data").AllReduceOne(x, compute.ReduceOpSum)
This will perform an AllReduceOne along the "data" axis of the mesh.
type DotBuilder ¶
type DotBuilder struct {
// contains filtered or unexported fields
}
DotBuilder is a builder for the DotGeneral operation.
func Dot ¶
func Dot(lhs, rhs *Node) *DotBuilder
Dot returns a builder for a generic, highly configurable "DotGeneral" operation. It returns a DotBuilder object, and once configured, one can call:
- Product(): the simplest form, it performs dot product of vectors, or vector-matrix/matrix-vector or simple matrix multiplications, for lhs/rhs ranks <= 2. Similar to numpy.dot.
- MatMul(): it assumes a batch dimension to the lhs.
- Einsum(): it performs a generic einsum operation, given an equation.
- DotGeneral(): it performs an arbitrary "DotGeneral" operation, where contracting and batch axes can be selected, the remainder axes are assumed to be cross-product.
func (*DotBuilder) Einsum ¶
func (b *DotBuilder) Einsum(equation string) *Node
Einsum evaluates the "Einstein summation" various types of products (inner/outer/batched) between 2 tensors, on arbitrary dimensions. This version uses a textual description on how to manipulate the axes. See EinsumAxes for a version where the axes are given numerically.
This is inspired on numpy Einsum, a description of which can be seen in https://stackoverflow.com/questions/26089893/understanding-numpys-einsum/33641428#33641428.
The equation string describes what to do with each dimension, for each operand, separated by ",", and the format of the result after the "->" describes what is to be made for each dimension.
Examples:
* `Dot(matrixA, matrixB).Einsum("ij,jk->ik")` performs the usual matrix multiplication. * `Dot(batchedMatrixA, batchedMatrixB).Einsum("bij,bjk->bik")` performs a batched matrix multiplication. * `Dot(vectorA, vectorB).Einsum("i,i->")` performs a dot product. * `Dot(vectorA, vectorB).Einsum("i,j->ij")` performs an outer (cross) product between two vectors.
It also works for higher dimension tensors. Dimensions missing on the output (after "->") are reduce-summed.
More examples in TensorFlow documentation: https://www.tensorflow.org/api_docs/python/tf/einsum
Notice though that this Einsum is only defined for operations between 2 operands:
- `lhs`: left-hand-side operand. - `rhs`: right-hand-side operand.
Important note: the order of the operands can have a dramatic impact on the speed of the multiplications. consider trying both sides.
func (*DotBuilder) EinsumAxes ¶
func (b *DotBuilder) EinsumAxes(contractingAxes, batchAxes [][2]int) (output *Node)
EinsumAxes evaluates the "Einstein summation" various types of products (inner/outer/batched) between 2 tensors, on arbitrary dimensions. Similar to Einsum, but it uses the explicit numeric axis, as opposed to a textual description.
There are two operands: `lhs` (left-hand-side) and `rhs` (right-hand-side). The default for every axis is to do a cross-product, and the resulting tensor will have the concatenated shape (`lhs` dimensions first then `rhs` dimensions).
One can specify contractionAxes, pairs of axes (each pair with one index in the lhs and rhs operands) to be contracted: these dimensions will multiplied and summed one at a time. That's what happens in the usual "dot product."
One can also specify batchAxes, pairs of axes (each pair with one index in the lhs and rhs operands) to be considered as independently, as a batch dimension. These dimensions will show up in the same position as the `lhs`.
Examples:
- `Dot(matrixA, matrixB).EinsumAxes([][2]int{{1, 0}}, nil)` performs the usual matrix multiplication, where we contract axis 1 of `matrixA` with axis 0 of `matrixB`.
- `Dot(batchedMatrixA, batchedMatrixB).EinsumAxes([][2]int{{2, 1}}, [][2]int{{0, 0}})` is similar, but we use axis 0 of both inputNodes as a batch, and following 2 axes as a matrix multiplication.
- `Dot(vectorA, vectorB).EinsumAxes(nil, nil)` performs an outer (cross) product -- no contractions, no batch.
- `Dot(vectorA, vectorB).EinsumAxes([][2]int{{0, 0}}, nil)` performs a dot product and returns a scalar.
Important note: the order of the operands can have a dramatic impact on the speed of the multiplications. Consider trying both sides.
func (*DotBuilder) General ¶
func (b *DotBuilder) General( lhsContractingAxes, lhsBatchAxes []int, rhsContractingAxes, rhsBatchAxes []int, ) *Node
General takes as input lhs (left-hand-side) and rhs (right-hand-side) specifications for a general vector product -- a generalized "Einsum". Each axis can be:
- Just aligned (batch axes), so the output has the same axes as the inputs. The dimensions must match in lhs and rhs.
- Crossed (default), in which case the output is the combination (concatenation) of the dimensions.
- Contracted (contracting axes), where the output does multiply the values and reduce sum those dimensions.
It follows that the resulting dimension number starts with the batch dimension, then the 'lhs' non-contracting/non-batch dimension, and finally the 'rhs' non-contracting/non-batch dimension. It provides the basic means of implementing Einsum.
func (*DotBuilder) MatMul ¶
func (b *DotBuilder) MatMul() *Node
MatMul is the `numpy.matmul` equivalent, for those used to that.
It is similar to Dot but extends to allow for more batch dimensions in lhs or rhs operand, and does broadcasting (of all but the last 2 axes) according to the numpy broadcasting rules.
It's popular hence it is here, but full of edge cases, consider using Dot().General() instead.
func (*DotBuilder) Product ¶
func (b *DotBuilder) Product() *Node
Product performs a generic linear dot-product operation, extended to handle matrices (rank-2 lhs and/or rhs), similar to numpy.dot.
The exact semantics of this operation depend on the ranks of the operands:
- Dot([n], [n]).Product() -> scalar
- Dot([m, k], [k]).Product() -> vector [m]
- Dot([k], [k, n]).Product() -> vector [n]
- Dot([m, k], [k, n]).Product() -> matrix [m x n]
func (*DotBuilder) WithAccumulatorDType ¶
func (b *DotBuilder) WithAccumulatorDType(dtype dtypes.DType) *DotBuilder
WithAccumulatorDType sets the accumulator data type for the DotGeneral operation.
Support for accumulator dtypes is very backend dependent. For example, XLA only supports mixed dtypes if accumulation is in F32.
GoMLX's Dot() operation will attempt to recover from an error and pre-convert the operands (lhs, rhs) to the accumulator dtype if the backend yields a "not-implemented" error.
func (*DotBuilder) WithOutputDType ¶
func (b *DotBuilder) WithOutputDType(dtype dtypes.DType) *DotBuilder
WithOutputDType sets the output data type for the DotGeneral operation.
Some combinations of input/accumulator/output dtypes may be invalid and yield errors -- in which case simply use ConvertDType after the DotGeneral operation.
type DynamicPadAxisSpec ¶ added in v0.28.5
type DynamicPadAxisSpec struct {
Start, End, Interior int
StartNode, EndNode, InteriorNode *Node
TargetAxisName string
}
DynamicPadAxisSpec specifies the padding configuration for an axis in DynamicPad. It can specify static integer padding amounts and/or dynamic scalar *Node amounts.
func DynamicPadAxis ¶ added in v0.28.5
func DynamicPadAxis(start, end, interior int) DynamicPadAxisSpec
DynamicPadAxis creates a DynamicPadAxisSpec with static padding amounts.
type Exec ¶
type Exec struct {
// contains filtered or unexported fields
}
func MustNewExec ¶
func MustNewExec[F ExecGraphFn](backend compute.Backend, graphFn F) *Exec
MustNewExec constructs an Exec object that uses the given graphFn to build computation graphs.
graphFn should take *Node as input and return a *Node -- except if there are no (Node) inputs, in which case it should take a single *Graph input.
It's a wrapper for MustNewExecCanonical, but uses generics to type check that graphFn is valid.
func MustNewExecCanonical ¶
func MustNewExecCanonical(backend compute.Backend, graphFn CanonicalExecGraphFn, numInputs, numOutputs int, inputIsGraph, inputAsSlice, outputAsSlice bool) *Exec
MustNewExecCanonical constructs an Exec object that uses the given graphFn to build computation graphs.
`graphFn` must be of type CanonicalExecGraphFn.
It panics if the inputs are invalid.
See also the generics MustNewExec (or MustNewExec for returning an error), which checks for valid graphFn in compile time.
func NewExec ¶
func NewExec[F ExecGraphFn](backend compute.Backend, graphFn F) (*Exec, error)
NewExec constructs an Exec object that uses the given graphFn to build computation graphs.
graphFn should take *Node as an input and return a *Node -- except if there are no (Node) inputs, in which case it should take a single *Graph input.
It's a wrapper to the NewExecCanonical, but it uses generics to add a compile-time check for valid graphFn signature.
func NewExecCanonical ¶
func NewExecCanonical(backend compute.Backend, graphFn CanonicalExecGraphFn, numInputs, numOutputs int, inputIsGraph, inputAsSlice, outputAsSlice bool) (*Exec, error)
NewExecCanonical constructs an Exec object that uses the given graphFn to build computation graphs.
The `graphFn` must be of type CanonicalExecGraphFn.
Please use NewExec if possible, it adds a compile-time check for most valid signatures of graphFn.
It returns an error if the inputs are invalid.
func (*Exec) AggregateShards ¶
AggregateShards returned by Exec into dtensor.Tensor. Usually, Exec will return a slice of numDevices * numOutputs individual shards (tensors.Tensor).
See also DistributedExec, which calls Exec and then calls this.
func (*Exec) AutoSharding ¶
func (e *Exec) AutoSharding(meshes ...*distributed.DeviceMesh) *Exec
AutoSharding sets the distribution strategy to AutoSharding and records the meshes that will be used in the computation graph(s).
A nil mesh will cause a panic.
It returns a reference to itself, so configuration calls can be cascaded.
func (*Exec) Call ¶
Call executes the computation with the given arguments.
It the input arguments shape has never been seen before, it JIT-compiles a new computation graph for that shape, which can take a while, but is cached and later executions are very fast.
The arguments are first all converted to tensors where needed.
Optionally, use DonateTensorBuffer(value) to mark a tensor as a value to be "donated" to the execution (and potentially save some space). See details in DonateTensorBuffer.
It returns the outputs in a slice, even if there is only one output, or an error if it fails. See Exec1-Exec4 for aliases that return some exact number of outputs.
Errors (with full stack-traces) are returned on failure.
func (*Exec) Call1 ¶
Call1 calls the compiled the graph with the given arguments and returns one output.
It returns an error if the graph doesn't return exactly one output.
See Callfor more details.
func (*Exec) Call2 ¶
Call2 calls the compiled graph with the given arguments and returns two outputs.
It returns an error if the graph doesn't return exactly two outputs.
See Call for more details.
func (*Exec) Call3 ¶
Call3 calls the compiled graph with the given arguments and returns three outputs.
It returns an error if the graph doesn't return exactly three outputs.
See Call for more details.
func (*Exec) Call4 ¶
func (e *Exec) Call4(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, *tensors.Tensor, error)
Call4 calls the compiled graph with the given arguments and returns four outputs.
It returns an error if the graph doesn't return exactly four outputs.
See Exec for more details.
func (*Exec) CallOnDevice ¶
func (e *Exec) CallOnDevice(defaultDevice compute.DeviceNum, args ...any) ([]*tensors.Tensor, error)
CallOnDevice behaves like Exec but for portable computations uses the given device for execution.
deafultDevice is used for single-device computations that are portable (no fixed device assignment set WithDeviceAssignment). Otherwise, it is ignored.
func (*Exec) CallWithGraph ¶
CallWithGraph is similar to Exec, but it also returns the computation graph used in the call.
Exec creates different computation graphs when the inputs' shapes change, so different calls may return different graphs.
It returns the outputs in a slice, even if there is only one output. It also returns the computation graph used.
Distributed execution: if the Exec was configured with AutoSharding(meshes..) or SPMD(mesh), then it requires the input values for each device used in the execution. So if there are D devices, and I inputs, it required D*I args, organized in a "device-major" list (all the inputs to the first device, then the inputs for the second device, and so on). Alternatively, you can provide I args of dtensor.Tensor (they already include one value per device), matching the DistributedMesh provided to Exec.SPMD.
Errors (with full stack-traces) are returned on failure.
func (*Exec) CallWithGraphOnDevice ¶
func (e *Exec) CallWithGraphOnDevice(defaultDevice compute.DeviceNum, args ...any) ( []*tensors.Tensor, *Graph, error)
ExecWithGraphOnDevice is a version of ExecGraph that runs on the given device by default.
defaultDevice is used for single-device computations that are portable (no fixed device assignment set WithDeviceAssignment). Otherwise, it is ignored.
func (*Exec) Compile ¶ added in v0.28.2
Compile creates (if not yet created) and compiles the computation graph for the given input shapes, without executing it.
func (*Exec) DeviceAssignment ¶
DeviceAssignment returns the current device assignment used by this Exec. It returns nil if none was provided.
func (*Exec) DistributedCall ¶
DistributedCall is just like Exec, but aggregates the outputs into dtensor.Tensor. Usually, Exec will return a slice of numDevices * numOutputs individual shards (tensors.Tensor).
Notice that to actually trigger distributed execution, you must set Exec.AutoSharding (or Exec.SPMD) and set the proper sharding specs of the inputs and outputs.
See also Exec.AggregateShards.
func (*Exec) DistributionStrategy ¶
func (e *Exec) DistributionStrategy() distributed.Strategy
DistributionStrategy returns the distribution strategy used by this Exec.
The default is distributed.None, which means that graphs constructed by this Exec will not be distributed, and it will be executed on the device specified by Exec.WithDevice (defaults to 0).
func (*Exec) Finalize ¶
func (e *Exec) Finalize()
Finalize clears the cache, finalizing the compiled graphs. The Exec object shouldn't be used after that.
Finalize marks the Exec as finalized, preventing any new calls or compilations from starting (they will immediately return ErrExecFinalized). It then blocks until all currently active in-flight calls and compilations finish executing, and finally releases resources for all cached graphs.
It is safe to call Finalize multiple times; calls after the first are no-ops.
func (*Exec) GetNodeLogger ¶
GetNodeLogger returns the currently registered LoggerFn.
func (*Exec) Meshes ¶
func (e *Exec) Meshes() []*distributed.DeviceMesh
Meshes returns the slice of currently configured meshes. It returns nil if no meshes were provided (e.g., for non-distributed execution).
func (*Exec) MustCall ¶
MustCall calls the computation with the given arguments.
It the input arguments shape has never been seen before, it JIT-compiles a new computation graph for that shape, which can take a while, but is cached and later executions are very fast.
The arguments are first all converted to tensors, if they not yet tensors.
Optionally, use DonateTensorBuffer(value) to mark a tensor as a value to be "donated" to the execution (and potentially save some space). See details in DonateTensorBuffer.
It returns the outputs in a slice, even if there is only one output, or an error if it fails. See Exec1-Exec4 for aliases that return some exact number of outputs.
It panics on errors (with full stack-traces).
func (*Exec) MustCall1 ¶
MustCall1 executes the graph with the given arguments and returns one output.
It panics on errors (with full stack-traces) or if the graph doesn't return exactly one output.
See MustExec for more details.
func (*Exec) MustCall2 ¶
MustCall2 executes the graph with the given arguments and returns two outputs.
It panics on errors (with full stack-traces) or if the graph doesn't return exactly two outputs.
See MustExec for more details.
func (*Exec) MustCall3 ¶
MustCall3 executes the graph with the given arguments and returns three outputs.
It panics on errors (with full stack-traces) or if the graph doesn't return exactly three outputs.
See MustExec for more details.
func (*Exec) MustCall4 ¶
func (e *Exec) MustCall4(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, *tensors.Tensor)
MustCall4 executes the graph with the given arguments and returns four outputs.
It panics on errors (with full stack-traces) or if the graph doesn't return exactly four outputs.
See MustExec for more details.
func (*Exec) MustCallWithGraph ¶
MustCallWithGraph is similar to MustExec, but it also returns the computation graph used in the call.
The underlying Exec creates different computation graphs when the inputs' shapes change, so different calls may return different graphs.
It returns the outputs in a slice, even if there is only one output. It also returns the computation graph used.
It panics on errors (with full stack-traces).
func (*Exec) NumDevices ¶
NumDevices returns the number of devices used by the current strategy.
func (*Exec) SPMD ¶
func (e *Exec) SPMD(mesh *distributed.DeviceMesh) *Exec
SPMD sets the distribution strategy to SPMD, which means that graphs constructed by this Exec will be replicated across the devices specified in the mesh.
A nil mesh will cause a panic.
It returns a reference to itself, so configuration calls can be cascaded.
func (*Exec) SetMaxCache ¶
SetMaxCache sets the maximum size of the cache. Set it to -1 to have unlimited cache size. It returns a reference to itself so calls can be cascaded.
func (*Exec) SetNodeLogger ¶
SetNodeLogger with the function to be called for the nodes marked for logging during execution. If set to nil, nothing will be logged.
func (*Exec) SetSideParamsHook ¶
func (e *Exec) SetSideParamsHook(fn SideParamsFn) *Exec
SetSideParamsHook configures a function to be called just before executing a graph, so it can set extra parameters.
Mostly, this is for internal use and end-users will not likely need this. The model.Exec object uses this to pass the variable values as side inputs to the graph.
Exec takes care of creating parameters (with graph.Parameter) for every value passed to Exec.Call before calling the graph building function (the graph building function is executed only the first time, after the graph is compiled, it is re-used for future executions).
But a graph building function may want to create extra parameters itself (with graph.Parameter), which we call "side parameters".
The values to feed these "side parameters" are not passed to Exec.MustCall, but instead set with a SideParamsFn, which is configured here.
SideParamsFn is called after the graph is already built, just before the execution. It is passed with a slice of the backend.Buffer to be fed to the graph execution. The side parameters in this slice will be left nil, and it's expected that SideParamsFn will set them to the appropriate input.
Notice: len(inputBuffers) = len(donate) = g.NumDevices() * g.NumParameters(), organized by device first. The SideParamsFn needs to set the last parameters (currently nil) for each device, in the order they were added to the backend.
It also includes the boolean map of the inputs to donate, which SideParamsFn can set accordingly (for the side parameters).
func (*Exec) WithDeviceAssignment ¶
WithDeviceAssignment specifies which concrete devices to use when compiling computation graphs.
These must be valid numbers for the backend and must match the number of devices of the largest mesh given to WithAutoSharding or WithSPMD, or one fixed device for non-portable single-device execution.
The default assignment is simply using the devices in the order they were added to the backend (sequential DeviceNum values, starting from 0).
For single-device execution (distributed strategy "None"), the default is to make it portable. If the backend supports that, it can be executed in any device with ExecOnDevice().
func (*Exec) WithDynamicAxes ¶
WithDynamicAxes sets the names of the axes that should be treated as dynamic for each input parameter. Any axis that is dynamic must have a non-empty name (e.g., "batch"). Static axes should have an empty string (""). The rank of each input parameter must match the length of its corresponding axisNames slice.
By marking an axis as dynamic, the computation graph will be compiled once with a symbolic size (e.g., shapes.DynamicDim) for that dimension. During subsequent executions, the actual size of the dynamic dimension is resolved dynamically from the shape of the execution inputs, avoiding expensive graph re-compilations for different input shapes.
Example:
exec, err := graph.NewExec(backend, func(x *graph.Node) *graph.Node {
return graph.Add(x, x)
})
// Configure the first input parameter (x) to have a dynamic dimension on axis 0, named "batch".
// The second axis (axis 1) of x is static, so we pass "" for it.
exec.WithDynamicAxes([]string{"batch", ""})
// exec can now be run with inputs of different batch sizes without triggering JIT re-compilation:
res1 := exec.MustExec(tensors.MustFromAnyValue(matrixOf32x512)) // batch=32
res2 := exec.MustExec(tensors.MustFromAnyValue(matrixOf64x512)) // batch=64 (re-uses compiled graph)
func (*Exec) WithInputShardingSpecs ¶
func (e *Exec) WithInputShardingSpecs(specs ...*distributed.ShardingSpec) *Exec
WithInputShardingSpecs sets the sharding specs for the inputs.
This is used for distributed computations with AutoSharding.
If the function takes variable inputs (`[]*Node`), then the last spec provided is used for all remaining inputs.
It returns a reference to itself so calls can be cascaded.
func (*Exec) WithName ¶
WithName sets the name of Exec, used to provide the name to graphs created. This should be called before any invocations of MustExec(). It returns a reference to itself so calls can be cascaded.
func (*Exec) WithOutputShardingSpecs ¶
func (e *Exec) WithOutputShardingSpecs(specs ...*distributed.ShardingSpec) *Exec
WithOutputShardingSpecs sets the sharding specs for the outputs.
If the function takes variable inputs (`[]*Node`), then the last spec provided is used for all remaining inputs.
This is used for distributed computations with AutoSharding.
It returns a reference to itself so calls can be cascaded.
type ExecGraphFn ¶
type ExecGraphFn interface {
ExecGraphFnOneOutput | ExecGraphFnTwoOutputs | ExecGraphFnThreeOutputs | ExecGraphFnSliceOutputs
}
type ExecGraphFnOneOutput ¶
type ExecGraphFnOneOutput interface {
func(*Graph) *Node |
func([]*Node) *Node |
func(*Graph, []*Node) *Node |
func(*Node) *Node |
func(*Node, *Node) *Node |
func(*Node, *Node, *Node) *Node |
func(*Node, *Node, *Node, *Node) *Node |
func(*Node, *Node, *Node, *Node, *Node) *Node |
func(*Node, *Node, *Node, *Node, *Node, *Node) *Node
}
type ExecGraphFnSliceOutputs ¶
type ExecGraphFnSliceOutputs interface {
func(*Graph) []*Node |
func([]*Node) []*Node |
func(*Graph, []*Node) []*Node |
func(*Node) []*Node |
func(*Node, *Node) []*Node |
func(*Node, *Node, *Node) []*Node |
func(*Node, *Node, *Node, *Node) []*Node |
func(*Node, *Node, *Node, *Node, *Node) []*Node |
func(*Node, *Node, *Node, *Node, *Node, *Node) []*Node
}
type ExecGraphFnThreeOutputs ¶
type ExecGraphFnThreeOutputs interface {
func(*Graph) (*Node, *Node, *Node) |
func([]*Node) (*Node, *Node, *Node) |
func(*Graph, []*Node) (*Node, *Node, *Node) |
func(*Node) (*Node, *Node, *Node) |
func(*Node, *Node) (*Node, *Node, *Node) |
func(*Node, *Node, *Node) (*Node, *Node, *Node) |
func(*Node, *Node, *Node, *Node) (*Node, *Node, *Node) |
func(*Node, *Node, *Node, *Node, *Node) (*Node, *Node, *Node) |
func(*Node, *Node, *Node, *Node, *Node, *Node) (*Node, *Node, *Node)
}
type ExecGraphFnTwoOutputs ¶
type ExecGraphFnTwoOutputs interface {
func(*Graph) (*Node, *Node) |
func([]*Node) (*Node, *Node) |
func(*Graph, []*Node) (*Node, *Node) |
func(*Node) (*Node, *Node) |
func(*Node, *Node) (*Node, *Node) |
func(*Node, *Node, *Node) (*Node, *Node) |
func(*Node, *Node, *Node, *Node) (*Node, *Node) |
func(*Node, *Node, *Node, *Node, *Node) (*Node, *Node) |
func(*Node, *Node, *Node, *Node, *Node, *Node) (*Node, *Node)
}
type ExecOneOutput ¶
type ExecOneOutput struct {
*Exec
}
ExecOneOutput is a wrapper around Exec for graphs that return exactly one output.
func MustNewExec1 ¶
func MustNewExec1[F ExecGraphFnOneOutput](backend compute.Backend, graphFn F) *ExecOneOutput
MustNewExec1 constructs an ExecOneOutput wrapper around a new Exec object and panics on error.
func NewExec1 ¶
func NewExec1[F ExecGraphFnOneOutput](backend compute.Backend, graphFn F) (*ExecOneOutput, error)
NewExec1 constructs an ExecOneOutput wrapper around a new Exec object, constraining the graphFn to return a single output.
type ExecThreeOutputs ¶
type ExecThreeOutputs struct {
*Exec
}
ExecThreeOutputs is a wrapper around Exec for graphs that return exactly three outputs.
func MustNewExec3 ¶
func MustNewExec3[F ExecGraphFnThreeOutputs](backend compute.Backend, graphFn F) *ExecThreeOutputs
MustNewExec3 constructs an ExecThreeOutputs wrapper around a new Exec object and panics on error.
func NewExec3 ¶
func NewExec3[F ExecGraphFnThreeOutputs](backend compute.Backend, graphFn F) (*ExecThreeOutputs, error)
NewExec3 constructs an ExecThreeOutputs wrapper around a new Exec object, constraining the graphFn to return three outputs.
type ExecTwoOutputs ¶
type ExecTwoOutputs struct {
*Exec
}
ExecTwoOutputs is a wrapper around Exec for graphs that return exactly two outputs.
func MustNewExec2 ¶
func MustNewExec2[F ExecGraphFnTwoOutputs](backend compute.Backend, graphFn F) *ExecTwoOutputs
MustNewExec2 constructs an ExecTwoOutputs wrapper around a new Exec object and panics on error.
func NewExec2 ¶
func NewExec2[F ExecGraphFnTwoOutputs](backend compute.Backend, graphFn F) (*ExecTwoOutputs, error)
NewExec2 constructs an ExecTwoOutputs wrapper around a new Exec object, constraining the graphFn to return two outputs.
type Function ¶
type Function struct {
// contains filtered or unexported fields
}
Function represents a function in the graph.
The Graph always is associated with a "current" function, where it is operating. It defaults to the main function (named "main") automatically created when the graph is created.
But if the backend supports it, other top-level functions or closures (also a type of function) can be created. See NewClosure and NewFunction functions.
func NewClosure ¶
NewClosure creates a new closure in the current graph.
Closures are used as parameters for special operations like While, If, etc; they cannot be called directly.
Closures, unlike top-level functions (created with NewFunction), can access variables from the parent scope. Because of that they are not named and not registered in the Graph (so they cannot be retrieved by name).
It creates the new Function object, sets it temporarily as the current for the Graph (reversed on exit) and call the funcDef with it.
The signature of the created function will have the inputs based on the parameters created by funcDef, and the outputs based on the return values of funcDef.
func NewClosureWithSharding ¶
func NewClosureWithSharding(g *Graph, funcDef func(g *Graph) ([]*Node, []*distributed.ShardingSpec)) *Function
NewClosureWithSharding creates a new closure in the current graph.
Closures are used as parameters for special operations like While, If, etc; they cannot be called directly.
It is similar to NewClosure, but funcDef also returns the sharding information, and it is used on f.Return in the end.
If the returned sharding information if not nil, it validates the sharding to the output nodes. Otherwise (sharding is nil), it behaves just like NewClosure.
func NewFunction ¶
NewFunction creates a new top-level function in the current graph.
It creates the new Function object, sets it temporarily as the current for the Graph (reversed on exit) and call the funcDef with it.
The signature of the created function will have the inputs based on the parameters created by funcDef, and the outputs based on the return values of funcDef.
func NewFunctionWithSharding ¶
func NewFunctionWithSharding(g *Graph, name string, funcDef func(g *Graph) ([]*Node, []*distributed.ShardingSpec)) *Function
NewFunctionWithSharding creates a new top-level function in the current graph.
It is similar to NewFunction, but funcDef also returns the sharding information, and it is used on f.Return in the end.
If the returned sharding information if not nil, it validates the sharding to the output nodes. Otherwise (sharding is nil), it behaves just like NewFunction.
func (*Function) Call ¶
Call a function with the given inputs.
The function f must be from the same graph.
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) Name ¶
Name returns the name of the function.
For top-level functions the name is unique. For closures the name is "".
func (*Function) Parent ¶
Parent return the parent function of a closure. It returns nil if this is a top-level function.
func (*Function) Path ¶
Path returns the full path of the function, following its parents to the root. Empty names (closures) are replaced by "closure".
func (*Function) Return ¶
func (f *Function) Return(outputs []*Node, outputShardings []*distributed.ShardingSpec)
Return from the given function. This is the last operation of a function.
Don't call this directly, this is mostly for internal use and testing: Compile, NewFunction and NewClosure will call this automatically.
type Graph ¶
type Graph struct {
// contains filtered or unexported fields
}
Graph with the operations and dependencies needed to run a computation.
See details in the package graph documentation.
func NewGraph ¶
NewGraph constructs an empty Graph.
An empty Graph can be further configured (e.g., with Graph.WithName) until one starts building a computation.
After building a computation, they can be compiled (see Graph.Compile), at which point the Graph becomes immutable and can only be executed.
If it is finalized (see Graph.Finalize), resources are released immediately (instead of waiting for the GC), and the Graph can no longer be used.
func (*Graph) AssertBuilding ¶
func (g *Graph) AssertBuilding()
AssertBuilding panics if the graph is nil, has been finalized, or has already been compiled and therefore immutable. If the Graph was in a configuring state (just after the creation), this triggers it to enter into a "building" state.
func (*Graph) AssertCompiled ¶
func (g *Graph) AssertCompiled()
AssertCompiled panics if the graph is nil, if it has already been finalized, or if it is not yet compiled (still building).
func (*Graph) AssertConfiguring ¶
func (g *Graph) AssertConfiguring()
AssertConfiguring panics if the graph is not in a "configuring" phase: that is, if one already started building a computation with it, or if it has already been compiled (immutable). It also panics if it is not valid (e.g.: if it has been finalized).
func (*Graph) AssertNotReturned ¶
func (g *Graph) AssertNotReturned()
AssertNotReturned panics if the graph is nil, has been finalized, or if the current function has already returned or the graph has already been compiled.
func (*Graph) AssertValid ¶
func (g *Graph) AssertValid()
AssertValid panics if the graph is nil or if it has already been finalized.
func (*Graph) AttachState ¶
AttachState saves an arbitrary object to the graph. These state objects are opaque to Graph itself, it simply keeps this map for the user.
This can be used, for instance, to store the root model, or any other type of "global" (graph-scoped) state.
The convention is to use as key an empty unique struct, defined in the same package as the type being stored, like:
type myStateKey struct{}
type MyState struct {...}
...
g.AttachState(myStateKey{}, &MyState{...})
If no key is provided, it panics.
func (*Graph) CheckValid ¶
CheckValid returns an error if the graph is nil or if it has already been finalized.
func (*Graph) Compile ¶
Compile just-in-time (JIT) compiles the Graph into a Computation that can be executed.
At least one output must be given.
func (*Graph) CompileWithSharding ¶
func (g *Graph) CompileWithSharding(outputs []*Node, outputShardings []*distributed.ShardingSpec) error
CompileWithSharding compiles the graph with the given outputs and optionally with the sharding specifications for these outputs.
At least one output must be given.
This is an advanced version of Compile, used for distributed computation with AutoSharding.
func (*Graph) CurrentFunc ¶
CurrentFunc returns the current function scope of the Graph.
func (*Graph) DeviceMeshes ¶
func (g *Graph) DeviceMeshes() []*distributed.DeviceMesh
DeviceMeshes returns the graph's DeviceMeshes. These are owned by the graph and should not be modified.
func (*Graph) Distributed ¶
func (g *Graph) Distributed() *DistributedOps
Distributed returns a helper object that provides access to all distributed and collective operations.
func (*Graph) DistributedStrategy ¶
func (g *Graph) DistributedStrategy() distributed.Strategy
DistributedStrategy returns the distributed strategy set for the graph. This is changed by configuring the Graph with SetAutoSharding or SetSPMD.
func (*Graph) DynamicDimDType ¶ added in v0.28.14
DynamicDimDType returns the DType used by the backend for dynamic dimensions (and returned by DimensionSize and DynamicShape). Defaults to dtypes.Int64 if the backend is nil or the field is unset.
func (*Graph) Executable ¶ added in v0.28.1
func (g *Graph) Executable() compute.Executable
Executable returns the compute.Executable associated with this graph.
It's a escape hatch to allow access to the backend implementation, and it's only available after the graph is compiled.
func (*Graph) Finalize ¶
func (g *Graph) Finalize()
Finalize frees the associated data with the compiled graph (if it is compiled) and all the nodes. The graph is left in an unusable state. It is safe to call it more than once. Calls on a finalized Graph are no-ops.
It is the responsibility of the caller to guarantee that there are no unfinished executions (such as calls to Graph.RunWithBuffers or Graph.Run) before calling Finalize. Calling Finalize while an execution is still running may lead to undefined behavior and potentially crash depending on the backend.
Calling Finalize is optional: one can always leave it to the garbage collector (GC), which will properly clean up native resources eventually. Alternatively, callers can rely on higher-level coordinator objects such as Exec or model.Exec to coordinate safe concurrent execution and teardown.
func (*Graph) GetNodeByAlias ¶
GetNodeByAlias returns a node with the given alias or nil if it didn't find it.
If the search alias has an absolute scope (path), meaning if it starts with AliasScopeSeparator, it is searched as is. If not, it is prefixed with the current scope before searching.
See Node.WithAlias to create node aliases, and Graph.PushAliasScope and Graph.PopAliasScope to manipulate the scope of the aliases created.
func (*Graph) GetParameterByHandle ¶
func (g *Graph) GetParameterByHandle(handle ParameterHandle) *Node
GetParameterByHandle returns the ii-th parameter, in order of creation, registered for this graph.
func (*Graph) GetParameterByName ¶
GetParameterByName returns the parameter registered with the given name. Returns nil if the parameter with the given name hasn't been registered (see Parameter method).
func (*Graph) GraphId ¶
GraphId is a globally unique id (even across different Backend's) of the graph. It's a counter that starts with 0.
func (*Graph) IsBuilding ¶
IsBuilding returns whether the Graph already started building a computation, in which case Graph parameters (like name, distribution strategy, etc.) can no longer be changed.
func (*Graph) IsCompiled ¶
IsCompiled returns whether the Graph has been compiled (immutable).
func (*Graph) IsMainFunc ¶
IsMainFunc returns whether the current Graph scope is the main function, that is, if we are not defining a separate top-level function or a closure.
See NewFunction or NewClosure for more details.
func (*Graph) IsValid ¶
IsValid returns whether the Graph is in a valid state: it is valid if it is in a configuring, building, or compiled state.
func (*Graph) IterAliasedNodes ¶
IterAliasedNodes provides an iterator over all aliased nodes. It yields pairs (alias, node). The aliases are sorted before iteration.
func (*Graph) LastNode ¶
LastNode returns the last node created. It returns nil if no node has been created for this graph yet.
func (*Graph) LoggedNodes ¶
LoggedNodes returns all nodes from the graph marked to be logged. Exec object makes use of this information and logs those values when executing the graph.
func (*Graph) Nodes ¶
Nodes return a slice of all nodes. The slice is owned by Graph and shouldn't be changed.
func (*Graph) NumDevices ¶
NumDevices participating in this computation graph.
This is 1 for non-distributed graphs. Otherwise, it's the number of devices in the mesh (see Graph.WithDeviceMesh).
func (*Graph) NumParameters ¶
NumParameters returns the number of parameters created for this graph.
func (*Graph) PopAliasScope ¶
func (g *Graph) PopAliasScope()
PopAliasScope removes the scope previously pushed with PushAliasScope.
It panics if there are no scopes pushed.
func (*Graph) PushAliasScope ¶
PushAliasScope pushes another scope to the current alias scope for new aliases.
For instance, for an image model, one may want to push a scope per layer, and create an alias "output" to the node with the output of the layer. The different scope helps differentiate the different "output" aliases nodes.
Notice this is orthogonal to the model.Store scope used for variables. That's because for instance, one may reuse a model multiple times for different inputs (e.g.: triplet loss will use the same model for the "anchor", "positive" and "negative" examples, or a style transfer model will use the same embedding model for the "source", "style" and "target" images), so the variables context scope is the same, but we want a different alias scope, so we can access the outputs per layer of each type of the example separately.
Each call to Graph.PushAliasScope should be matched by a call to Graph.PopAliasScope, usually using defer.
func (*Graph) Run ¶
Run the compiled Graph with the inputs given in order -- the same order as the parameters were created.
The values for inputs can be:
- A tensors.Tensor.
- Any multi-dimensional slice (e.g.: [][]float32 for a 2D float32 value) that is dynamically converted to a temporary tensor.
- The output of DonateTensorBuffer, which then donates the device buffer being used by a tensor -- if there are any.
This is a very "bare-bones" way of running the Graph. Typically, one would use the Exec object instead (which dynamically generates a new Graph for inputs of different shapes when needed).
To donate the inputs buffers (if they are no longer used, e.g., when updating a state), consider using DonateTensorBuffer.
If there are multiple devices, the inputs are split among them.
func (*Graph) RunOnDevice ¶
func (g *Graph) RunOnDevice(defaultDeviceNum compute.DeviceNum, inputs ...any) (outputs []*tensors.Tensor)
RunOnDevice runs the compiled Graph (see Graph.Run), but uses the defaultDeviceNum to run if the computation is not already fixed to a device.
If the computation was compiled with a fixed device assignment, the defaultDevieNum is ignored.
func (*Graph) RunWithBuffers ¶
func (g *Graph) RunWithBuffers(inputs []compute.Buffer, donate []bool, defaultDevice compute.DeviceNum) ( outputs []*tensors.Tensor)
RunWithBuffers executes the graph using as inputs the on-device buffers.
This is mostly internal, for the normal use cases, consider using the Exec object or Graph.Run.
The donate slice indicates which buffers can be donated to the execution -- they are immediately finalized after the execution is finished.
Notice that for repeated output nodes in the graph (the same output node returned in more than one position), the returned tensors are shared.
If there are multiple devices, the inputs are split among them.
func (*Graph) RunWithMap
deprecated
RunWithMap runs the compiled graph with the inputs given as a map of the corresponding parameter node to tensor value to use.
The values for the inputs can be:
- A tensors.Tensor.
- Any multi-dimensional slice (e.g.: [][]float32 for a 2D float32 value) that is dynamically converted to a temporary tensor.
- The output of DonateTensorBuffer, which then donates the device buffer being used by a tensor -- if there are any.
This is a very "bare-bones" way of running the Graph. Typically, one would use the Exec object instead (which dynamically generates a new Graph for inputs of different shapes when needed).
To donate the inputs buffers (if they are no longer used, e.g., when updating a state), consider using DonateTensorBuffer.
Deprecated: use Run or RunOnDevice instead.
func (*Graph) SetAutoSharding ¶
func (g *Graph) SetAutoSharding(meshes ...*distributed.DeviceMesh) error
SetAutoSharding sets the distributed strategy to AutoSharding and sets the device meshes that will be used for this Graph computation.
This is the supported and recommended strategy for distributed training. It uses XLA Shardy [1] framework to automatically shard the computation across the devices (both data and model), given sharded input and output shapes of the computations. (and optional in between hints).
func (*Graph) SetDeviceAssignment ¶
SetDeviceAssignment specifies which concrete devices to use for the graph.
These must be valid numbers for the backend and must match the number of devices of the largest mesh given to WithAutoSharding or WithSPMD.
The default assignment is simply using the devices in the order they were added to the backend (sequential DeviceNum values, starting from 0).
func (*Graph) SetSPMD ¶
func (g *Graph) SetSPMD(mesh *distributed.DeviceMesh) error
SetSPMD sets the distributed strategy to SPMD.
This is a Single Program Multiple Data (SPMD) strategy, where synchronization is done by the user with the "collective" operations (see Graph.Distributed()).
EXPERIMENTAL: For normal use WithAutoSharding instead. If you want to use this consider reaching out to the GoMLX team to discuss what you will need.
func (*Graph) SetTraced ¶
SetTraced defines whether each node creation is traced. If true, every node will save a stack-trace of where it was created, which is helpful for debugging. See Node.Track().
This is expensive, but can be handy for debugging.
func (*Graph) State ¶
State retrieves an object from the graph. These state objects are opaque to Graph itself, it simply keeps this map for the user.
The convention is to use as key an empty unique struct, defined in the same package as the type being stored, like:
type myStateKey struct{}
...
state := g.State(myStateKey{})
func (*Graph) String ¶
String converts the Graph to a multiline string with a description of the full graph.
func (*Graph) UniqueName ¶ added in v0.28.2
UniqueName generates a graph-unique name with the given base string as prefix. The first call with a base name returns "base", while subsequent calls return "base_1", "base_2", etc.
type GraphProvider ¶
type GraphProvider interface {
Graph() *Graph
}
GraphProvider is an interface for objects that have a reference to a Graph.
type InterpolationConfig ¶
type InterpolationConfig struct {
// contains filtered or unexported fields
}
InterpolationConfig is created with Interpolate and then actually executed with a call to Done.
Between the its construction and execution one can set the various parameters for the interpolation.
func Interpolate ¶
func Interpolate(input *Node, outputSizes ...int) *InterpolationConfig
Interpolate will interpolate the tensor to the given output sizes. The outputSizes should have the same rank as the image, and can have values set to NoInterpolation (`== -1`) for dimensions that shouldn't be changed.
Example:
image.AssertDims(100, 72, 72, 3) // Shape `[batch_size, height=72, width=72, depth]` image = Interpolate(image, -1, 64, 64, -1).Bilinear().Done() image.AssertDims(100, 64, 64, 3)
Interpolate will return an InterpolationConfig that can be configured. When Done() is called it builds the graph for the interpolation and returns the interpolated tensor. The default set up is using Bilinear interpolation and HalfPixelCenters set to true.
This can be used for images (2D) but also for anything volumetric (3D or higher) or also for time-series (1D).
The implementation is based on the Tensorflow `tf2xla` one.
func (*InterpolationConfig) AlignCorner ¶
func (c *InterpolationConfig) AlignCorner(alignCorner bool) *InterpolationConfig
AlignCorner configures the interpolation to be value of "align corner": if set to true, the input and output tensors corner pixels are aligned at the center points of their corner pixels, preserving the values at the corner pixels. If set to false, the input and output tensors are aligned by the corner points of their corner pixels, and the interpolation uses edge value padding for out-of-boundary values. Default is false.
One cannot select both, HalfPixelCenters(true) and AlignCorner(true).
Default is true.
It returns the InterpolationConfig passed, to allow cascaded method calls.
func (*InterpolationConfig) Bilinear ¶
func (c *InterpolationConfig) Bilinear() *InterpolationConfig
Bilinear configures the interpolation to be bilinear (as opposed to nearest). Default is Bilinear. See also Nearest.
It returns the InterpolationConfig passed, to allow cascaded method calls.
Note: there is a bug in that makes the Bilinear gradient fail if the input dimensions to interpolate <= 3. Use Nearest instead for now.
func (*InterpolationConfig) Done ¶
func (c *InterpolationConfig) Done() (output *Node)
Done finishes the configuration of the interpolation and creates the computation graph that resizes the input to the given output sizes. It returns the resized input.
Any errors are returned in the graph.
func (*InterpolationConfig) HalfPixelCenters ¶
func (c *InterpolationConfig) HalfPixelCenters(halfPixelCenters bool) *InterpolationConfig
HalfPixelCenters is used, if set. Defaults to true.
One cannot select both, HalfPixelCenters(true) and AlignCorner(true).
Default is false.
It returns the InterpolationConfig passed, to allow cascaded method calls.
func (*InterpolationConfig) Nearest ¶
func (c *InterpolationConfig) Nearest() *InterpolationConfig
Nearest configures the interpolation to be bilinear (as opposed to nearest). Default is Bilinear. See also Bilinear.
It returns the InterpolationConfig passed, to allow cascaded method calls.
type LoggerFn ¶
LoggerFn is the function used to log nodes marked for logging. It is called after the Exec method, with the list of messages and corresponding values of the evaluated nodes.
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node represents the result of an operation in the computation graph, and can be used as input to further operations.
Internally, it keeps tracks of all parameters used for the computation: this is later used for auto-differentiation (see Gradient).
It also stores meta-information: see Node.SetLogged, Node.StopGradient.
Notice some complex methods offered in this package may be implemented with several instances of simpler operations and yield several nodes in the graph, that's normal.
Node.String allows for a pretty-printing of node. To see the full graph with all nodes, use Graph.String.
func Acosh ¶ added in v0.28.18
Acosh returns the element-wise inverse hyperbolic cosine of x (for x >= 1):
$$
\operatorname{acosh}(x) = \ln\left(x + \sqrt{x - 1}\sqrt{x + 1}\right)
$$
It is implemented as Log1p((x-1) + sqrt(x-1)sqrt(x+1)) to preserve precision for x close to 1. For x > 1/sqrt(epsilon), where x + sqrt(x-1)sqrt(x+1) would overflow for the largest values, it uses ln(x) + ln 2.
For half-precision types (Float16, BFloat16), intermediate calculations are performed in Float32.
func Add ¶
Add returns the element-wise sum of the two values. Standard broadcasting rules apply (see documentation).
func AddScalar ¶
func AddScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
AddScalar converts scalar to a constant with x's DType and returns `x + scalar` with proper broadcasting.
func ArgMax ¶
ArgMax returns the index of the largest element across the given axis.
The selected axis is reduced, and the output has one fewer axes (rank `x.Rank() - 1`). The output `DType`, if not given, is `dtypes.Int32`.
Ties are resolved by returning the smallest index.
func ArgMin ¶
ArgMin returns the index of the smallest element across the given axis.
The selected axis is reduced, and the output has one fewer axes (rank `x.Rank() - 1`). The output `DType`, if not given, is `dtypes.Int32`.
Ties are resolved by returning the smallest index.
func Asinh ¶ added in v0.28.18
Asinh returns the element-wise inverse hyperbolic sine of x:
$$
\operatorname{asinh}(x) = \operatorname{sign}(x) \ln\left(|x| + \sqrt{x^2 + 1}\right)
$$
It is implemented using Log1p to preserve precision for small |x| and avoid cancellation for negative x. For |x| > 1/sqrt(epsilon), where x² would lose precision or overflow, it uses ln(|x|) + ln 2.
For half-precision types (Float16, BFloat16), intermediate calculations are performed in Float32.
func Atan2 ¶
Atan2 returns element-wise the arc tangent of y/x, using the signs of both arguments to determine the correct quadrant of the result. Standard broadcasting rules apply (see documentation).
func Atanh ¶ added in v0.28.18
Atanh returns the element-wise inverse hyperbolic tangent of x (for x in (-1, 1)):
$$
\operatorname{atanh}(x) = \frac{1}{2}\left(\operatorname{log1p}(x) - \operatorname{log1p}(-x)\right)
$$
For half-precision types (Float16, BFloat16), intermediate calculations are performed in Float32.
func BackendFusedActivation ¶ added in v0.28.11
func BackendFusedActivation(x *Node, cfg compute.ActivationConfig) *Node
BackendFusedActivation applies the configured activation function. Internal: prefer activations.Apply which handles fallback and gradients.
func BackendFusedActivationVJP ¶ added in v0.28.11
func BackendFusedActivationVJP(y, x, dOutput *Node, cfg compute.ActivationConfig) *Node
BackendFusedActivationVJP computes the vector-jacobian product of the configured activation. Internal: this is used for reverse-mode autodiff of FusedActivation.
func BackendFusedAttentionQKVProjection ¶
func BackendFusedAttentionQKVProjection(x, wQKV, biasQ, biasK, biasV *Node, queryDim, keyValueDim int) (query, key, value *Node)
BackendFusedAttentionQKVProjection performs fused Query-Key-Value projection. Internal: prefer attention.QKVProjection which handles fallback and gradients.
func BackendFusedDense ¶
func BackendFusedDense(x, weight, bias *Node, options compute.DenseConfig) *Node
BackendFusedDense performs fused matmul + optional bias + optional activation. Internal: prefer nn.Dense which handles fallback and gradients.
func BackendFusedDenseVJP ¶ added in v0.28.11
func BackendFusedDenseVJP(x, weight, bias, y, dOutput *Node, options compute.DenseConfig) (dx, dWeight, dBias *Node)
BackendFusedDenseVJP computes the vector-jacobian product (gradients) of FusedDense with respect to its inputs (x, weight, and bias). Internal: this is used for reverse-mode autodiff of FusedDense.
func BackendFusedLayerNorm ¶
BackendFusedLayerNorm applies layer normalization. gamma and beta are optional (nil to skip). Internal: prefer nn.LayerNorm which handles fallback and gradients.
func BackendFusedQuantizedDense ¶
func BackendFusedQuantizedDense(x, weights, bias *Node, wq *Quantization, activation compute.ActivationType) *Node
BackendFusedQuantizedDense performs fused dequantization + matmul + optional bias + optional activation. Internal: prefer nn.QuantizedDense which handles fallback and gradients.
func BackendFusedSoftmax ¶
BackendFusedSoftmax computes softmax along the specified axis. Internal: prefer graph.Softmax which handles fallback and gradients.
func BackendGather ¶
func BackendGather(operand *Node, startIndices *Node, indexVectorAxis int, offsetAxes []int, collapsedSliceAxes []int, startIndexMap []int, sliceSizes []int, indicesAreSorted bool) (node *Node)
BackendGather exposes the raw backend Gather operator.
This is internal, and it is exposed only for debugging purposes, please don't rely on it. If it turns out you need some functionality here that is not provided in Gather or GatherSlices, open an issue in GoMLX and we'll figure a betterAPI.
See convoluted and circular description in https://openxla.org/xla/operation_semantics#gather
func BackendQuantizedEmbeddingLookup ¶
func BackendQuantizedEmbeddingLookup(data, indices *Node, tq *Quantization) *Node
BackendQuantizedEmbeddingLookup performs a quantized embedding lookup (row gather) with on-the-fly dequantization. Internal: prefer nn.QuantizedGather which handles fallback and gradients.
func BackendReduceWindow ¶
func BackendReduceWindow(x *Node, reductionType ReduceOpType, windowDimensions, strides, inputDilations, windowDilations []int, paddings [][2]int) *Node
BackendReduceWindow provides direct access to the backend operator.
This is exposed to allow testing, but you probably should avoid using it directly and instead use the pool operations (MaxPool, MinPool, SumPool and MeanPool), which allow almost the same flexibility.
func BackendScatterMax ¶
func BackendScatterMax(operand, indices, updates *Node, indexVectorAxis int, updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int, indicesAreSorted, uniqueIndices bool) *Node
BackendScatterMax exposes the raw backend ScatterMax operator.
This should be internal, and it is exposed only for testing and debugging purposes, please don't rely on it. If it turns out you need some functionality here that is not provided in ScatterMax, open an issue in GoMLX and we'll figure a betterAPI.
Description in https://openxla.org/xla/operation_semantics#scatter
func BackendScatterMin ¶
func BackendScatterMin(operand, indices, updates *Node, indexVectorAxis int, updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int, indicesAreSorted, uniqueIndices bool) *Node
BackendScatterMin exposes the raw backend ScatterMin operator.
This should be internal, and it is exposed only for testing and debugging purposes, please don't rely on it. If it turns out you need some functionality here that is not provided in ScatterMin, open an issue in GoMLX and we'll figure a betterAPI.
Description in https://openxla.org/xla/operation_semantics#scatter
func BackendScatterSum ¶
func BackendScatterSum(operand, indices, updates *Node, indexVectorAxis int, updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int, indicesAreSorted, uniqueIndices bool) *Node
BackendScatterSum exposes the raw backend ScatterSum operator.
This should be internal, and it is exposed only for testing and debugging purposes, please don't rely on it. If it turns out you need some functionality here that is not provided in ScatterSum, open an issue in GoMLX and we'll figure a betterAPI.
Description in https://openxla.org/xla/operation_semantics#scatter
func BitCount ¶
BitCount returns the number of bits that are set to one. Also known as Population Count ("Popcnt") or Hamming Weight.
func Bitcast ¶
Bitcast performs an elementwise bitcast operation from a dtype to another dtype.
The Bitcast doesn't "convert", rather it just reinterprets the bits from operand.DType() to the targetDType.
If the element sizes (in bytes/bits) differ, the last dimension is adjusted:
- Smaller target: a new trailing axis of size (srcBits / dstBits) is appended, so rank is increased by 1.
- Larger target: the last axis must be equal to (dstBits / srcBits), and the resultign rank is decreased by 1 ("squeezed").
E.g:
Bitcast([1]uint32{0xdeadbeef}, dtypes.UInt16) -> [1][2]uint16{{0xbeef, 0xdead}} // Little-endian encoding.
Bitcast([1][2]uint16{{0xbeef, 0xdead}}, dtypes.UInt32) -> [1]uint32{0xdeadbeef}
Dynamic shapes: Bitcasting that collapses or expands a dynamic dimension is currently not supported (requires axis expressions).
func BitwiseAnd ¶
BitwiseAnd returns the element-wise bitwise AND operation.
func BitwiseNot ¶
BitwiseNot returns the element-wise bitwise AND operation.
func BitwiseShiftLeft ¶
BitwiseShiftLeft n bits of integer values. It implicitly preserves the sign bit, if there is no overflow. So BitwiseShiftLeft(-1, 1) = -2.
func BitwiseShiftLeftScalar ¶
func BitwiseShiftLeftScalar[T gotype.NumericNotComplex](x *Node, n T) *Node
BitwiseShiftLeftScalar is an alias to BitwiseShiftLeft, but takes n as a scalar.
func BitwiseShiftRightArithmetic ¶
BitwiseShiftRightArithmetic n bits of integer values, preserving the sign bit. So ShiftRight(-2, 1) = -1. See also BitwiseShiftRightLogical for a version the ignores the sign bit.
func BitwiseShiftRightArithmeticScalar ¶
func BitwiseShiftRightArithmeticScalar[T gotype.NumericNotComplex](x *Node, n T) *Node
BitwiseShiftRightArithmeticScalar is an alias to BitwiseShiftRightArithmetic, but takes n as a scalar. It shifts n bits of integer values, preserving the sign bit. So ShiftRight(-2, 1) = -1.
func BitwiseShiftRightLogical ¶
BitwiseShiftRightLogical n bits of integer values, ignoring the sign bit. See also BitwiseShiftRightArithmetic for a version that preserves the sign bit.
func BitwiseShiftRightLogicalScalar ¶
func BitwiseShiftRightLogicalScalar[T gotype.NumericNotComplex](x *Node, n T) *Node
BitwiseShiftRightLogicalScalar is an alias to BitwiseShiftRightLogical, but takes n as a scalar. It shifts right n bits of integer values, ignoring the sign bit.
func BitwiseXor ¶
BitwiseXor returns the element-wise bitwise XOR operator.
func BottomK ¶
BottomK returns the K smallest elements and their indices along the specified axis.
Parameters:
- x: The input tensor.
- k: The number of bottom elements to retrieve.
- axis: The axis along which to find bottom K (can be negative to count from the end).
Returns:
- values: The K smallest values, sorted in ascending order.
- indices: The indices of the K smallest values in the original tensor (dtype Int32).
The output shapes have the same rank as input, with the specified axis having size K.
Tie-breaking: When multiple elements have equal values, stable sort is used, meaning elements that appear earlier in the original order along the axis are selected first.
Example:
x := Const(g, []float32{3, 1, 4, 1, 5, 9, 2, 6})
values, indices := BottomK(x, 3, 0)
// values = [1, 1, 2]
// indices = [1, 3, 6]
func BroadcastLike ¶ added in v0.28.5
BroadcastLike broadcasts the operand to the shape of the reference node along the specified broadcastAxes. If broadcastAxes is omitted, it defaults to trailing (NumPy-style) axes.
It works seamlessly with both static and dynamic shapes (delegating to DynamicBroadcastLike).
func BroadcastPrefix ¶
BroadcastPrefix adds dimensions to an array by duplicating the data in the array.
The new dimensions dims are inserted on the left, i.e., if broadcast_sizes has values `{a0, ..., aN}` and the operand shape has dimensions {b0, ..., bM} then the shape of the output has dimensions {a0, ..., aN, b0, ..., bM}.
The new dimensions id into copies of the operand, i.e.
BroadcastPrefix creates a new tensor by prepending prefixDims to x, and broadcasting x to the new shape.
Formally:
output[i0, ..., iN, j0, ..., jM] = operand[j0, ..., jM]
It works seamlessly with both static and dynamic shapes.
func BroadcastToDims ¶
BroadcastToDims broadcasts x to the given dimensions. x must have an equal or lower rank than the given dimensions, and if there are more dimensions than x rank, x will be expanded at the end (so new axes will be appended to x). Dimensions of x must either match the corresponding value in dimensions, or they must be 1, in which case they are broadcast.
Dynamic shape rules: If dimensions contains shapes.DynamicDim (-1), it is only allowed at an axis i where x is already dynamic (x.Shape().Dimensions[i] == shapes.DynamicDim), preserving x's dynamic axis name and size. Specifying -1 for an axis where x has static dimension (including 1) or for an appended new axis is not allowed because BroadcastToDims does not carry axis names or reference nodes to infer the size. In such cases, use BroadcastLike, DynamicBroadcastLike, or DynamicBroadcastToDims instead.
See also the equivalent BroadcastToShape.
func BroadcastToShape ¶
BroadcastToShape broadcasts x to the given shape (which can be static or dynamic). x must have an equal or lower rank than shape, and if shape has higher rank, x will be expanded at the end (so new axes will be appended to x). Dimensions of x must either match the corresponding dimension in shape, or they must be 1, in which case they are broadcast.
Dynamic shape rules for target axes:
- Preserved dynamic axis: If operand x at axis i is already dynamic (shapes.DynamicDim), the dynamic size is taken directly from x (DimensionSize(x, i)). The target dynamic axis must have a compatible name (or empty).
- Broadcast 1 -> Dynamic: Broadcasting dimension 1 to a dynamic dimension is not supported by BroadcastToShape, because no reference tensor is available to provide the runtime dynamic size. Use BroadcastLike or DynamicBroadcastLike with a reference node instead, or DynamicBroadcastInDim with explicit DimensionSpec(*Node) values.
- Static dimension > 1 to Dynamic: An exception is raised.
It works as expected if x is a scalar.
Notice that the dtype of shape is ignored, the returned value preserves the dtype of x.
This is equivalent to BroadcastToDims(x, shape.Dimensions...).
func Ceil ¶
Ceil returns the ceil of x, i.e., the smallest integer greater than or equal to x. For integer dtypes, it returns x unchanged.
func Clamp ¶
Clamp returns the element-wise clamping operation.
The values max and min can either be a scalar or have the same shape as x.
func Clip ¶
Clip is a shortcut to `Min(max, Max(x, min))`, which returns the values of x clipped between min and max.
func ClipScalar ¶
ClipScalar is a shortcut to `Min(max, Max(x, min))`, which returns the values of x clipped between min and max. The values min and max are given as scalar values -- the float64 is converted to the `DType` of x.
func Clz ¶
Clz returns element-wise the "count leading zeros" bits of input node x -- for integer values.
func Complex ¶
Complex returns the complex number taking x0 as the real part and x1 as the imaginary part. The real (x0) and imaginary (x1) must have the same dtype, and they must be either `dtypes.Float32` or `dtypes.Float64`. The output will be either `dtypes.Complex64` or `dtypes.Complex128`, depending on x0 and x1 dtypes. The shapes of `real` or `imaginary` must be the same, or one must be a scalar, in which case the value is broadcast to every other value.
func Concatenate ¶
Concatenate results on the given axis. A negative axis will be counted from the end -- so `axis==-1` means the last axis.
If operands are scalars, they will be concatenated to a vector (just use `axis=0`).
func ConsecutiveDifference ¶
ConsecutiveDifference is the inverse of CumSum: it outputs the difference from each number to be previous on the selected axis.
If preserveShape is true, the first element is preserved, and the shape is preserved, in which case we have ConsecutiveDifference(CumSum(x)) == x.
If preserveShape is false, just the differences are returned, and the resulting shape has the selected axis shrunk by 1.
Examples:
ConsecutiveDifference([2, 4, 8], 0, true) = [2, 2, 4] ConsecutiveDifference([2, 4, 8], 0, false) = [2, 4] ConsecutiveDifference([[1, 3, 6], [4, 9, 15]], -1, true) = [[1, 2, 3], [4, 5, 6]] ConsecutiveDifference([[1, 2, 3], [5, 7, 9]], 0, true) = [[1, 2, 3], [4, 5, 6]]
func Const ¶
Const creates constant nodes in the Graph. It can take a tensor as well as multidimensional slices (or scalars).
It uses tensor.FromAnyValue to figure out the shape given a Go scalar/slice/array. If the value is unsupported, it panics.
A tensor.Device (e.g., generated by another computation) will be converted to local first. If you are creating very large constants that don't need to be materialized locally, consider instead storing them as variables in the context, or as a side parameter.
func ConstAs ¶
ConstAs creates a constant of the same DType and on the same Graph as the given base node, and converts X to that dtype.
Example:
ConstAs(batchNode, 5) // If batchNode has dtype Float32 it results in a scalar constant node representing Float32(5).
ConstAs(batchNode, []int{1, 3}) // If batchNode has dtype Float64 it results in a 1D constant node representing [2]Float64{1.0, 3.0}.
func ConstAsDType ¶
ConstAsDType creates a constant of the given DType. It adds the convenience of converting x (slice or scalar) to the appropriate type. E.g.:
Pi := ConstAsDType(g, myDType, math.Pi)
PiAndE := ConstAsDType(g, myDType, []float64{math.Pi, math.E})
func ConstCachedTensor ¶
ConstCachedTensor returns a constant node for the tensor t. If it's the first time the tensor is used in this graph, a new node is created. Otherwise, a previously created node is reused.
The caching of the tensor has the side effect of keeping the tensor alive (and its memory resources) util the Graph itself is garbage collected. If this is a concern, use ConstTensor instead.
TODO:this can be made default (ConstTensor) once weak references land into Go and the issue of keeping the tensor alive is resolved. See discussion in https://github.com/golang/go/issues/67552 and cache with weak references example in https://github.com/golang/go/issues/67552#issuecomment-2200755798
func ConstTensor ¶
ConstTensor returns a newly created constant node for the tensor t.
The value of t is copied into the graph. It's recommended that for very large tensors, even if constants, that they are passed as side inputNodes (or variables, see context package) instead.
See also ConstCachedTensor if you think you'll use the same tensor multiple times in the same graph.
func ConvGeneral ¶
func ConvGeneral(input, kernel *Node, axes ConvolveAxesConfig, strides []int, paddings [][2]int, inputDilations, kernelDilations []int, channelGroupCount, batchGroupCount int) *Node
ConvGeneral provides direct access to the backend implementation of convolutions. Consider using Convolve instead since this is mostly used for testing.
It implements a generic convolution operation with support for:
- Arbitrary number of spatial axes. - Arbitrary transposition of axes. - Strides and padding. - Dilations of the input. - Dilations of the kernel, aka. atrous convolution. - Filter grouping (on the input channels). - Batch grouping.
Some details in https://www.tensorflow.org/xla/operation_semantics#convwithgeneralpadding_convolution. There operand and filter are called lhs and rhs. (XLA documentation is unfortunately poor, much is guess-work). Also useful, https://arxiv.org/pdf/1603.07285v1.pdf.
Note: input is aka. operand; kernel is aka. "filters". The input and output "channels" are also known as "features dimensions".
func ConvertDType ¶
ConvertDType of x to dtype. If x is already of the given dtype, it's a no-op.
func ConvertType ¶
ConvertType is an alias to ConvertDType. Deprecated: use ConvertDType instead.
func Cosh ¶ added in v0.28.18
Cosh returns the element-wise hyperbolic cosine of x:
$$
\cosh(x) = \frac{e^x + e^{-x}}{2}
$$
For large |x| it is computed as exp(|x| - ln 2), which only overflows where cosh(x) itself does (e^x overflows earlier).
For half-precision types (Float16, BFloat16), intermediate calculations are performed in Float32.
func CosineSimilarity ¶
CosineSimilarity calculates the cosine similarity between the lhs and rhs nodes along the given axis. A typical value for axis is -1, it calculates the cosine similarity for the last dimension.
The output will have the same rank, but the axis is contracted to 1, and will hold the similarity.
Notice, this expects both lhs and rhs to have the same shape, it's a "element-wise" cosine similarity of lhs and rhs. See also CrossCosineSimilarity to calculate the cosine similarty "of all elements of lhs x all elements of rhs"
func CrossCosineSimilarity ¶
CrossCosineSimilarity calculates the cosine similarity on the cross of the elements of lhs and rhs.
Let's say lhs has shape [BatchSize, NumLHS, EmbeddingDim) and rhs has shape [BatchSize, NumRHS, EmbeddingDim). The output of CrossCosineSimilarity(lhs, rhs, contractingAxis=-1, crossAxis=1) will have shape [BatchSize, NumLHS, NumRHS] (the cosine similariy of all LHS elements cross all RHS elements).
Notice axes that are not contracting or cross are considered "batch" and preserved in the output.
The rank and the order of the axes of lhs and rhs must match -- so the contracting axis is the same on both.
A typical value for axis is -1, it calculates the cosine similarity for the last dimension.
The output will have the same rank, but the axis is contracted to 1, and will hold the similarity.
See also CosineSimilarity if you want to do element-wise cosine similarity.
func CumSum ¶
func CumSum(x *Node, axis int, options ...*CumSumOptions) *Node
CumSum returns the cumulative sum along the given axis.
Examples:
CumSum([[1, 2, 3], [4, 5, 6]], -1) = [[1, 3, 6], [4, 9, 15]]
CumSum([[1, 2, 3], [4, 5, 6]], 0) = [[1, 2, 3], [5, 7, 9]]
CumSum([1, 2, 3], 0, &CumSumOptions{Exclusive: true}) = [0, 1, 3]
CumSum([1, 2, 3], 0, &CumSumOptions{Reverse: true}) = [6, 5, 3]
CumSum([1, 2, 3], 0, &CumSumOptions{Exclusive: true, Reverse: true}) = [5, 3, 0]
func Diagonal ¶
Diagonal returns a diagonal boolean square matrix of shape `[dim, dim]`.
This can be combined with `Where` to select values of any arbitrary other matrix.
func DiagonalWithValue ¶
DiagonalWithValue returns a diagonal matrix of shape `[dim, dim]` with scalar in the diagonal and zero elsewhere. Set scalar to `ScalarOne()` and you get an identity matrix.
func DimensionSize ¶ added in v0.28.5
DimensionSize returns a scalar *Node representing the dimension size of the given axis. The returned node has DType graph.DynamicDimDType() (typically Int64, or backend-dependent). If the dimension is static, it returns a constant Scalar node. If the dimension is dynamic, it queries the backend for the dynamic dimension size.
func Div ¶
Div returns the element-wise division of the two values. Standard broadcasting rules apply (see documentation).
func DivScalar ¶
func DivScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
DivScalar converts scalar to a constant with x's DType and returns `x / scalar` with proper broadcasting.
For float DType's, DivScalar instead uses MulScalar(x, 1/scalar).
func DotGeneral ¶
func DotGeneral( lhs *Node, lhsContractingAxes, lhsBatchAxes []int, rhs *Node, rhsContractingAxes, rhsBatchAxes []int, ) *Node
DotGeneral takes as input lhs (left-hand-side) and rhs (right-hand-side) specifications for a general vector product -- a generalized "Einsum". Each axis can be:
- Just aligned (batch axes), so the output has the same axes as the inputs. The dimensions must match in lhs and rhs.
- Crossed (default), in which case the output is the combination (concatenation) of the dimensions.
- Contracted (contracting axes), where the output does multiply the values and reduce sum those dimensions.
It follows that the resulting dimension number starts with the batch dimension, then the 'lhs' non-contracting/non-batch dimension, and finally the 'rhs' non-contracting/non-batch dimension. It provides the basic means of implementing Einsum.
It's an alias to Dot(lhs, rhs).General(lhsContractingAxes, lhsBatchAxes, rhsContractingAxes, rhsBatchAxes). Use Dot() instead if you need further configuration.
func DotProduct ¶
DotProduct performs a generic linear dot-product operation, extended to handle matrices (rank-2 lhs and/or rhs), similar to numpy.dot.
The exact semantics of this operation depend on the ranks of the operands:
- DotProduct([n], [n]) -> scalar
- DotProduct([m, k], [k]) -> vector [m]
- DotProduct([k], [k, n]) -> vector [n]
- DotProduct([m, k], [k, n]) -> matrix [m x n]
This is an alias for Dot(lhs, rhs).Product(). Use Dot() instead if you need further configuration.
func DynamicBroadcastInDim ¶ added in v0.28.5
func DynamicBroadcastInDim(operand *Node, broadcastAxes []int, axisSpecs ...DimensionSpec) *Node
DynamicBroadcastInDim broadcasts the operand to an output with target dimensions specified by axisSpecs.
broadcastAxes maps operand axes to the corresponding output axes (len(broadcastAxes) == operand.Shape().Rank()), where the i-th axis of operand is mapped to broadcastAxes[i]-th dimension of the output. broadcastAxes must also be strictly increasing: this operation cannot be used to transpose axes.
If both the operand and all axisSpecs are completely static, this falls back to static BroadcastInDim instead.
func DynamicBroadcastLike ¶ added in v0.28.5
DynamicBroadcastLike broadcasts the operand to the shape of the reference node along the specified broadcastAxes. If broadcastAxes is omitted, it defaults to trailing (NumPy-style) axes.
It works seamlessly for both static and dynamic shapes (extracting dynamic sizes automatically).
func DynamicBroadcastToDims ¶ added in v0.28.5
func DynamicBroadcastToDims(operand *Node, axisSpecs ...DimensionSpec) *Node
DynamicBroadcastToDims broadcasts operand to the target dimensions using prefix axis alignment (appending new axes at the end), matching BroadcastToDims.
func DynamicBroadcastToShape ¶ added in v0.28.5
DynamicBroadcastToShape broadcasts x to the given shape (which can be static or dynamic). x must have an equal or lower rank than shape, and if shape has more dimensions than x rank, x will be expanded at the end (so new axes will be appended to x). Dimensions of x must either match the corresponding dimension in shape, or they must be 1, in which case they are broadcast.
Dynamic shape rules for target axes:
- Preserved dynamic axis: If operand x at axis i is already dynamic (shapes.DynamicDim), the dynamic size is taken directly from x (DynamicDimensionSize(x, i)). The target dynamic axis must have a compatible name (or empty).
- Broadcast 1 -> Dynamic: Broadcasting dimension 1 to a dynamic dimension is not supported by DynamicBroadcastToShape, because no reference tensor is available to provide the runtime dynamic size. Use BroadcastLike or DynamicBroadcastLike with a reference node instead, or DynamicBroadcastInDim with explicit DimensionSpec(*Node) values.
- Static dimension > 1 to Dynamic: An exception is raised.
If neither shape nor x is dynamic, it delegates to BroadcastToShape. Conversely, BroadcastToShape delegates to DynamicBroadcastToShape if shape or x is dynamic.
func DynamicIota ¶ added in v0.28.5
DynamicIota creates a tensor with the given dynamic dimensions and dtype, filled with increasing numbers (starting from 0) along the specified iotaAxis.
If all dimension specs are static, it delegates to static Iota.
func DynamicPad ¶ added in v0.28.5
func DynamicPad(x, fillValue *Node, axesConfig ...DynamicPadAxisSpec) *Node
DynamicPad injects padding on the start, end, or interior of the given operand using static and/or dynamic scalar padding amounts.
If all padding specifications and operand shape are static, it delegates to static Pad.
func DynamicReshape ¶ added in v0.28.2
func DynamicReshape(operand *Node, axisSpecs ...DimensionSpec) *Node
DynamicReshape reshapes the operand according to dimension specifications for each axis. Because the shape is not known in graph building time, it is only supported in backends that support dynamic axes (shapes), see backend.Capabilities().
If both the operand and all of the axis specs have static dimensions, this uses the static Reshape instead.
Each axis can have its dimension specified in one of:
- StaticDim(dim): the dimension is a constant known at graph building time.
- DynamicDim(dimNode): the dimension is given by the scalar node dimNode (anonymous dynamic axis).
- NamedDynamicDim(name, dimNode): the dimension is given by the scalar node dimNode and named.
- InferredDim(): the dimension is automatically inferred from the total size of the operand.
- NamedInferredDim(name): the dimension is automatically inferred and named.
At most one axis can be inferred (`InferredDim()` or `NamedInferredDim(name)`).
Example: Flattening a dynamically shaped input with rank > 2, while preserving the dynamic "batch_size" axis:
batchSizeNode := DynamicDimensionSize(inputs, 0)
batchSizeSpec := NamedDynamicDim("batch_size", batchSizeNode)
flatInputs := DynamicReshape(inputs, batchSizeSpec, NamedInferredDim("features"))
func DynamicReshapeLike ¶ added in v0.28.2
DynamicReshapeLike reshapes the operand to the same shape (and axis names) as the reference node. The DType of reference is ignored; the returned node will retain operand's DType. It works seamlessly for both static and dynamic shapes.
func DynamicShape ¶
DynamicShape returns the shape of the operand as a dynamic value. This is only supported by backends that support dynamic shapes (see Capabilities.DynamicAxes).
func DynamicSlice ¶
DynamicSlice extracts a slice from the operand at the startIndices position and the given sliceSizes.
- operand: tensor from where to take the slice. - startIndices: scalar tensors, one per axis of operand: len(startIndices) == operand.Rank(). - sliceSizes: static values and fixed to keep the shape of the output static.
The startIndices are adjusted as follows:
adjustedStartIndices[i] = clamp(0, StartIndices[i], operand.Dimensions[i] - sliceSizes[i])
See description in https://openxla.org/xla/operation_semantics#dynamicslice
func DynamicUpdateSlice ¶
DynamicUpdateSlice updates the operand with the values given in update, at the position given by startIndices.
- operand: original value that to be updated. - update: values to "paste" on top of operand, at position startIndices. - startIndices: scalar tensors, one per axis of operand: len(startIndices) == operand.Rank(). - sliceSizes: static values and fixed to keep the shape of the output static.
It returns a value with the same shape as the operand, with the values updated.
The startIndices are adjusted as follows:
adjustedStartIndices[i] = clamp(0, StartIndices[i], operand.Dimensions[i] - update.Dimensions[i])
func Einsum ¶
Einsum evaluates the "Einstein summation" various types of products (inner/outer/batched) between 2 tensors, on arbitrary dimensions. This version uses a textual description on how to manipulate the axes. See EinsumAxes for a version where the axes are given numerically.
This is inspired on numpy Einsum, a description of which can be seen in https://stackoverflow.com/questions/26089893/understanding-numpys-einsum/33641428#33641428.
The equation string describes what to do with each dimension, for each operand, separated by ",", and the format of the result after the "->" describes what is to be made for each dimension.
Examples:
* `Einsum("ij,jk->ik", matrixA, matrixB)` performs the usual matrix multiplication. * `Einsum("bij,bjk->bik", batchedMatrixA, batchedMatrixB)` performs a batched matrix multiplication. * `Einsum("i,i->", vectorA, vectorB)` performs a dot product. * `Einsum("i,j->ij", vectorA, vectorB)` performs an outer (cross) product between two vectors.
It also works for higher dimension tensors. Dimensions missing on the output (after "->") are reduce-summed.
More examples in TensorFlow documentation: https://www.tensorflow.org/api_docs/python/tf/einsum
Notice though that this Einsum is only defined for operations between 2 operands:
- `lhs`: left-hand-side operand. - `rhs`: right-hand-side operand.
Important note: the order of the operands can have a dramatic impact on the speed of the multiplications. consider trying both sides.
This is an alias for Dot(lhs, rhs).Einsum(equation). Use Dot() instead if you need further configuration.
func EinsumAxes ¶
EinsumAxes evaluates the "Einstein summation" various types of products (inner/outer/batched) between 2 tensors, on arbitrary dimensions. Similar to Einsum, but it uses the explicit numeric axis, as opposed to a textual description.
There are two operands: `lhs` (left-hand-side) and `rhs` (right-hand-side). The default for every axis is to do a cross-product, and the resulting tensor will have the concatenated shape (`lhs` dimensions first then `rhs` dimensions).
One can specify contractionAxes, pairs of axes (each pair with one index in the lhs and rhs operands) to be contracted: these dimensions will multiplied and summed one at a time. That's what happens in the usual "dot product."
One can also specify batchAxes, pairs of axes (each pair with one index in the lhs and rhs operands) to be considered as independently, as a batch dimension. These dimensions will show up in the same position as the `lhs`.
Examples:
- `EinsumAxes(matrixA, matrixB, [][2]int{{1, 0}}, nil)` performs the usual matrix multiplication, where we contract axis 1 of `matrixA` with axis 0 of `matrixB`.
- `EinsumAxes(batchedMatrixA, batchedMatrixB, [][2]int{{2, 1}}, [][2]int{{0, 0}})` is similar, but we use axis 0 of both inputNodes as a batch, and following 2 axes as a matrix multiplication.
- `EinsumAxes(vectorA, vectorB, nil, nil)` performs an outer (cross) product -- no contractions, no batch.
- `EinsumAxes(vectorA, vectorB, [][2]int{{0, 0}}, nil)` performs a dot product and returns a scalar.
Important note: the order of the operands can have a dramatic impact on the speed of the multiplications. Consider trying both sides.
This is an alias for Dot(lhs, rhs).EinsumAxes(contractingAxes, batchAxes). Use Dot() instead if you need further configuration.
func Equal ¶
Equal performs element-wise equality check, returns boolean results with the same dimensions as input.
func EqualTotalOrder ¶
EqualTotalOrder returns the element-wise operation. Standard broadcasting rules apply (see documentation). The "TotalOrder" version of the operation enforces `-NaN < -Inf < -Finite < -0 < +0 < +Finite < +Inf < +NaN`.
func ExpandAndBroadcast ¶
ExpandAndBroadcast combines ExpandAxes and broadcast of axes of `x`, the returned shape will be newDimensions. Only newly expanded axes can be broadcast.
newDimensions should have a rank larger than the rank of x, and the new axes in newDimensions should be listed in expandedAxes. In other words: `x.Rank() + len(expandedAxes) == len(newDimensions)`.
expandedAxes refer to the axes in newDimensions that are expanded and going to be broadcast. The reminder dimensions in newDimensions much match the corresponding in x.
It works seamlessly with both static and dynamic shapes.
Example:
x = Const(g, []int32{10, 20})
ExpandAndBroadcast(x, []int{2, 2}, []int{0}) // -> [][]int32{{10, 20}, {10, 20}}
ExpandAndBroadcast(x, []int{2, 2}, []int{1}) // -> [][]int32{{10, 10}, {20, 20}}
func ExpandAxes ¶
ExpandAxes expands x creating new axes at the positions given by newAxes -- the positions are given at the target shape.
The list newAxes represent the positions in the returned shape. If newAxes[ii] < 0, then they are counted from the end of the new shape — -1 represents the last axis in the new shape.
There should be no repeated values in newAxes -- since they represent the positions in the returned shape, it wouldn't make sense.
It works seamlessly with both static and dynamic shapes.
See also InsertAxes, where the new axes are given as positions in the target shape.
func ExpandDims
deprecated
func ExpandLeftToRank ¶
ExpandLeftToRank prepend axes of dimension 1 to x, until it reaches rank `newRank`.
It works seamlessly with both static and dynamic shapes.
func FFT ¶
FFT computes a forward 1D fast-fourier transformation of the operand, which is expected to be complex. The FFT is computed on the last dimension, in case `operand.Rank() > 1`.
If no lengths are specified, the resulting tensor (Node) has the same shapes as the operand and has the values on the frequency domain calculated at the last axis.
Optionally, one can provide the FFT lengths: the default being the last dimension, over which the FFT is calculated. Note: gradients are not defined for different FFT lengths yet.
Use InverseFFT to reverse the result.
func FillScalar ¶
FillScalar creates a Node with a value with the given shape, filled with the given value. It's implemented indirectly using other nodes.
func Floor ¶
Floor returns the floor of x, i.e., the largest integer less than or equal to x. For integer dtypes, it returns x unchanged.
func Gather ¶
Gather values in params from the pointers in indices. The outputs are slices of params selected by indices, stitched together.
Let's assume params has shapes [i_1, ..., i_N, s_1, ..., s_S], where:
- `i_1, ..., i_N` are the N "indexed axes", that is, the axes that are indexed by indices.
- `s_1, ..., s_S` are the S dimensions of the slices that are going to be "gathered" (copied over).
And let's assume indices has shapes [o_1,...,o_O, N], where:
- `o_1, ..., o_O` are "batch dimensions" of the slices from `params` to gather, that will be included in the output. E.g.: let's say O=1, and o_1=3, that means there will be 3 slices to gather.
- Last dimension `N`: this is the number of indices in `params` to point to. `N` is the number of dimensions indexed `i_1, ..., i_N` in `params` above.
The output will have shapes [o_1,...,o_O, s_1, ... s_S], where:
- `o_1, ..., o_O` come from indices, and are enumerations of the slices from params to gather.
- `s_1, ..., s_S` are the slice sizes copied from params.
indicesAreSorted can be set if you know the indices in start are sorted, in some backends this allows for optimizations. If not set it default to false.
For example:
params := [][]float32{{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}
indices := [][]int{{1}, {0}}
Gather(params, indices) would return {{3, 4, 5}, {0, 1, 2}}
In the case above params shapes is interpreted as [i_1=3, s_1=3], and indices shapes is [o_1=2, N=1]. The output shapes is [o_1=2, s_1=3].
func GatherSlices ¶
func GatherSlices(input *Node, slicedAxes []int, start *Node, sizes []int, indicesAreSorted bool) (gathered *Node)
GatherSlices from inputNodes. Each axis listed in slicedAxes have corresponding start position and size for each slice indexed by `start` (a graph Node, can be dynamically generated in the graph) and `sizes`, which will define the output final shapes, and must be statically given.
Axes in slicedAxes can be given as negative numbers, which are taken from the the end of the input rank -- that is axis -1 means the last axis in the input. Axes not given in slicedAxes (and in `start` and `sizes`) are taken in full length.
Axes in slicedAxes must be given sorted in increasing order.
The output has a rank equal to the prefixing rank of `start` (== `start.Rank()-1`) plus the rank of `input`. And the shapes will depend on the sizes of the slices.
- TODO: Add an option to support batch axes, present in both the input and in the start indices. This will need to automatically concatenate the batch index in the start Node as a iota of each batch example, and add the size 1 slice. This can be done manually today.
indicesAreSorted can be set if you know the indices in start are sorted, in some backends this allows for optimizations.
Example:
x := IotaFull(g, shapes.Make(dtypes.Float64, 3, 10, 10)) // 300 in total.
start := Const(g, [][]int32{{0, 3}, {1, 2}}) // 2 slices
sizes := []int{1, 3}
slices := GatherSlices(x, []int{1,2}, start, sizes, true) // Axis=0 is taken in full.
slices.AssertDims(2, 3, 1, 2) // 2 slices, Axis=0 taken in full (3), and each slice of dimensions (1, 2).
// Result would be [][][][]int32{{{0, 1, 2, 3, 4}}, {{30, 31, 32, 33, 34}}, {{40, 41, 42, 43, 44}}}
func Gradient ¶
Gradient creates new nodes for the gradients of the output with respect to each node in gradientNodes. The output must be a scalar -- otherwise this would be called Jacobian. TODO: Define a Jacobian.
func GreaterOrEqual ¶
GreaterOrEqual performs element-wise comparison, returns boolean results with the same dimensions as input.
func GreaterOrEqualTotalOrder ¶
GreaterOrEqualTotalOrder returns the element-wise operation. Standard broadcasting rules apply (see documentation). The "TotalOrder" version of the operation enforces `-NaN < -Inf < -Finite < -0 < +0 < +Finite < +Inf < +NaN`.
func GreaterThan ¶
GreaterThan performs element-wise comparison, returns boolean results with the same dimensions as input.
func GreaterThanTotalOrder ¶
GreaterThanTotalOrder returns the element-wise operation. Standard broadcasting rules apply (see documentation). The "TotalOrder" version of the operation enforces `-NaN < -Inf < -Finite < -0 < +0 < +Finite < +Inf < +NaN`.
func GrowLeft ¶
GrowLeft will grow the dimension of the given axis by concatenating n elements to the left (start). Those elements are filled with value (converted to the corresponding dtype).
func GrowRight ¶
GrowRight will grow the dimension of the given axis by concatenating n elements to the left (start). Those elements are filled with fillValue (converted to the corresponding dtype).
func Identity ¶
Identity returns an Op whose output is the same as its input. It's a no-op that can serve as a place-holder.
func IdentityWithCustomGradient ¶
IdentityWithCustomGradient returns x unchanged, but sets a custom gradient function to be applied when doing the reverse autograd (gradient) calculation.
The `gradientFn` will be called during auto-grad and will be passed `x` and `v`, the "adjoint", which represents the gradient of the loss (typically, but of whatever we are calculating the gradient of) with respect to `x`, and we should return the updated `v`, that is, the customized gradient with respect to `x`.
func If ¶
If executes one of two branches based on a boolean predicate.
The branch closures should be created with NewClosure and can capture values from the parent scope.
Both branches must:
- Take no parameters
- Return the same number of values with matching shapes
Example:
pred := IsPositive(x)
trueBranch := NewClosure(g, func(g *graph.Graph) []*Node {
return []*Node{x} // Return x if x > 0
})
falseBranch := NewClosure(g, func(g *graph.Graph) []*Node {
return []*Node{Neg(x)} // Return -x if x <= 0
})
result := If(pred, trueBranch, falseBranch)
Parameters:
- pred: A scalar boolean value determining which branch to execute.
- trueBranch: Closure executed when pred is true.
- falseBranch: Closure executed when pred is false.
Returns the outputs of the executed branch.
func Imag ¶
Imag returns the imaginary part of a complex number. It returns 0 if the x is a float number.
func IndicesForShape ¶
IndicesForShape enumerates a list of indices for all elements of the given shapes. It will always return a node with shapes [shapes.Size(), shapes.Rank()]. E.g: if shapes=[3, 2], it returns `[[0 0] [0 1] [1 0] [1 1] [2 0] [2 1]]`.
func Infinity ¶
Infinity returns the positive/negative (depending on the value of sign, which must be 1 or -1) for the given dtype. For integer dtypes, it returns the highest/lowest values.
func InsertAxes ¶
InsertAxes expands x creating new axes just before the axes given -- beforeAxes points to positions on the original tensor x, and they can be repeated, in case one wants to insert more than one new axis in the given position.
If beforeAxes[ii] < 0, then they are counted from the end — -1 represents a new axis after the end of the original shape.
The new axes will be of dimension 1 (so the total size of and contents of the tensor remains the same), and the rank is increased by `len(axes)`.
It works seamlessly with both static and dynamic shapes.
See also ExpandAxes, where the new axes are given as positions in the target shape.
func InternalBatchNormForInference ¶
func InternalBatchNormForInference( operand *Node, scale *Node, offset *Node, mean *Node, variance *Node, epsilon float32, axis int, ) (node *Node)
InternalBatchNormForInference is a wrapper to the backend function. Don't use this directly, instead use layers.BatchNormalization.
func InternalBatchNormForTraining ¶
func InternalBatchNormForTraining( operand *Node, scale *Node, offset *Node, epsilon float32, axis int, ) (normalized, batchMean, batchVariance *Node)
InternalBatchNormForTraining is a wrapper to the backend function. Don't use this directly, instead use layers.BatchNormalization.
func InternalBatchNormGradient ¶
func InternalBatchNormGradient( operand *Node, scale *Node, mean *Node, variance *Node, gradOutput *Node, epsilon float32, axis int, ) (gradOperand, gradScale, gradOffset *Node)
InternalBatchNormGradient is a wrapper to the backend function. Don't use this directly, instead use layers.BatchNormalization.
func InternalFusedOpCaller ¶
func InternalFusedOpCaller(fused, decomposed func() *Node, useDecomposedAlternateVJP bool) (output *Node, opFused bool)
InternalFusedOpCaller attempts to call fused, and if it panics with compute.ErrNotImplemented, falls back to the decomposed version. Any other panic is re-thrown — this prevents real bugs in fused op implementations from being silently swallowed.
If useDecomposedAlternateVJP is set, the decomposed version is stored as the vjpAlternateOutputs on the returned node, so that reverse-mode autodiff can compute gradients through the decomposed graph without hand-written VJPs. This should be set to true if there is no corresponding fused VJP.
The returned opFused indicates whether the fused operation was taken (true) or fell back to decomposed (false).
Internal: this is used by higher-level wrappers (graph.Softmax, nn.Dense, nn.LayerNorm) that pair a fused backend call with a decomposed fallback.
Note: If "GOMLX_FUSION" (see FusionEnv constant) is disabled (set to "0", "false", etc.) the fused version is never used. The default is enabled though.
func InternalFusedOpCallerMulti ¶
func InternalFusedOpCallerMulti(fused, decomposed func() []*Node, useDecomposedAlternateVJP bool) (outputs []*Node, opFused bool)
InternalFusedOpCallerMulti is the multi-output counterpart of InternalFusedOpCaller. It handles fused ops that return multiple outputs (e.g. FusedAttentionQKVProjection returning q, k, v).
Like InternalFusedOpCaller, the decomposed version is built first so it has lower node indices than the fused nodes. When the fused call succeeds and useDecomposedAlternateVJP is set, the decomposed outputs are stored as vjpAlternateOutputs on each individual output node (which are split nodes under the hood) for reverse-mode autodiff. This should be set to true if there is no corresponding fused VJP.
The returned opFused indicates whether the fused operation was taken (true) or fell back to decomposed (false).
func InverseFFT ¶
InverseFFT computes an inverse fast-fourier transformation of the operand, which is expected to be complex. The InverseFFT is computed on the last dimension, in case `operand.Rank() > 1`.
Optionally, one can provide the FFT lengths: the default being the last dimension, over which the FFT is calculated. Note: gradients are not defined for different FFT lengths yet.
The resulting tensor (Node) has the same shapes as the input and has the values on the frequency domain.
func InverseRealFFT ¶
InverseRealFFT computes the inverse of a forward 1D fast-fourier transformation. The inverse FFT is computed on the last dimension, in case `operand.Rank() > 1`.
The resulting tensor (Node) has the shapes equal to the input, except the last dimension (where the FFT is computed) which is reversed back to the original, `(dim-1)*2`, where `dim` is the operand's last axis dimension.
Optionally, one can provide the FFT lengths. The default being the last dimension of the original RealFFT (so 2*(x.Dims(-1)-1)). Note: gradients are not defined for different FFT lengths yet.
func Iota ¶
Iota creates a constant of the given shape with increasing numbers (starting from 0) on the given axis. So Iota([2,2], 1) returns [[0 1][0 1]], while Iota([2,2], 0) returns [[0 0][1 1]].
See also IotaFull.
func IotaFull ¶
IotaFull creates a constant of the given shape with increasing numbers for all values. So `IotaFull([2,2])` returns `[[0 1][2 3]]`.
func IotaLike ¶ added in v0.28.5
IotaLike creates a tensor with the same shape as reference, filled with increasing numbers (starting from 0) along iotaAxis.
It works seamlessly with both static and dynamic shapes (extracting dynamic sizes automatically).
func IsFinite ¶
IsFinite tests whether each element of operand is finite, i.e., if it is not positive nor negative infinity, and it is not NaN. It returns the same shape as the input, but with boolean values where each element is true if and only if the corresponding input element is finite.
func IsNaN ¶
IsNaN tests whether each element of operand is NaN, i.e., if it is not a finite number.
func IsNegative ¶
IsNegative returns a boolean indicating whether x < 0.
func IsNonNegative ¶
IsNonNegative returns a boolean indicating whether x >= 0.
func IsNonPositive ¶
IsNonPositive returns a boolean indicating whether x <= 0.
func IsPositive ¶
IsPositive returns a boolean indicating whether x > 0.
func IsZero ¶
IsZero returns a Bool tensor that is true where x is zero, and false otherwise. A shortcut to Equal(x, ScalarZero(x.Graph(), x.DType())).
func L1Norm ¶
L1Norm returns the L1 norm (same as Manhattan length) of the last axis of x. The returned value has the same rank, but the last axes will have dimension 1.
If no axes are given, it returns a scalar. Otherwise, the returned value has the same rank as `x`, but the reduce axes will have dimension 1.
func L2Norm ¶
L2Norm returns the L2 norm (same as Euclidean length) over the given axes of x (defaults to all), given by Sqrt(\Sum{x_i^2}).
If no axes are given, it returns a scalar. Otherwise, the returned value has the same rank as `x`, but the reduce axes will have dimension 1.
func L2NormSquare ¶
L2NormSquare returns the L2 norm square (same as square of the Euclidean length) over the given axes of x (defaults to all). Same as `\Sum_{reduceAxes}{x_i^2}`.
If no axes are given, it returns a scalar. Otherwise, the returned value has the same rank as `x`, but the reduce axes will have dimension 1.
func L2Normalize ¶
L2Normalize returns `x/L2Norm(x)` on the given reduce axes, making the last axis a unit-length vector.
It will return `inf` for values of x that are near zero-length.
For elements that have L2Norm zero, it returns 0 and 1s for the gradients, so no NaNs are generated.
See L2NormalizeWithEpsilon for a version that adds an epsilon to the denominator to avoid that.
func L2NormalizeWithEpsilon ¶
L2NormalizeWithEpsilon returns `x/(L2Norm(x)+epsilon)` on the last axis, making the last axis a unit-length vector.
func LessOrEqual ¶
LessOrEqual performs element-wise comparison, returns boolean results with the same dimensions as input.
func LessOrEqualTotalOrder ¶
LessOrEqualTotalOrder returns the element-wise operation. Standard broadcasting rules apply (see documentation). The "TotalOrder" version of the operation enforces `-NaN < -Inf < -Finite < -0 < +0 < +Finite < +Inf < +NaN`.
func LessThan ¶
LessThan performs element-wise comparison, returns boolean results with the same dimensions as input.
func LessThanTotalOrder ¶
LessThanTotalOrder returns the element-wise operation. Standard broadcasting rules apply (see documentation). The "TotalOrder" version of the operation enforces `-NaN < -Inf < -Finite < -0 < +0 < +Finite < +Inf < +NaN`.
func LogAddExp ¶
LogAddExp Logarithm of the sum of exponentiations of the inputs. Calculates log(exp(x1) + exp(x2)). This function is useful in statistics where the calculated probabilities of events may be so small as to exceed the range of normal floating point numbers. In such cases the logarithm of the calculated probability is stored. This function allows adding probabilities stored in such a fashion.
func LogSoftmax ¶
LogSoftmax computes the logarithm of the Softmax function, which rescales elements to the range $[-\infty, 0)$.
$$
\mathrm{log\_softmax}(x)_i = \log \left( \frac{\exp(x_i)}{\sum_j \exp(x_j)}
\right)
$$
The axes define over which axes the LogSoftmax should be computed. If missing it is assumed to be -1.
If any input values are "+inf", the result will be all "NaN": this reflects the fact that "inf / inf" is not well-defined in the context of floating-point math.
func LogicalAll ¶
LogicalAll returns true if all values of x (converted to boolean) evaluate to true. It's a "ReduceLogicalAnd" equivalent.
If reduceAxes is empty, it will reduce over all dimensions.
func LogicalAnd ¶
LogicalAnd returns the element-wise logical AND operation.
func LogicalAny ¶
LogicalAny returns true if any values of x (converted to boolean) evaluate to true. It's a "ReduceLogicalOr" equivalent.
If reduceAxes is empty, it will reduce over all dimensions.
func LogicalNot ¶
LogicalNot returns the Op that represents the output of the corresponding operation.
func LogicalXor ¶
LogicalXor returns the element-wise logical XOR operator.
func Logistic ¶
Logistic returns the element-wise expression 1/(1+exp(-x)). Also known as the Sigmoid function.
func LowerTriangular ¶
LowerTriangular returns a lower-triangular boolean square matrix of shape `[dim, dim]`.
This can be combined with `Where` to select values of any arbitrary other matrix.
func MaskedLogSoftmax ¶
MaskedLogSoftmax computes the logarithm of the MaskedSoftmax function, which rescales elements to the range $[-\infty, 0)$.
It takes a mask that is true on the values to be considered, and false for the values not to be considered. If mask is nil, it behaves like LogSoftmax.
See LogSoftmax for details.
func MaskedReduceAllMax ¶
MaskedReduceAllMax reduces all dimensions to a scalar by taking the max.
It ignores values for which the corresponding mask is false. The shapes of `mask and x must be the same.
func MaskedReduceAllMean ¶
MaskedReduceAllMean reduces all dimensions to a scalar by taking the mean. It ignores entries where mask is false.
func MaskedReduceAllMin ¶
MaskedReduceAllMin reduces all dimensions to a scalar by taking the min.
It ignores values for which the corresponding mask is false. The shapes of `mask and x must be the same. If mask is nil, it behaves like ReduceAllMin.
func MaskedReduceAllSum ¶
MaskedReduceAllSum reduces all dimensions to a scalar by summing.
It ignores values for which the corresponding mask is false. The `mask` and `x` values must have the same shape.
func MaskedReduceAndKeep ¶
func MaskedReduceAndKeep(operand, mask *Node, reduceFn func(operand, mask *Node, reduceAxes ...int) *Node, reduceAxes ...int) *Node
MaskedReduceAndKeep applies the given masked reduction function but regenerates the reduced dimensions with size 1.
func MaskedReduceMax ¶
MaskedReduceMax reduces by taking the max of `x` elements over the selected axes. If reduceAxes is nil, reduce over all dimensions to a scalar.
It ignores values for which the corresponding mask is false. The shapes of `mask and x must be the same. If mask is nil, it behaves like ReduceMax.
func MaskedReduceMean ¶
MaskedReduceMean reduces by taking the mean over the elements of the selected axes.
The reduced axes of `x` are removed in the output -- so the rank is reduced.
It first applies a mask to x, converting masked values to the neutral value of the operation (0). For reduction dimensions that are completely masked, it returns 0. If mask is nil, it behaves like ReduceMean.
func MaskedReduceMin ¶
MaskedReduceMin reduces by taking the min of `x` elements over the selected axes. If reduceAxes is nil, reduce over all dimensions to a scalar.
It ignores values for which the corresponding mask is false. The shapes of `mask and x must be the same. If mask is nil, it behaves like ReduceMin.
func MaskedReduceSum ¶
MaskedReduceSum reduces by summing the `x` elements over the selected axes. If `reduceAxes` is nil, reduce over all dimensions to a scalar.
The reduced axes of `x` are removed in the output -- so the rank is reduced.
It ignores values for which the corresponding mask is false. The `mask` and `x` values must have the same shape. If mask is nil, it behaves like ReduceSum.
func MaskedSoftmax ¶
MaskedSoftmax computes softmax activations. It's the equivalent to ```
Exp(logits) / InsertAxes(ReduceSum(Exp(logits), -1), -1)
```
But implemented in a numerical stable way.
It takes a mask that is true on the values to be considered, and false for the values not to be considered.
The list axes defines which axes is it supposed to run the softmax over (the axes that will be summed over). If no axes are given, it is assumed to be [-1], meaning, the last axes.
It ignores values for which the corresponding mask is false, and will return 0 for those fields. mask and logits must have the same shape.
func MatMul ¶
MatMul is the `numpy.matmul` equivalent, for those used to that.
It is similar to Dot but extends to allow for more batch dimensions in lhs or rhs operand, and does broadcasting (of all but the last 2 axes) according to the numpy broadcasting rules.
It's popular hence it is here, but full of edge cases, consider using Dot().General() (or DotGeneral()) instead.
This is an alias for Dot(lhs, rhs).MatMul(). Use Dot() instead if you need further configuration.
func MaxScalar ¶
func MaxScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
MaxScalar converts scalar to a constant with x's DType and returns element-wise `Max(x, scalar)`.
func MinScalar ¶
func MinScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
MinScalar converts scalar to a constant with x's DType and returns element-wise `Min(x, scalar)`.
func MirroredLog1p ¶
MirroredLog1p is similar to Log1p, but it is mirrored to negative numbers. It return Log(Abs(x)+1)*Sign(x).
func Mod ¶
Mod adds to the graph the module (remainder) operation on the two input nodes x and y. It's an alias to Rem. Standard broadcasting rules apply (see documentation).
func ModScalar ¶
func ModScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
ModScalar converts scalar to a constant with x's DType and returns `x % scalar` with proper broadcasting.
func Mul ¶
Mul returns the element-wise multiplication of the two values. Standard broadcasting rules apply (see documentation).
func MulScalar ¶
func MulScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
MulScalar converts scalar to a constant with x's DType and returns `x * scalar` with proper broadcasting.
func NegativeIndicator ¶
NegativeIndicator returns 1 where x < 0, 0 otherwise. E.g: NegativeIndicator({1.0, 0.0001, 0, -0.2, -3.0}) -> [0, 0, 0, 1, 1], with the same shape/dtype as x.
func NonNegativeIndicator ¶
NonNegativeIndicator returns 1 where x >= 0, 0 otherwise. See also PositiveIndicator. E.g: NonNegativeIndicator ({1.0, 0.0001, 0, -0.2, -3.0}) -> [1, 1, 1, 0, 0], with the same shape/dtype as x.
func NonPositiveIndicator ¶
NonPositiveIndicator returns 1 where x <= 0, 0 otherwise. See also NegativeIndicator. E.g: NonPositiveIndicator ({1.0, 0.0001, 0, -0.2, -3.0}) -> [0, 0, 1, 1, 1], with the same shape/dtype as x.
func NormalizeIndices ¶
NormalizeIndices converts Python-style negative indices to positive indices for gathering along a single axis of data.
Negative indices are converted by adding the dimension size of the specified axis. For example, if data has dimension 5 on the specified axis and an index is -1, it becomes 4 (i.e., 5 + (-1) = 4).
This is useful for compatibility with ONNX and Python where -1 refers to the last element, -2 to the second-to-last, etc.
Parameters:
- data: The tensor from which gathering will be done (used to get dimension size)
- indices: The values to normalize according to data dimensions, must be integer
- axis: The axis of data along which gathering will happen (supports negative axis)
Returns normalized indices with the same shape and dtype as input indices.
Notes:
- This function only converts negative indices to positive by adding the axis dimension. It does NOT clamp values to valid bounds. Indices that remain out-of-bounds after normalization (e.g., -6 for axis size 5 yields -1) will be handled by the underlying Gather operation according to XLA/StableHLO semantics, which clamps to valid range [0, dim-1].
- For ONNX compatibility, valid input indices should be in range [-dim, dim-1].
- Unsigned integer indices are technically supported but will never be modified since they cannot be negative. Use signed integer types (int32, int64) for indices that may contain negative values.
func NotEqual ¶
NotEqual performs element-wise inequality check, returns boolean results with the same dimensions as input.
func NotEqualTotalOrder ¶
NotEqualTotalOrder returns the element-wise operation. Standard broadcasting rules apply (see documentation). The "TotalOrder" version of the operation enforces `-NaN < -Inf < -Finite < -0 < +0 < +Finite < +Inf < +NaN`.
func OneHot ¶
OneHot converts an integer numbers representing indices to it's "one-hot" representation, that is an expanded tensor with the indices position set to 1, and the other positions set to 0. The returned tensor has one extra dimension at the end. For example:
OneHot([]int64{1, 0, 3}, 4, types.Float32) // -> `[][]float32{{0, 1, 0, 0}, {1, 0, 0, 0}, {0, 0, 0, 1}}`
func Ones ¶
Ones creates a computation with the same shape as the input, but with the value 1. It's implemented indirectly using other nodes.
It also works for booleans, so it can create a tensor filled with true values.
func OptimizationBarrier ¶
OptimizationBarrier creates an optimization barrier for a single node. It returns a new Node that is mathematically equal to the input operand, but prevents the compiler from optimizing across the barrier.
func OptimizationBarriers ¶
OptimizationBarriers creates an optimization barrier for multiple nodes. It returns a slice of Nodes that are mathematically equal to the input operands, but prevents the compiler from optimizing across the barrier.
func Pad ¶
Pad injects padding on the start, end, or interior (in between each element) of the given operand. There must be at most `operand.Rank()` axesConfig values. Missing PadAxis are assumed to be zeros, that is, no padding for those axes.
Dynamic shapes: Padding on a dynamic axis is currently not supported if the padding is non-zero, because the resulting size cannot be represented symbolically yet (requires axis expressions).
func Parameter ¶
Parameter registers an input parameter for a computation Graph (e.g: a feature used as input).
When created they get a handle (a plain index) but they can also be accessed It can be used in two different ways: as a Node when building the Graph, so when defining a function that uses the parameter, or as the key in the map of the inputNodes when executing the computation Graph (see Backend.RunWithMap).
func PositiveIndicator ¶
PositiveIndicator returns 1 where x > 0, 0 otherwise. E.g: PositiveIndicator({1.0, 0.0001, 0, -0.2, -3.0}) -> [1, 1, 0, 0, 0], with the same shape/dtype as x.
func PowScalar ¶
func PowScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
PowScalar converts scalar to a constant with x's DType and returns `Pow(x, scalar)` (or `x ** scalar`) with proper broadcasting.
func RNGStateForGraph ¶
RNGStateForGraph creates a random number generator (RNG) state initialized using the OS's cryptographically secure random number generator, if available. It returns a constant in the graph with the value, that can be used for random operations.
A typical use case would be to use like:
rngState := RNGStateForGraph(g)
func RNGStateFromSeedForGraph ¶
RNGStateFromSeedForGraph creates a random number generator (RNG) state initialized using the given seed. It returns a constant in the graph with the value, that can be used for random operations.
A typical use case would be to use like:
rngState := RNGStateFromSeedForGraph(g, 12345)
func RNGStateSplit ¶
RNGStateSplit splits the current state into 2 different states that can be used separately and will lead to different random numbers.
func RandomIntN ¶
func RandomIntN[IntT interface{ *Node | constraints.Integer }](
rngState *Node, N IntT, shape shapes.Shape) (newRNGState, values *Node)
RandomIntN generates random numbers uniformly from 0 to N-1. It only works for integer types, see RandomUniform for float or complex data types. N can be given as a Node, or a static scalar integer value.
Example:
rngState := Const(g, RNGStateFromSeed(42)) rngState, D10 := RandomIntN(rngState, 10, shapes.Make(dtypes.Int32))
It uses and updates the random number generator (RNG) state in `rngState`. See RNGStateFromSeed or RNGState to generate a random state tensor (that can be fed to the computation graph).
Alternatively, if you don't want to worry about carrying around the rngState, use the model.Store.RandomIntN version, which stores the rngState as a variable.
func RandomNormal ¶
RandomNormal generates random numbers from a normal distribution, with mean 0.0 and standard deviation 1.0. It generates values with the given shapes, each value pseudo-randomly generated.
If you need a different mean and standard deviation, just do something like the example below, where `mean` and `stddev` are the desired mean and standard deviation:
rngState := Const(g, RNGStateFromSeed(42)) rngState, values := RandomNormal(rngState, shapes.Make(dtypes.Float32, 3, 2)) numbers = AddScalar(MulScalar(values, stddev), mean)
It uses the Box-Muller algorithm (see https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform). It has some numeric limitations, but works well for most purposes.
It will signal an error if the dtype is not float. See also RandomIntN for random integers.
It uses and updates the random number generator (RNG) state in `rngState`. See RNGStateFromSeed or RNGState to generate a random state tensor (that can be fed to the computation graph).
Alternatively, if you don't want to worry about carrying around the rngState, use the model.Store.RandomNormal version, which stores the rngState as a variable.
func RandomUniform ¶
RandomUniform generates random uniform values from 0.0 to 1.0 (half-open `[0.0, 1.0)`, so 1.0 is never returned) for float numbers in the given shapes.
It will signal an error if the dtype is not float -- see RandomIntN for random integers.
For complex numbers, both the real and the imaginary part are independently sampled from `[0.0, 1.0)`.
It uses and updates the random number generator (RNG) state in `rngState`. See RNGStateFromSeed or RNGState to generate a random state tensor (that can be fed to the computation graph).
Alternatively, if you don't want to worry about carrying around the rngState, use the model.Store.RandomUniform version, which stores the rngState as a variable.
Example:
rngState := Const(g, RNGStateFromSeed(42)) rngState, values := RandomUniform(rngState, shapes.Make(dtypes.Float32, 3, 2))
func RealFFT ¶
RealFFT computes a forward 1D fast-fourier transformation on a real (float) input. The FFT is computed on the last dimension, in case `operand.Rank() > 1`.
The resulting tensor (Node) has the shapes equal to the input, except the last dimension (where the FFT is computed) which has dimension `dim/2 + 1`, where `dim` is the operand's last axis dimension.
Note that because of the last dimension change in RealFFT, this cannot be perfectly reversed if `operand.Shape().Dimensions[-1]` is odd. Preferably, use with an even last axis dimension.
Optionally, one can provide the FFT lengths: the default being the last dimension, over which the FFT is calculated. Note: gradients are not defined for different FFT lengths yet.
func Reciprocal ¶
Reciprocal returns (1/x) element-wise, the multiplicative inverse.
func ReduceAllMax ¶
ReduceAllMax reduces all dimensions to a scalar by taking the max.
func ReduceAllMean ¶
ReduceAllMean reduces all dimensions to a scalar by taking the mean.
func ReduceAllMin ¶
ReduceAllMin reduces all dimensions to a scalar by taking the min.
func ReduceAllMultiply ¶
ReduceAllMultiply reduces all dimensions to a scalar by multiplying.
func ReduceAllSum ¶
ReduceAllSum reduces all dimensions to a scalar by summing.
func ReduceAndKeep ¶
func ReduceAndKeep(operand *Node, reduceFn func(operand *Node, reduceAxes ...int) *Node, reduceAxes ...int) *Node
ReduceAndKeep applies the given reduction function but regenerate the reduced dimensions with size 1. If len(reduceAxes) is 0 (no axes given) it's assumed it is being reduced on all axes.
func ReduceBitwiseAnd ¶
ReduceBitwiseAnd returns the bitwise AND of the values across the given axes. Only defined for integer values. No gradients are defined.
If reduceAxes is empty, it will reduce over all dimensions.
func ReduceBitwiseOr ¶
ReduceBitwiseOr returns the bitwise OR of the values across the given axes. Only defined for integer values. No gradients are defined.
If reduceAxes is empty, it will reduce over all dimensions.
func ReduceBitwiseXor ¶
ReduceBitwiseXor returns the bitwise XOR of the values across the given axes. Only defined for integer values. No gradients are defined.
If reduceAxes is empty, it will reduce over all dimensions.
func ReduceLogicalAnd ¶
ReduceLogicalAnd returns true if all values of x evaluate to true across the given axes. No gradients are defined.
If reduceAxes is empty, it will reduce over all dimensions.
func ReduceLogicalOr ¶
ReduceLogicalOr returns true if any values of x evaluate to true across the given axes. No gradients are defined.
If reduceAxes is empty, it will reduce over all dimensions.
func ReduceLogicalXor ¶
ReduceLogicalXor returns the xor of the values across the given axes. No gradients are defined.
If reduceAxes is empty, it will reduce over all dimensions.
func ReduceMax ¶
ReduceMax reduces by taking the max over the elements of the selected axes. If reduceAxes is nil, reduce over all dimensions to a scalar.
The reduced axes of `x` are removed in the output -- so the rank is reduced. See ReduceAndKeep for a version to preserve the reduced axes.
func ReduceMean ¶
ReduceMean reduces by taking the mean over the elements of the selected axes.
The reduced axes of `x` are removed in the output -- so the rank is reduced. See ReduceAndKeep for a version to preserve the reduced axes.
func ReduceMin ¶
ReduceMin reduces by taking the min over the elements of the selected axes. If reduceAxes is nil, reduce over all dimensions to a scalar.
The reduced axes of `x` are removed in the output -- so the rank is reduced. See ReduceAndKeep for a version to preserve the reduced axes.
func ReduceMultiply ¶
ReduceMultiply reduces by summing over the elements of the selected axes. If reduceAxes is nil, reduce over all dimensions to a scalar.
The reduced axes of `x` are removed in the output -- so the rank is reduced. See ReduceAndKeep for a version to preserve the reduced axes.
func ReduceSkewness ¶
ReduceSkewness calculates the skewness (the 3rd standardized moment of a distribution) across the given axes.
If no axes is given, it assumes it should reduce all axes and returns a scalar.
func ReduceSum ¶
ReduceSum reduces by summing over X elements over the selected axes. If reduceAxes is nil, reduce over all dimensions to a scalar.
The reduced axes of `x` are removed in the output -- so the rank is reduced. See ReduceAndKeep for a version to preserve the reduced axes.
func ReduceVariance ¶
ReduceVariance calculates the variance across the given axes.
If no axes is given, it assumes it should reduce all axes and returns a scalar.
func Rem ¶
Rem returns the remainder operation, also known as modulo (or Mod for short). Notice despite the name XLA implements Mod not IEEE754 Remainder operation.
func Reshape ¶
Reshape x to the given dimensions. Total size cannot change. One dimension can be left as -1, in which case it will be set to match the size, if possible.
If x or target is dynamic, it delegates to DynamicReshape.
func ReshapeLike ¶ added in v0.28.5
ReshapeLike reshapes operand to have the same shape as reference.
It works seamlessly with both static and dynamic shapes (delegating to DynamicReshapeLike).
func ReshapeWithShape ¶
ReshapeWithShape reshapes x to the dimensions given by shape. Total size cannot change, neither the DType is allowed to change. Conceptually, this is a limited form of "shape casting."
func Reverse ¶
Reverse returns x with the values for the given dimensions reversed, that is, the value indexed at `i` will be swapped with the value at indexed `(dimension_size - 1 - i)`. The shape remains the same.
func Round ¶
Round returns the Op that represents the output of the corresponding operation. This operation rounds to the nearest even.
func Scalar ¶
Scalar returns a constant scalar with the given value.
The value is first converted to float64 to serve as index to a cache and later converted to the requested dtype. This may lose bits of precision to very large integers. If you are worried with any of these conversions, use Const instead.
func ScalarOne ¶
ScalarOne returns a scalar constant 1 for the given DType.
It also work for booleans (so it's also a "ScalarTrue").
func ScalarZero ¶
ScalarZero returns a scalar constant 0 for the given DType.
It also work for booleans (so it's also a "ScalarFalse").
func Scatter ¶
Scatter sums up the slices in updates into a new tensor of the given shapes, at the locations pointed by indices. It does the opposite of Gather.
In the simplest form, [indices] is shaped `[num_updates, 1]`, [updates] is shaped `[num_updates, update_size]` and shapes is of the form `[output_size, update_size]`. The indices values should be in between 0 and `output_size-1`.
Args:
- indices: the positions where to set the new values.
- updates: the values that are going to be set.
- shape: output shape, it must have the same dtype as updates.
- sorted: the indices must be in order. If set to true for some backends it is faster, but if the indices are not sorted, results may be unstable. If in doubt, leave it false.
- unique: Whether the indices are unique. If set to true for some backends it is faster, but if the indices are not unique, results may be unstable. If in doubt, leave it false.
func ScatterAdd
deprecated
func ScatterMax ¶
ScatterMax updates the max value of operand, from the values in updates pointed by indices.
The operand provides the initial values for the operation, and typically will be initialized with -inf. See Infinity and BroadcastToDims to create an arbitrarily shaped node filled with infinity.
Args: - [sorted]: the indices must be in order. In some cases it is faster, but if indices are not in order results may be unstable. - unique: the indices must be unique. In some cases it is faster, but if indices are not unique results may be unstable.
func ScatterMin ¶
ScatterMin updates the min value of operand, from the values in updates pointed by indices.
The operand provides the initial values for the operation, and typically will be initialized with +inf. See Infinity and BroadcastToDims to create an arbitrarily shaped node filled with infinity.
Args: - [sorted]: the indices must be in order. In some cases it is faster, but if indices are not in order results may be unstable. - unique: the indices must be unique. In some cases it is faster, but if indices are not unique results may be unstable.
func ScatterSum ¶
ScatterSum adds up the slices in updates into the given operand tensor, at the locations pointed by indices. It does the opposite of Gather.
Args:
- operand: input values to which new values will be added.
- indices: the positions where add the new values.
- updates: the values to add.
- sorted: the indices must be in order. If set to true for some backends it is faster, but if the indices are not sorted, results may be unstable. If in doubt, leave it false.
- unique: Whether the indices are unique. If set to true for some backends it is faster, but if the indices are not unique, results may be unstable. If in doubt, leave it false.
func ScatterUpdate ¶
ScatterUpdate replaces values in the operand with values from updates, at the locations pointed by indices.
Only implemented for `unique=true` for now: it doesn't handle the case with overlapping updates.
Args:
- operand: input values that are going to be modified.
- indices: the positions where to set the new values.
- updates: the values that are going to be set.
- sorted: the indices must be in order. If set to true for some backends it is faster, but if the indices are not sorted, results may be unstable. If in doubt, leave it false.
- unique: Only **true** is implemented for now, if set to **false** it will panic. Whether the indices are unique. If set to true for some backends it is faster, but if the indices are not unique, results may be unstable. If in doubt, leave it false.
func SchedulingBarrier ¶
SchedulingBarrier introduces a scheduling barrier. Returned value is identity to the operand, but it is guaranteed to depend on all the dependencies.
func ShapedLowerTriangular ¶
ShapedLowerTriangular returns a triangular boolean matrix (rows x column) (not necessarily rows == columns), where the lower triangular are set to true (including diagonal), and the upper triangular is set to zero.
The k value shifts the triangular up or down: k < 0 sets true values below the diagonal. Conversely, k > 0 extends the true values above the diagonal.
Examples:
ShapedLowerTriangular(g, 3, 3, k=0) => [][]bool{{true, false, false}, {true, true, false}, {true, true, true}}
ShapedLowerTriangular(g, 3, 3, k=-1) => [][]bool{{false, false, false}, {true, false, false}, {true, true, false}}
ShapedLowerTriangular(g, 2, 3, k=1) => [][]bool{{true, true, false}, {true, true, true}}
func ShardedParameter ¶
func ShardedParameter(g *Graph, name string, shape shapes.Shape, sharding *distributed.ShardingSpec) (node *Node)
ShardedParameter works like Parameter but takes as an optional (it can be nil) argument the sharding specification of how this input is going to be fed across devices. This is used for distributed computations -- see Graph.SetAutoSharding.
func Shift ¶
func Shift(x *Node, axis int, shiftDir ShiftDirection, n int) *Node
Shift a given [axis] of [x] by [n] positions ([n] is a static value). The [shiftDir] defines the direction: left towards lower values or right towards higher values. The spaces left open keep the edge value. Example:
Shift([0, 1, 2, 3], axis=-1, ShiftDirLeft, n=2)
Will return `[2, 3, 3, 3]`.
func ShiftLeft ¶
ShiftLeft the last axis of [x] by [n] positions ([n] is a static value) and fill the new value with [fill]. The value of [fill] is converted to [x]'s dtypes.DType. For boolean dtype, use 1.0 or 0.0.
See ShiftWithScalar and ShiftWithValue for a more generic shift function.
func ShiftRight ¶
ShiftRight the last axis of [x] by [n] positions ([n] is a static value) and fill the new value with [fill]. The value of [fill] is converted to [x]'s dtypes.DType. For boolean dtype, use 1.0 or 0.0.
See ShiftWithScalar and ShiftWithValue for a more generic shift function.
func ShiftWithScalar ¶
ShiftWithScalar a given [axis] of [x] by [n] positions ([n] is a static value) and fill the new value with [fill], a **static** scalar value. The [shiftDir] defines the direction: left towards lower values or right towards higher values. The value of [fill] is converted to [x]'s dtypes.DType. For boolean dtype, use 1.0 or 0.0.
func ShiftWithValue ¶
ShiftWithValue a given [axis] of [x] by [n] positions ([n] is a static value) and fill the new value with a dynamic (graph) [value]. The [shiftDir] defines the direction: left towards lower values or right towards higher values. The filling [value] must be "broadcast-able" (see [BroadcastToDim]) to the space it's going to fill with the shift -- a scalar can always be broadcast.
func Sigmoid ¶
Sigmoid returns the expression $1/(1+exp(-x)). It is an alias to the Logistic function.
func Sign ¶
Sign returns element-wise +1, +/-0 or -1 depending on the sign of x. It returns NaN if the input is NaN. The gradient of Sign is assumed to be zero everywhere.
func SignPlusOrMinus ¶
SignPlusOrMinus return +1 or -1 whether x >= 0 or x < 0. It's similar to Sign, but where 0s are considered positive.
func Sinh ¶ added in v0.28.18
Sinh returns the element-wise hyperbolic sine of x:
$$
\sinh(x) = \frac{e^x - e^{-x}}{2}
$$
It is computed on |x| as (t + t/(t+1))/2 with t = Expm1(|x|), which avoids the cancellation of e^x - e^{-x} for |x| close to 0, and as exp(|x| - ln 2) for large |x|, which only overflows where sinh(x) itself does (e^x overflows earlier).
For half-precision types (Float16, BFloat16), intermediate calculations are performed in Float32.
func Skewness ¶
Skewness calculates the skewness (the 3rd standardized moment of a distribution) across the given axes. It's just an alias to ReduceSkewness.
It's a form of reduction function, and the returned rank will be x.Rank() - len(axes).
If no axes is given, it assumes it should reduce all axes and returns a scalar.
func Slice ¶
func Slice(x *Node, axesSpec ...SliceAxisSpec) *Node
Slice take slices of the operand.
Each axis can have a range defined as (start, end) pairs. Any axis for which a range is not specified is assumed to be taken in full. Consider using the shortcut AxisRange to define the ranges.
Examples:
- For `x = {10, 20, 30, 40}`:
- `Slice(x) = {10, 20, 30, 40}` // SliceAxisSpec not given is taken in full.
- `Slice(x, AxisRange()) = {10, 20, 30, 40}` // Default for AxisRange is the full range.
- `Slice(x, AxisRange(1,-1)) = {20, 30}` // Negative values are taken from the end of the axis dimension.
- `Slice(x, AxisRangeFromStart(-2)) = {10, 20}` // Negative values are taken from the end of the axis dimension.
- `Slice(x, AxisRangeToEnd(2)) = {30, 40}` // Negative values are taken from the end of the axis dimension.
- `Slice(x, AxisElem(2)) = {3}` // Take only one element of an axis.
- For `x = {{1, 2, 3}, {4, 5, 6}}`:
- `Slice(x, AxisRange(), AxisElem(0)) = {{1}, {4}}` // First axis taken in full, second axis only the first element.
- `Slice(x, AxisElem(1)) = {{4, 5, 6}}` // Missing second SliceAxisSpec, assumed to be taken in full.
If Slice is called with `x.shape = [5, 5, 5, 5]` and `axesRanges=AxisElem(1), AxisRange(), AxisRange(2), AxisRange(0,2)` would return a node shaped `[1, 5, 3, 2]`.
It also supports "spacers" (like "*" in paths), that fill the unknown axes. Example: let's say we want to get just the last example of a batch, and just the first element of the embedding. Assume x is shaped `[batch_size, ..., embedding_size]` and we want something like `x[-1, ..., 0:1]`.
sample := Slice(x, AxisElem(-1), AxisRange().Spacer(), AxisElem(0))
It also works with strides, use the SliceAxisSpec.Stride() method to conveniently set it.
Example:
- For `x = {1, 2, 3, 4}`:
- `Slice(x, AxisRange().Stride(2)) = {1, 3}` // The whole range, but with a stride of 2.
- For `x = {{1, 2, 3}, {4, 5, 6}}`:
- `Slice(x, AxisRange().Stride(2), AxisRange(-1)) = {{3}}` // Take every 2nd row (so only the 1st here), the last column.
func SliceAxis ¶
func SliceAxis(x *Node, axis int, axisSpec SliceAxisSpec) *Node
SliceAxis is similar to Slice, but take a slice of one axis only, and preserve all others.
Example:
x.Shape() == [5, 4, 3] SliceAxis(x, 1, AxisElem(1)) -> shape [5, 1 (sliced axis), 3]
func Softmax ¶
Softmax computes softmax activations. It's the equivalent to
Exp(logits) / ReduceAndKeep(Exp(logits), ReduceSum, axes...)
But implemented in a numerical stable way.
The list axes defines which axes is it supposed to run the softmax over (the axes that will be summed over).
If no axes are given, it is assumed to be [-1], meaning, the last axes.
If the backend supports fused softmax (single axis), it will use the optimized native implementation instead of decomposing into primitives.
func Softplus ¶
Softplus activation function $[\log\(1+\exp(x))$ Equivalent of Log1P(Exp(x)) But implemented in a numerical stable way.
func Sort ¶
Sort sorts a single tensor along the specified axis.
This is a simplified version of SortFunc that doesn't require a comparator closure. For sorting multiple tensors together or using a custom comparator, use SortFunc.
Parameters:
- input: The tensor to sort.
- axis: The axis along which to sort (can be negative to count from the end).
- ascending: If true, sorts in ascending order; otherwise descending.
Returns the sorted tensor.
Example:
x := Const(g, []float32{5, 2, 8, 1, 9, 3})
sorted := Sort(x, 0, true) // Returns [1, 2, 3, 5, 8, 9]
func SortFunc ¶
SortFunc sorts one or more tensors along the specified axis using a comparator closure.
The comparator closure should be created with NewClosure and must:
- Take 2*N scalar parameters (where N is the number of input tensors), in the order (lhs_0, rhs_0, lhs_1, rhs_1, ..., lhs_N-1, rhs_N-1) where lhs_i and rhs_i are scalar values from input tensor i being compared.
- Return a single boolean scalar: true if lhs should come before rhs.
For a standard ascending sort on a single tensor with dtype Float32:
comparator := NewClosure(g, func(g *graph.Graph) []*Node {
lhs := Parameter(g, "lhs", shapes.Make(dtypes.Float32))
rhs := Parameter(g, "rhs", shapes.Make(dtypes.Float32))
return []*Node{LessThan(lhs, rhs)}
})
sorted := SortFunc(comparator, 0, false, x)
For sorting two tensors together (e.g., values and indices):
comparator := NewClosure(g, func(g *graph.Graph) []*Node {
lhsVal := Parameter(g, "lhs_val", shapes.Make(dtypes.Float32))
rhsVal := Parameter(g, "rhs_val", shapes.Make(dtypes.Float32))
lhsIdx := Parameter(g, "lhs_idx", shapes.Make(dtypes.Int32))
rhsIdx := Parameter(g, "rhs_idx", shapes.Make(dtypes.Int32))
_ = lhsIdx // unused but required
_ = rhsIdx // unused but required
return []*Node{LessThan(lhsVal, rhsVal)} // Compare by values only
})
sortedResults := SortFunc(comparator, 0, false, values, indices)
Parameters:
- comparator: A closure that compares two sets of scalar values.
- axis: The axis along which to sort (can be negative to count from the end).
- isStable: If true, maintains the relative order of equal elements.
- inputs: One or more tensors to sort. All must have the same dimensions (dtypes can differ).
Returns the sorted tensors in the same order as inputs.
func Split ¶
Split splits x on the given axis in numSplits equally shaped values. x.Shape().Dimensions[axis] must be divisible by numSplits.
Example:
x := IotaFull(g, shapes.Make(dtypes.Int32, 2, 3)) // Creates [[0 1 2][3 4 5]] splits := Split(x, 1, 3) // Split along axis 1 into 3 parts // Now splits[0] is [[0][3]], splits[1] is [[1][4]], splits[2] is [[2][5]]
func Squeeze ¶
Squeeze removes `axes` of dimension 1. If `axes` is not set, all axes of dimension 1 are removed. Otherwise, only the provided `axes` are removed. If any of the given `axes` is not of dimension 1, an error is raised in the Graph and an invalid node is returned.
If all dimensions are reduced, it returns a scalar.
It works seamlessly with both static and dynamic shapes.
func Stack ¶
Stack puts together many values (*Node) with the exact same shape by creating a new axis and concatenating them.
Axis is relative to returning shape.
The returned value increased the rank by 1: output.Rank() = 1+operands[i].Rank()
func StopGradient ¶
StopGradient creates an identity node (see Identity), through which gradients don't back-propagate.
No new XLA outputOps is created, so there are no costs to the computation execution speed.
func Sub ¶
Sub returns the element-wise subtraction of the two values. Standard broadcasting rules apply (see documentation).
func SubScalar ¶
func SubScalar[N gotype.NumericNotComplex](x *Node, scalar N) *Node
SubScalar converts scalar to a constant with x's DType and returns `x - scalar` with proper broadcasting.
func TakeLowerTriangular ¶
TakeLowerTriangular takes the lower triangular of the last 2 dimensions of x (x.Rank() must be >= 2), and set the other values to 0. The returned shape is the same as x.
The k value shifts the triangular up or down: k < 0 takes values further below the diagonal. Conversely, k > 0 extends the true values above the diagonal.
It uses ShapedLowerTriangular to calculate the mask.
Examples:
input = AddScalar(IotaFull(g, shapes.Make(dtypes.Float64, 2, 2)), 1)
TakeLowerTriangular(input, 0) => [][]float64{{1, 0}, {3, 4}}
input = AddScalar(IotaFull(g, shapes.Make(dtypes.Float32, 1, 2, 3, 4)), 1)
TakeLowerTriangular(input, 0)
// -> [][][][]float32{{{{1, 0, 0, 0}, {5, 6, 0, 0}, {9, 10, 11, 0}}, {{13, 0, 0, 0}, {17, 18, 0, 0}, {21, 22, 23, 0}}}}
TakeLowerTriangular(input, -1)
// -> [][][][]float32{{{{0, 0, 0, 0}, {5, 0, 0, 0}, {9, 10, 0, 0}}, {{0, 0, 0, 0}, {17, 0, 0, 0}, {21, 22, 0, 0}}}}
TakeLowerTriangular(input, 1)
// -> [][][][]float32{{{{1, 2, 0, 0}, {5, 6, 7, 0}, {9, 10, 11, 12}}, {{13, 14, 0, 0}, {17, 18, 19, 0}, {21, 22, 23, 24}}}}
func TakeUpperTriangular ¶
TakeUpperTriangular takes the upper triangular of the last 2 dimensions of x (x.Rank() must be >= 2), and set the other values to 0. The returned shape is the same as x.
The k value shifts the triangular up or down: k < 0 takes values further below the diagonal. Conversely, k > 0 extends the true values above the diagonal.
It uses ShapedLowerTriangular to calculate the mask.
Examples:
input = AddScalar(IotaFull(g, shapes.Make(dtypes.Float64, 2, 2)), 1)
TakeUpperTriangular(input, 0) => [][]float64{{1, 2}, {0, 4}}
input = AddScalar(IotaFull(g, shapes.Make(dtypes.Float32, 1, 2, 3, 4)), 1)
TakeUpperTriangular(input, 0)
// -> [][][][]float32{{{{1, 2, 3, 4}, {0, 6, 7, 8}, {0, 0, 11, 12}}, {{13, 14, 15, 16}, {0, 18, 19, 20}, {0, 0, 23, 24}}}}
TakeUpperTriangular(input, -1)
// -> [][][][]float32{{{{1, 2, 3, 4}, {5, 6, 7, 8}, {0, 10, 11, 12}}, {{13, 14, 15, 16}, {17, 18, 19, 20}, {0, 22, 23, 24}}}}
TakeUpperTriangular(input, 1)
// -> [][][][]float32{{{{0, 2, 3, 4}, {0, 0, 7, 8}, {0, 0, 0, 12}}, {{0, 14, 15, 16}, {0, 0, 19, 20}, {0, 0, 0, 24}}}}
func TopK ¶
TopK returns the top K largest elements and their indices along the specified axis.
Parameters:
- x: The input tensor.
- k: The number of top elements to retrieve.
- axis: The axis along which to find top K (can be negative to count from the end).
Returns:
- values: The top K largest values, sorted in descending order.
- indices: The indices of the top K values in the original tensor (dtype Int32).
The output shapes have the same rank as input, with the specified axis having size K.
Tie-breaking: When multiple elements have equal values, stable sort is used, meaning elements that appear earlier in the original order along the axis are selected first.
Example:
x := Const(g, []float32{3, 1, 4, 1, 5, 9, 2, 6})
values, indices := TopK(x, 3, 0)
// values = [9, 6, 5]
// indices = [5, 7, 4]
func TopKMask ¶
TopKMask returns a boolean mask of the top-k elements along the specified axis. This is more efficient than TopK when you only need to know which elements are in the top-k.
Parameters:
- x: Input tensor
- k: Number of top elements to mark
- axis: The axis along which to find top K (can be negative to count from the end)
Returns:
- mask: Boolean mask with same shape as x, true for top-k elements
Tie-breaking: When multiple elements have equal values, stable sort is used, meaning elements that appear earlier in the original order along the axis are selected first. This ensures exactly k elements are marked as true in the mask.
Example:
x := Const(g, []float32{3, 1, 4, 1, 5, 9, 2, 6})
mask := TopKMask(x, 3, 0)
// mask = [false, false, false, false, true, true, false, true]
func TransposeAllAxes ¶
TransposeAllAxes allows one to transpose any or all dimensions. It permutes the operand axes with the given permutation, so ∀ i, 0 ≤ i < rank ⇒ input_dimensions[permutations[i]] = output_dimensions[i].
func TransposeAllDims
deprecated
func UpperTriangular ¶
UpperTriangular returns an upper-triangular boolean square matrix of shape `[dim, dim]`.
This can be combined with `Where` to select values of any arbitrary other matrix.
func Variance ¶
Variance calculates the variance across the given axes. It's just an alias to ReduceVariance.
It's a form of reduction function, and the returned rank will be x.Rank() - len(axes).
If no axes is given, it assumes it should reduce all axes and returns a scalar.
func Where ¶
Where takes element-wise values from onTrue or onFalse depending on the value of condition (expected to be boolean).
It supports implicit broadcasting:
- Any operand can be a scalar, in which case it is implicitly broadcast to the output shape.
- Non-scalar operands must have matching ranks, and for each dimension they must either be equal or one of them must be 1 (in which case it is broadcast to the larger dimension).
- If condition has lower rank than onTrue/onFalse, trailing axes of size 1 are inserted so it has the same rank.
func While ¶
While executes a loop while a condition is true.
The condition and body closures should be created with NewClosure.
The condition closure must:
- Take N parameters (matching the number and shapes of initialState)
- Return a single boolean scalar
The body closure must:
- Take N parameters (matching the number and shapes of initialState)
- Return N values with shapes matching initialState
Example for summing numbers 1 to 10:
// State: [counter, sum]
cond := NewClosure(g, func(g *graph.Graph) []*Node {
counter := Parameter(g, "counter", shapes.Make(dtypes.Int32))
_ = Parameter(g, "sum", shapes.Make(dtypes.Int32))
return []*Node{LessThan(counter, Const(g, int32(11)))}
})
body := NewClosure(g, func(g *graph.Graph) []*Node {
counter := Parameter(g, "counter", shapes.Make(dtypes.Int32))
sum := Parameter(g, "sum", shapes.Make(dtypes.Int32))
return []*Node{
Add(counter, Const(g, int32(1))),
Add(sum, counter),
}
})
results := While(cond, body, Const(g, int32(1)), Const(g, int32(0)))
// results[0] = 11, results[1] = 55
Parameters:
- cond: Condition closure returning boolean scalar.
- body: Body closure returning new state.
- initialState: Initial values for the loop state.
Returns the final state values.
func Zeros ¶
Zeros creates a computation with the same shape as the input, but with the value 0. It's implemented indirectly using other nodes.
It also works for booleans, so it can create a tensor filled with false values.
func (*Node) AssertDims ¶
AssertDims checks whether the shape has the given dimensions and rank. A value of -1 in dimensions means it can take any value and is not checked.
If the shape is not what was expected, it panics with an error message.
This often serves as documentation for the code when implementing some complex computational graphs. This allows the reader of the code to corroborate what is the expected shape of a node.
Example:
batch_size := inputNodes[0].Shape().Dimensions[0] … layer := Concatenate(allEmbeddings, -1) layer.AssertDims(batchSize, -1) // 2D tensor, with batch size as the leading dimension.
func (*Node) AssertRank ¶
AssertRank checks whether the shape has the given rank.
If the rank is not what was expected, it panics with an error message.
This often serves as documentation for the code when implementing some complex computational graphs. This allows the reader of the code to corroborate what is the expected shape of a node.
It can be used in a similar fashion as AssertDims.
func (*Node) AssertScalar ¶
func (n *Node) AssertScalar()
AssertScalar checks whether the shape is a scalar.
If the rank is not what was expected, it panics with an error message.
It can be used in a similar fashion as AssertDims.
func (*Node) AssertValid ¶
func (n *Node) AssertValid()
AssertValid panics if `n` is nil, or if its graph is invalid.
func (*Node) Checkpoint ¶
Checkpoint wraps the current node in an optimization barrier, marks it as a memory firewall boundary, and kicks off the contagious rematerialization flag.
This should be called at the input boundaries of your checkpointed blocks (e.g., at the start of a transformer layer). Downstream nodes will inherit the volatile state and be recomputed during the backward pass to save memory.
Example usage for a heavy compute block:
// 1. Create a checkpoint at every start of a computation:
for range numlayers {
x = x.Checkpoint()
residual := x
x = layers.Dense(ctx, x, 1024)
x = activations.Gelu(x)
// ... more heavy layers ...
x = Add(x, residual)
}
// 2. End of the block: stop checkpointing, so the caller of this function
// has a "normal" node (if they don't want to further use checkpointing).
return x.StopCheckpoint()
func (*Node) CloneWithInputs ¶
CloneWithInputs creates a clone of the node but using the given new inputs instead.
It also propagates some generic attributes like stopGradient, customVJP, alias. But it **does not** propagate extra functionality ones, like `logMessage`, `isCheckpointed`, `needsRematerialization`.
func (*Node) ConstantValue ¶
ConstantValue returns the value assigned to a constant node. It's an "introspection" method. It returns nil if n.Type() != NodeTypeConstant.
func (*Node) CustomGradient ¶
CustomGradient returns a registered custom gradient for the Node. See IdentityWithCustomGradient.
func (*Node) GetAlias ¶
GetAlias returns the alias (with the absolute path) of the current node, if one was registered with Node.WithAlias, otherwise returns "".
func (*Node) GetParameterHandle ¶
func (n *Node) GetParameterHandle() ParameterHandle
GetParameterHandle returns the parameter id in the graph. It panics if node is not a parameter.
func (*Node) GetParameterName ¶
GetParameterName returns the parameter name. If node is not a parameter, it panics.
func (*Node) Inputs ¶
Inputs are the other nodes that are direct inputNodes to the node. This doesn't include static inputNodes for some operations that are not given by other Graph nodes.
func (*Node) IsConstantExpression ¶
IsConstantExpression returns whether the Node is a Constant or an expression that depends only on constant values. It traverses all the node dependencies and checks that all leaf nodes are constants.
func (*Node) LogMessage ¶
LogMessage associated with node, if any.
func (*Node) NumOutputs ¶
NumOutputs returns the number of outputs for a node.
Almost every node will have one output only. But a few (like "RNGBitGenerator") will output various outputs that are split before usage. These nodes are marked with an invalid dtype.
Used internally only, all Graph public operations will return nodes with one output only.
func (*Node) SetLogged ¶
SetLogged indicates that a node should be logged by executors, with the given message.
func (*Node) SetLoggedf ¶
SetLoggedf indicates that a node should be logged by executors, with the given formatted message. See SetLogged.
func (*Node) Shape ¶
Shape of the Node's output. It can be `nil`, for nodes that simply have a side effect, like a "Print" Node.
func (*Node) StopCheckpoint ¶
StopCheckpoint wraps the current node in an optimization barrier, marks it as a memory firewall boundary, but clears the contagious rematerialization flag.
This isolates downstream layers from unnecessarily duplicating their execution paths. Call this exactly once at the final output of your checkpointed block.
See example in Node.Checkpoint.
func (*Node) StopGradient ¶
StopGradient returns weather node is a StopGradient.
func (*Node) String ¶
String implements the `fmt.Stringer` interface. Logged nodes are marked with (*).
func (*Node) Trace ¶
Trace returns stack-trace in form of an error, of when the node was created. Only available if enabled by `Graph.SetTraced(true)`.
func (*Node) Type ¶
Type identify the operation performed by the node. It's an "introspection" method.
func (*Node) WithAlias ¶
WithAlias sets an alias in the Graph for the node. It allows it to be retrieved with Graph.GetNodeByAlias.
The alias is automatically prefixed with the Graph current "alias scope", see Graph.PushAliasScope and Graph.PopAliasScope. Except if the alias starts with AliasScopeSeparator ("/"), in which case it is assumed to be given with an "absolute scope path".
It returns the Node itself, to allow cascading method calling.
It panics if the exact same alias already exists.
type NodeInputs ¶
type NodeInputs interface {
Type() NodeType
// String prints a descriptive representation of the node, using its parameters.
String() string
// CloneWithInputs recreates the node using the given inputs instead of the original ones.
CloneWithInputs(originalNode *Node, newInputs ...*Node) *Node
}
NodeInputs represents the inputs to node. The common interface is to return the type of the node. For the input parameters themselves, the pointer needs to be cast to the corresponding type, usually named inputNodes<backend_operation_name>, see generated gen_backend_ops.go
type NodeType ¶
type NodeType int
const ( NodeTypeInvalid NodeType = iota NodeTypeSplitNode NodeTypeAbs NodeTypeAdd NodeTypeAllReduce NodeTypeArgMinMax NodeTypeAtan2 NodeTypeBatchNormForInference NodeTypeBatchNormForTraining NodeTypeBatchNormGradient NodeTypeBitCount NodeTypeBitcast NodeTypeBitwiseAnd NodeTypeBitwiseNot NodeTypeBitwiseOr NodeTypeBitwiseXor NodeTypeBroadcastInDim NodeTypeCeil NodeTypeClamp NodeTypeClz NodeTypeComplex NodeTypeConcatenate NodeTypeConj NodeTypeConstant NodeTypeConvGeneral NodeTypeConvertDType NodeTypeCos NodeTypeCumSum NodeTypeDiv NodeTypeDotGeneral NodeTypeDynamicBroadcastInDim NodeTypeDynamicDimensionSize NodeTypeDynamicIota NodeTypeDynamicPad NodeTypeDynamicReshape NodeTypeDynamicShape NodeTypeDynamicSlice NodeTypeDynamicUpdateSlice NodeTypeEqual NodeTypeEqualTotalOrder NodeTypeErf NodeTypeExp NodeTypeExpm1 NodeTypeFFT NodeTypeFloor NodeTypeFusedActivation NodeTypeFusedActivationVJP NodeTypeFusedAttentionQKVProjection NodeTypeFusedDense NodeTypeFusedDenseVJP NodeTypeFusedLayerNorm NodeTypeFusedQuantizedDense NodeTypeFusedScaledDotProductAttention NodeTypeFusedScaledDotProductAttentionVJP NodeTypeFusedSoftmax NodeTypeGather NodeTypeGreaterOrEqual NodeTypeGreaterOrEqualTotalOrder NodeTypeGreaterThan NodeTypeGreaterThanTotalOrder NodeTypeIdentity NodeTypeImag NodeTypeIota NodeTypeIsFinite NodeTypeIsNaN NodeTypeLessOrEqual NodeTypeLessOrEqualTotalOrder NodeTypeLessThan NodeTypeLessThanTotalOrder NodeTypeLog NodeTypeLog1p NodeTypeLogicalAnd NodeTypeLogicalNot NodeTypeLogicalOr NodeTypeLogicalXor NodeTypeLogistic NodeTypeMax NodeTypeMin NodeTypeMul NodeTypeNeg NodeTypeNotEqual NodeTypeNotEqualTotalOrder NodeTypeOptimizationBarrier NodeTypePad NodeTypeParameter NodeTypePow NodeTypeQuantizedEmbeddingLookup NodeTypeRNGBitGenerator NodeTypeReal NodeTypeReduceBitwiseAnd NodeTypeReduceBitwiseOr NodeTypeReduceBitwiseXor NodeTypeReduceLogicalAnd NodeTypeReduceLogicalOr NodeTypeReduceLogicalXor NodeTypeReduceMax NodeTypeReduceMin NodeTypeReduceProduct NodeTypeReduceSum NodeTypeReduceWindow NodeTypeRem NodeTypeReshape NodeTypeReverse NodeTypeRound NodeTypeRsqrt NodeTypeScatterMax NodeTypeScatterMin NodeTypeScatterSum NodeTypeSchedulingBarrier NodeTypeSelectAndScatterMax NodeTypeSelectAndScatterMin NodeTypeShiftLeft NodeTypeShiftRightArithmetic NodeTypeShiftRightLogical NodeTypeSign NodeTypeSin NodeTypeSlice NodeTypeSqrt NodeTypeSub NodeTypeTanh NodeTypeTranspose NodeTypeWhere )
const NodeTypeCall NodeType = 1000
NodeTypeCall is the NodeType for function calls. We use a large number to avoid conflict with generated NodeTypes in gen_backend_ops.go.
const NodeTypeIf NodeType = 1003
NodeTypeIf is the NodeType for If operations.
const NodeTypeSort NodeType = 1001
const NodeTypeWhile NodeType = 1002
NodeTypeWhile is the NodeType for While operations.
func NodeTypeString ¶
NodeTypeString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.
func NodeTypeValues ¶
func NodeTypeValues() []NodeType
NodeTypeValues returns all values of the enum
func (NodeType) IsANodeType ¶
IsANodeType returns "true" if the value is listed in the enum definition. "false" otherwise
func (NodeType) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface for NodeType
func (NodeType) MarshalText ¶
MarshalText implements the encoding.TextMarshaler interface for NodeType
func (NodeType) MarshalYAML ¶
MarshalYAML implements a YAML Marshaler for NodeType
func (*NodeType) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface for NodeType
func (*NodeType) UnmarshalText ¶
UnmarshalText implements the encoding.TextUnmarshaler interface for NodeType
func (*NodeType) UnmarshalYAML ¶
UnmarshalYAML implements a YAML Unmarshaler for NodeType
type NodeXlaHandle ¶
type NodeXlaHandle int
NodeXlaHandle is used by the underlying XLA implementation.
type PadAxis ¶
PadAxis defines the amount of padding preceding one axis (Start), at the end of axis (End) or in between the inputNodes (Interior). This is used as a parameter for the Pad function. This is an alias to compute.PadAxis
type ParameterHandle ¶
type ParameterHandle int
ParameterHandle is a key to be used by Graph implementations to refer to its internal parameters.
type ParamsMap ¶
ParamsMap is a shortcut for the map of parameters and their values passed to a graph execution. The values can be anything accepted by tensor.FromAnyValue().
type PoolBuilder ¶
type PoolBuilder struct {
// contains filtered or unexported fields
}
PoolBuilder is a helper to build a pool computation. Create it with {Max|Sum|Mean|Prod}Pool, set the desired parameters and when set, call `IsNil()`.
func ConcatPool ¶
func ConcatPool(x *Node) *PoolBuilder
ConcatPool pool on the spatial dimensions by increasing the channels' dimension, across the window.
Example: x.shape=[batch_size, height, width, 3] and Window(3): the output depth will be 9x3=27, with the concatenation of the surrounding pixels' channels.
The implementation actually uses a convolution with a fixed kernel, but it can be seen as a concatenating pool operation.
func MaxPool ¶
func MaxPool(x *Node) *PoolBuilder
MaxPool prepares a max pooling on x for an arbitrary number of spatial dimensions (1D, 2D, 3D, etc.). It returns the max value for the selected window, on given strides.
It is very flexible. To ease the configuring of its parameters, it returns a PoolBuilder for configuration. Once it is set up, call `PoolBuilder.Done` and it will return the pooled x. Browse through PoolBuilder to see the capabilities, and the defaults.
The window sizes must be set with PoolBuilder.Window or PoolBuilder.WindowPerAxis.
The shapes of x should be `[batch, <spatial_dimensions...>, input_channels]` if configured with `PoolBuilder.ChannelsAxis(images.ChannelsLast)`, the default. If one sets `PoolBuilder.ChannelsAxis(images.ChannelsFirst)`, the shapes should be `[batch, input_channels, <spatial_dimensions...>]` instead.
The "channels" axis is also known as the depth or feature axis.
Note: `images` refers to the package `github.com/gomlx/gomlx/core/tensors/images`.
func MeanPool ¶
func MeanPool(x *Node) *PoolBuilder
MeanPool prepares a mean pooling on x for an arbitrary number of spatial dimensions (1D, 2D, 3D, etc.). It returns the max value for the selected window, on given strides.
It is very flexible. To ease the configuring of its parameters, it returns a PoolBuilder for configuration. Once it is set up, call `PoolBuilder.Done` and it will return the pooled x. Browse through PoolBuilder to see the capabilities, and the defaults.
The window sizes must be set with PoolBuilder.Window or PoolBuilder.WindowPerAxis.
The shapes of x should be `[batch, <spatial_dimensions...>, input_channels]` if configured with `PoolBuilder.ChannelsAxis(images.ChannelsLast)`, the default. If one sets `PoolBuilder.ChannelsAxis(images.ChannelsFirst)`, the shapes should be `[batch, input_channels, <spatial_dimensions...>]` instead.
The "channels" axis is also known as the depth or feature axis.
Note: `images` refers to the package `github.com/gomlx/gomlx/core/tensors/images`.
func MinPool ¶
func MinPool(x *Node) *PoolBuilder
MinPool prepares a min pooling on x for an arbitrary number of spatial dimensions (1D, 2D, 3D, etc.). It returns the max value for the selected window, on given strides.
It is very flexible. To ease the configuring of its parameters, it returns a PoolBuilder for configuration. Once it is set up, call `PoolBuilder.Done` and it will return the pooled x. Browse through PoolBuilder to see the capabilities, and the defaults.
The window sizes must be set with PoolBuilder.Window or PoolBuilder.WindowPerAxis.
The shapes of x should be `[batch, <spatial_dimensions...>, input_channels]` if configured with `PoolBuilder.ChannelsAxis(images.ChannelsLast)`, the default. If one sets `PoolBuilder.ChannelsAxis(images.ChannelsFirst)`, the shapes should be `[batch, input_channels, <spatial_dimensions...>]` instead.
The "channels" axis is also known as the depth or feature axis.
Note: `images` refers to the package `github.com/gomlx/gomlx/core/tensors/images`.
func SumPool ¶
func SumPool(x *Node) *PoolBuilder
SumPool prepares a sum pooling on x for an arbitrary number of spatial dimensions (1D, 2D, 3D, etc.). It returns the max value for the selected window, on given strides.
It is very flexible. To ease the configuring of its parameters, it returns a PoolBuilder for configuration. Once it is set up, call `PoolBuilder.Done` and it will return the pooled x. Browse through PoolBuilder to see the capabilities, and the defaults.
The window sizes must be set with PoolBuilder.Window or PoolBuilder.WindowPerAxis.
The shapes of x should be `[batch, <spatial_dimensions...>, input_channels]` if configured with `PoolBuilder.ChannelsAxis(images.ChannelsLast)`, the default. If one sets `PoolBuilder.ChannelsAxis(images.ChannelsFirst)`, the shapes should be `[batch, input_channels, <spatial_dimensions...>]` instead.
The "channels" axis is also known as the depth or feature axis.
Note: `images` refers to the package `github.com/gomlx/gomlx/core/tensors/images`.
func (*PoolBuilder) ChannelsAxis ¶
func (pool *PoolBuilder) ChannelsAxis(channelsAxisConfig images.ChannelsAxisConfig) *PoolBuilder
ChannelsAxis configures the axis for the channels (aka. "depth" or "features") dimension. The default is `images.ChannelsLast`, meaning the "channels" dimension comes last.
Note: `images` refers to package `github.com/gomlx/gomlx/core/tensors/images`.
If you don't want to exclude the batch size and channels from the pooling, use FullShape instead.
It returns the modified Config object, so calls can be cascaded.
func (*PoolBuilder) Done ¶
func (pool *PoolBuilder) Done() *Node
Done finishes the PoolBuilder configuration and returns the pooled output.
func (*PoolBuilder) FullShape ¶
func (pool *PoolBuilder) FullShape() *PoolBuilder
FullShape configures the pooling operation to consider all its axes as part of the pooling, with no special considerations for the batch or channel axes.
See ChannelsAxis to handle batch and channels specially.
The default is configured with ChannelsAxis(images.ChannelsLast).
func (*PoolBuilder) NoPadding ¶
func (pool *PoolBuilder) NoPadding() *PoolBuilder
NoPadding removes any paddings, so if the pooling window > 1, the output shapes will be reduced on the edges. This is the default.
func (*PoolBuilder) PadSame ¶
func (pool *PoolBuilder) PadSame() *PoolBuilder
PadSame adds paddings on the edges of x such that in the end the output of the convolution has the same shapes as the input.
This changes the default value of Strides to 1 if it is not set -- if set to something else, PadSame won't really output the same shapes as the input.
The default is NoPadding.
func (*PoolBuilder) PaddingPerDim ¶
func (pool *PoolBuilder) PaddingPerDim(paddings [][2]int) *PoolBuilder
PaddingPerDim specifies the paddings at the start and at the end to use per spatial dimension, that means one pair ([2]int) per spatial dimension. The default is PadSame.
func (*PoolBuilder) StridePerAxis ¶
func (pool *PoolBuilder) StridePerAxis(strides ...int) *PoolBuilder
StridePerAxis sets the strides for each spatial dimension of the pooling.
The default is the same value as the window size (set with Window or WindowPerAxis) -- except if one uses PadSame, then the default changes to 1.
The stride is how many steps to move after a pooling. A value of 2 will half the input size, since a pooling will be done at every other position, and so on. It can be defined separately per dimension.
One cannot use strides and dilation at the same time.
func (*PoolBuilder) Strides ¶
func (pool *PoolBuilder) Strides(strides int) *PoolBuilder
Strides sets the strides of the pooling. It sets the same value for every spatial dimension.
The default is the same value as the window size (set with Window or WindowPerAxis) -- except if one uses PadSame, then the default changes to 1.
The stride is how many steps to move after the pooling of a window. A value of 2 will halve the input size, since the pooling will be done at every other position, and so on. It can be defined separately per dimension with StridePerAxis.
One cannot use strides and dilation at the same time.
func (*PoolBuilder) Window ¶
func (pool *PoolBuilder) Window(windowSize int) *PoolBuilder
Window sets the pooling window size for all spatial dimensions to the same windowSize.
There is no default, and this must be set either with Window or WindowPerAxis.
func (*PoolBuilder) WindowPerAxis ¶
func (pool *PoolBuilder) WindowPerAxis(sizes ...int) *PoolBuilder
WindowPerAxis sets the pooling window size for each spatial dimension.
There is no default, and this must be set either with Window or WindowPerAxis.
type Quantization ¶
type Quantization struct {
// Scheme: Linear, NF4, or GGML.
Scheme compute.QuantizationScheme
// Scale is the multiplicative factor.
// Shape: [K, NumBlocks] (block-wise), where K is the input-features
// (contracting) dimension of the [K, N] weight matrix and
// NumBlocks = ceil(N / BlockSize).
// Nil for QuantGGML (scales are embedded in the blocks).
Scale *Node
// ZeroPoint is the additive offset (only for Linear).
// If nil, the quantization is assumed symmetric.
// Unused for QuantGGML and QuantNF4.
ZeroPoint *Node
// BlockAxis is the dimension of the quantized tensor that is blocked.
// This is the output-features dimension (axis 1) of a [K, N] weight matrix.
// Currently only BlockAxis=1 is supported.
// Unused for QuantGGML.
BlockAxis int
// BlockSize is the number of elements in BlockAxis that share one scale.
// If BlockSize == values.Shape()[BlockAxis], it's effectively per-axis quantization.
// Unused for QuantGGML.
BlockSize int
// GGMLType specifies the concrete GGML block format (Q4_0, Q8_0, etc.).
// Only used when Scheme == QuantGGML.
GGMLType compute.GGMLQuantType
}
Quantization describes how a graph-level quantized tensor is dequantized. This is the graph-layer counterpart of compute.Quantization, holding *Node references for Scale and ZeroPoint instead of compute.Value.
type Ragged2D ¶
Ragged2D is a 2D ragged representation with the first dimension dense and the second axis being ragged. It can be interpreted as an array (fixed size) of variable length lists.
A "ragged" representation is a special type of sparse representation where values are only defined on the start of the axis, and the tail of the axis is assumed to be irrelevant, or in some cases zero.
For now, if the user has ragged tensors with larger rank, its up to them to reshape and transpose around to get to a 2D representation. A generic ragged representation using fixed shaped tensors is a TODO.
To store a "ragged" representation we use a flat compact representation of the data (without the irrelevant parts) and the RowIDs for each elements: which row they are part of. Because GoMLX doesn't (yet) support dynamic shapes, it also takes the static value of the first axis dimension Dim0, it must be known in graph compile time.
See TensorFlow's more generic RaggedTensor in https://www.tensorflow.org/guide/ragged_tensor, which was used as a source of inspiration -- this is a much simpler implementation, but covers many of the use cases.
A note on padding: because of the static shape requirements, it's practice to use the last row as a "padding" row, and assign the RowIDs of the padding values to that extra row.
func MakeRagged2D ¶
MakeRagged2D creates a new Ragged2D using rowIDs.
The rowIDs _must be sorted_, meaning the flat values must come in row,col order, otherwise many of the operations will display undefined behaviour.
Example:
MakeRagged2D(dim0=4, flat=[1, 2, 3, 4, 5], rowsIds=[0, 0, 0, 1, 3]) represents the following 4x3 ragged 2D tensor :
{ {1, 2, 3},
{4},
{},
{5} }
func (Ragged2D) ReduceMaxCols ¶
ReduceMaxCols returns the max over the ragged axis (columns). It returns a 1D tensor of shape Ragged2D.Dim0 with the values for each rows.
Rows with no ragged values, will have -Inf values.
func (Ragged2D) ReduceMinCols ¶
ReduceMinCols returns the min over the ragged axis (columns). It returns a 1D tensor of shape Ragged2D.Dim0 with the values for each rows.
Rows with no ragged values, will have Inf values.
func (Ragged2D) ReduceSumCols ¶
ReduceSumCols returns the sum over the ragged axis (columns). It returns a 1D tensor of shape Ragged2D.Dim0.
type ReduceOpType ¶
type ReduceOpType = compute.ReduceOpType
type ReshapeDimensionSpec
deprecated
added in
v0.28.2
type ReshapeDimensionSpec = DimensionSpec
ReshapeDimensionSpec is an alias to DimensionSpec for backwards compatibility.
Deprecated: use DimensionSpec instead.
type ShiftDirection ¶
type ShiftDirection bool
ShiftDirection used by ShiftWithScalar and ShiftWithValue. See ShiftDirLeft and ShiftDirRight.
const ( ShiftDirLeft ShiftDirection = false ShiftDirRight = true )
func (ShiftDirection) String ¶
func (s ShiftDirection) String() string
String implements the stringer interface.
type SideParamsFn ¶
SideParamsFn is a function that sets side parameters during execution for Graphs that defines those. Typically, this is used to set the variables of a model.
type SingleOutputVJP ¶
SingleOutputVJP for VJP of ops that have a single output (most of them).
type SliceAxisSpec ¶
SliceAxisSpec specifies the range and stride of an axis to include in a Slice.
The recommendation is to use AxisRange or AxisElem (defined below) to create it.
Full means to include the whole range (and ignore Start/End), and NoEnd means from Start to the full dimension of the axis.
Optional (if Stride != 0) it can set the stride for the axis as well.
Spacer means this AxisRange should be the generic definition for all undefined axes -- useful when the rank of the node is not known.
Consider using function AxisRange below to construct SliceAxisSpec values.
TODO: Add strides.
func AxisElem ¶
func AxisElem(index int) SliceAxisSpec
AxisElem defines a range of one element to take for an axis in Slice. It returns an `SliceAxisSpec` object.
func AxisRange ¶
func AxisRange(indices ...int) SliceAxisSpec
AxisRange defines a range to take for an axis in Slice. It returns an `SliceAxisSpec` object.
The indices can have 0, 1 or 2 elements: - If `len(indices) == 0`, it's assumed to be the full range of the axis. - If `len(indices) == 1`, it's assumed to be the start, and the range should be taken to the end. - If `len(indices) == 2`, they should be the start and end indices for the axis. - If `len(indices) > 2`, an error is raised with panic.
See also AxisElem if you want to define only one element of the range.
func AxisRangeFromStart ¶
func AxisRangeFromStart(to int) SliceAxisSpec
AxisRangeFromStart defines a range from the start (0) to the given value for the axis. It's return value is to be used by Slice to specify one axis.
func AxisRangeToEnd ¶
func AxisRangeToEnd(from int) SliceAxisSpec
AxisRangeToEnd defines a range from the given value to the end of the axis. It's return value is to be used by Slice to specify one axis.
func (SliceAxisSpec) Spacer ¶
func (ar SliceAxisSpec) Spacer() SliceAxisSpec
Spacer marks this SliceAxisSpec to be a generic filler range to use on the undefined axes in Slice -- similar to a "*" in a path definition.
It works with any SliceAxisSpec, so it can be used with the return of any call to AxisRange or AxisElem.
Example: let's say we want to get just the last example of a batch, and just the first element of the embedding. Assume x is shaped `[batch_size, ..., embedding_size]` and we want something like `x[-1, ..., 0:1]`
sample := Slice(x, AxisElem(-1), AxisRange().Spacer(), AxisElem(0))
Notice that "spacer" ranges also matches zero dimensions. So if x is shaped `[5, 5]`, calling `Slice(x, AxisElem(0), AxisRange().Spacer(), AxisElem(0))` would return a node of shape `[1, 1]` and the spacer would be ignored.
func (SliceAxisSpec) Stride ¶
func (ar SliceAxisSpec) Stride(stride int) SliceAxisSpec
Stride returns a copy of the SliceAxisSpec with Stride set to the given stride.
type VJP ¶
VJP returns the $v \dot Jacobian$ of the given `node`, with respect to each of its inputNodes (given by `node.Inputs()`).
outputShape is the shape of the value for which we are calculating the gradient for. For now this is only used for Gradient, so one can expect outputShape to be scalar, and `v.Shape()` to be the same as `output.Shape()`. But this won't be true once Jacobian functionality (like a Gradient where output is a non-scalar tensor), is defined.
Args:
node: node for which we are calculating the backward gradient. An important part of `node` are its inputNodes given by `node.Inputs()`. The VJP function must one gradient per input. v: gradient (or jacobian) of what we care about with the respect to the output of `node`, also known as the adjoint. VJP needs to calculate the next adjoint (`v`) but with respect to the inputNodes of `node` instead. outputShape: for now fixed as scalar, and can be ignored. When we add support for Jacobian this will hold the outputShape of the thing we are calculating the Jacobian for.
Returns:
The adjoint (the updated `vjps`) to each of `node` inputNodes. That is, the gradient of the loss (typically, but of whatever we are calculating the gradient of) with respect to each of the `node` inputNodes.
Source Files
¶
- asserts.go
- distributed.go
- exec.go
- execaliases.go
- function.go
- fused_ops.go
- gen_compute_ops.go
- gen_constraints.go
- gen_nodetype_enumer.go
- gradcheckpoint.go
- graph.go
- introspection.go
- node.go
- node_aliases.go
- ops.go
- ops_bitwise.go
- ops_controlflow.go
- ops_convolve.go
- ops_dotgeneral.go
- ops_dynamic.go
- ops_helpers.go
- ops_interpolate.go
- ops_order.go
- ops_pool.go
- ops_random.go
- ops_signal.go
- ops_sparse.go
- ops_util.go
- ragged2d.go
- rev_autodiff.go
- rng_seed_secure.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package graphtest holds test utilities for packages that depend on the graph package.
|
Package graphtest holds test utilities for packages that depend on the graph package. |
|
Package nanlogger collects `graph.Node` objects to monitor for `NaN` ("not-a-number") or `Inf` (infinity) values.
|
Package nanlogger collects `graph.Node` objects to monitor for `NaN` ("not-a-number") or `Inf` (infinity) values. |