Documentation
¶
Overview ¶
Package notimplemented implements a compute.Builder interface that returns a "not implemented" error for all operations.
This can be wrapped by a [comute.Backend] to bootstrap its implementation and to provide some future compatibility as new ops are added to the API.
Index ¶
- Variables
- type Backend
- func (b *Backend) BufferFromFlatData(deviceNum compute.DeviceNum, flat any, shape shapes.Shape) (compute.Buffer, error)
- func (b *Backend) Builder(name string) compute.Builder
- func (b *Backend) Capabilities() compute.Capabilities
- func (b *Backend) Description() string
- func (b *Backend) DeviceDescription(deviceNum compute.DeviceNum) string
- func (b *Backend) Finalize()
- func (b *Backend) HasSharedBuffers() bool
- func (b *Backend) IsFinalized() bool
- func (b *Backend) Name() string
- func (b *Backend) NewSharedBuffer(deviceNum compute.DeviceNum, shape shapes.Shape) (buffer compute.Buffer, flat any, err error)
- func (b *Backend) NumDevices() int
- func (b *Backend) String() string
- type Builder
- func (b Builder) Compile() (compute.Executable, error)
- func (b Builder) DeviceAssignment(devices ...compute.DeviceNum) error
- func (b Builder) DistributedAutoSharding(meshes ...compute.Mesh) error
- func (b Builder) DistributedSPMD(numDevices int) error
- func (b Builder) Main() compute.Function
- func (b Builder) Name() string
- func (b Builder) NewFunction(name string) (compute.Function, error)
- func (b Builder) OpShape(op compute.Value) (shapes.Shape, error)
- type Function
- func (f Function) Abs(x compute.Value) (compute.Value, error)
- func (f Function) Add(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) AllReduce(inputs []compute.Value, reduceOp compute.ReduceOpType, replicaGroups [][]int) ([]compute.Value, error)
- func (f Function) ArgMinMax(x compute.Value, axis int, outputDType dtypes.DType, isMin bool) (compute.Value, error)
- func (f Function) Atan2(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) BatchNormForInference(operand, scale, offset, mean, variance compute.Value, epsilon float32, ...) (compute.Value, error)
- func (f Function) BatchNormForTraining(operand, scale, offset compute.Value, epsilon float32, axis int) (normalized, batchMean, batchVariance compute.Value, err error)
- func (f Function) BatchNormGradient(operand, scale, mean, variance, gradOutput compute.Value, epsilon float32, ...) (gradOperand, gradScale, gradOffset compute.Value, err error)
- func (f Function) BitCount(operand compute.Value) (compute.Value, error)
- func (f Function) Bitcast(operand compute.Value, targetDType dtypes.DType) (compute.Value, error)
- func (f Function) BitwiseAnd(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) BitwiseNot(x compute.Value) (compute.Value, error)
- func (f Function) BitwiseOr(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) BitwiseXor(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) BroadcastInDim(operand compute.Value, outputShape shapes.Shape, broadcastAxes []int) (compute.Value, error)
- func (f Function) Builder() compute.Builder
- func (f Function) Call(target compute.Function, inputs ...compute.Value) ([]compute.Value, error)
- func (f Function) Ceil(x compute.Value) (compute.Value, error)
- func (f Function) Clamp(min compute.Value, x compute.Value, max compute.Value) (compute.Value, error)
- func (f Function) Closure() (compute.Function, error)
- func (f Function) Clz(x compute.Value) (compute.Value, error)
- func (f Function) Complex(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) Concatenate(axis int, operands ...compute.Value) (compute.Value, error)
- func (f Function) Conj(x compute.Value) (compute.Value, error)
- func (f Function) Constant(flat any, dims ...int) (compute.Value, error)
- func (f Function) ConstantFromBuffer(buf compute.Buffer, donate bool) (compute.Value, error)
- func (f Function) ConvGeneral(input compute.Value, kernel compute.Value, axes compute.ConvolveAxesConfig, ...) (compute.Value, error)
- func (f Function) ConvertDType(x compute.Value, dtype dtypes.DType) (compute.Value, error)
- func (f Function) Cos(x compute.Value) (compute.Value, error)
- func (f Function) CumMax(operand compute.Value, axis int, options compute.CumSumOptions) (compute.Value, error)
- func (f Function) CumSum(operand compute.Value, axis int, options compute.CumSumOptions) (compute.Value, error)
- func (f Function) Div(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) DotGeneral(lhs compute.Value, lhsContractingAxes []int, lhsBatchAxes []int, ...) (compute.Value, error)
- func (f Function) DynamicBroadcastInDim(operand compute.Value, broadcastAxes []int, ...) (compute.Value, error)
- func (f Function) DynamicDimensionSize(operand compute.Value, axis int) (compute.Value, error)
- func (f Function) DynamicIota(dtype dtypes.DType, iotaAxis int, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)
- func (f Function) DynamicPad(x compute.Value, fillValue compute.Value, axesConfig ...compute.DynamicPadAxis) (compute.Value, error)
- func (f Function) DynamicReshape(operand compute.Value, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)
- func (f Function) DynamicShape(operand compute.Value) (compute.Value, error)
- func (f Function) DynamicSlice(operand compute.Value, startIndices []compute.Value, sliceDims []int) (compute.Value, error)
- func (f Function) DynamicUpdateSlice(operand compute.Value, update compute.Value, startIndices []compute.Value) (compute.Value, error)
- func (f Function) Equal(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) EqualTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) Erf(x compute.Value) (compute.Value, error)
- func (f Function) Exp(x compute.Value) (compute.Value, error)
- func (f Function) Expm1(x compute.Value) (compute.Value, error)
- func (f Function) FFT(operand compute.Value, fftType compute.FFTType, fftLength []int) (compute.Value, error)
- func (f Function) Floor(x compute.Value) (compute.Value, error)
- func (f Function) FusedActivation(x compute.Value, cfg compute.ActivationConfig) (compute.Value, error)
- func (f Function) FusedActivationVJP(y compute.Value, x compute.Value, dOutput compute.Value, ...) (compute.Value, error)
- func (f Function) FusedAttentionQKVProjection(x, wQKV, biasQ, biasK, biasV compute.Value, queryDim, keyValueDim int) (query, key, value compute.Value, err error)
- func (f Function) FusedDense(x compute.Value, weight compute.Value, bias compute.Value, ...) (compute.Value, error)
- func (f Function) FusedDenseVJP(x, weight, bias, y, dOutput compute.Value, options compute.DenseConfig) (dx, dWeight, dBias compute.Value, err error)
- func (f Function) FusedLayerNorm(x compute.Value, gamma compute.Value, beta compute.Value, ...) (compute.Value, error)
- func (f Function) FusedLayerNormVJP(x, dOutput, gamma, beta compute.Value, config compute.FusedLayerNormConfig) (dx, dGamma, dBeta compute.Value, err error)
- func (f Function) FusedQuantizedDense(x compute.Value, weight compute.Value, bias compute.Value, ...) (compute.Value, error)
- func (f Function) FusedQuantizedDenseVJP(x, weight, bias, y, dOutput compute.Value, ...) (dx, dBias compute.Value, err error)
- func (f Function) FusedRoPE(x compute.Value, cos compute.Value, sin compute.Value, ...) (compute.Value, error)
- func (f Function) FusedScaledDotProductAttention(query, key, value compute.Value, axesLayout compute.AttentionAxesLayout, ...) (output compute.Value, statesForVJP []compute.Value, err error)
- func (f Function) FusedScaledDotProductAttentionVJP(query, key, value compute.Value, axesLayout compute.AttentionAxesLayout, ...) (dQuery, dKey, dValue compute.Value, err error)
- func (f Function) FusedSoftmax(x compute.Value, axis int) (compute.Value, error)
- func (f Function) FusedTopK(operand compute.Value, k int, cfg compute.FusedTopKConfig) (compute.Value, compute.Value, error)
- func (f Function) Gather(operand compute.Value, startIndices compute.Value, indexVectorAxis int, ...) (compute.Value, error)
- func (f Function) GreaterOrEqual(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) GreaterOrEqualTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) GreaterThan(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) GreaterThanTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) Identity(x compute.Value) (compute.Value, error)
- func (f Function) If(pred compute.Value, trueBranch, falseBranch compute.Function) ([]compute.Value, error)
- func (f Function) Imag(x compute.Value) (compute.Value, error)
- func (f Function) Iota(shape shapes.Shape, iotaAxis int) (compute.Value, error)
- func (f Function) IsFinite(x compute.Value) (compute.Value, error)
- func (f Function) IsNaN(x compute.Value) (compute.Value, error)
- func (f Function) LessOrEqual(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) LessOrEqualTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) LessThan(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) LessThanTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) Log(x compute.Value) (compute.Value, error)
- func (f Function) Log1p(x compute.Value) (compute.Value, error)
- func (f Function) LogicalAnd(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) LogicalNot(x compute.Value) (compute.Value, error)
- func (f Function) LogicalOr(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) LogicalXor(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) Logistic(x compute.Value) (compute.Value, error)
- func (f Function) Max(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) Min(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) Mul(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) Name() string
- func (f Function) Neg(x compute.Value) (compute.Value, error)
- func (f Function) NonZero(operand compute.Value, cfg compute.NonZeroConfig) (compute.Value, error)
- func (f Function) NotEqual(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) NotEqualTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) OptimizationBarrier(operands ...compute.Value) ([]compute.Value, error)
- func (f Function) Pad(x compute.Value, fillValue compute.Value, axesConfig ...compute.PadAxis) (compute.Value, error)
- func (f Function) Parameter(name string, shape shapes.Shape, spec *compute.ShardingSpec) (compute.Value, error)
- func (f Function) Parent() compute.Function
- func (f Function) Pow(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) QuantizedGather(x compute.Value, indices compute.Value, xQuantization *compute.Quantization) (compute.Value, error)
- func (f Function) RNGBitGenerator(state compute.Value, shape shapes.Shape, algorithm compute.RNGAlgorithm) (newState, values compute.Value, err error)
- func (f Function) Real(x compute.Value) (compute.Value, error)
- func (f Function) ReduceBitwiseAnd(x compute.Value, axes ...int) (compute.Value, error)
- func (f Function) ReduceBitwiseOr(x compute.Value, axes ...int) (compute.Value, error)
- func (f Function) ReduceBitwiseXor(x compute.Value, axes ...int) (compute.Value, error)
- func (f Function) ReduceLogicalAnd(x compute.Value, axes ...int) (compute.Value, error)
- func (f Function) ReduceLogicalOr(x compute.Value, axes ...int) (compute.Value, error)
- func (f Function) ReduceLogicalXor(x compute.Value, axes ...int) (compute.Value, error)
- func (f Function) ReduceMax(x compute.Value, axes ...int) (compute.Value, error)
- func (f Function) ReduceMin(x compute.Value, axes ...int) (compute.Value, error)
- func (f Function) ReduceProduct(x compute.Value, axes ...int) (compute.Value, error)
- func (f Function) ReduceSum(x compute.Value, axes ...int) (compute.Value, error)
- func (f Function) ReduceWindow(input compute.Value, reductionType compute.ReduceOpType, ...) (compute.Value, error)
- func (f Function) Rem(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) Reshape(x compute.Value, dimensions ...int) (compute.Value, error)
- func (f Function) Return(outputs []compute.Value, shardings []*compute.ShardingSpec) error
- func (f Function) Reverse(x compute.Value, axes ...int) (compute.Value, error)
- func (f Function) Round(x compute.Value) (compute.Value, error)
- func (f Function) Rsqrt(x compute.Value) (compute.Value, error)
- func (f Function) ScatterMax(operand compute.Value, scatterIndices compute.Value, updates compute.Value, ...) (compute.Value, error)
- func (f Function) ScatterMin(operand compute.Value, scatterIndices compute.Value, updates compute.Value, ...) (compute.Value, error)
- func (f Function) ScatterSum(operand compute.Value, scatterIndices compute.Value, updates compute.Value, ...) (compute.Value, error)
- func (f Function) SchedulingBarrier(operand compute.Value, dependencies ...compute.Value) (compute.Value, error)
- func (f Function) SelectAndScatterMax(operand compute.Value, source compute.Value, windowDimensions []int, ...) (compute.Value, error)
- func (f Function) SelectAndScatterMin(operand compute.Value, source compute.Value, windowDimensions []int, ...) (compute.Value, error)
- func (f Function) Shape(v compute.Value) (shapes.Shape, error)
- func (f Function) ShiftLeft(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) ShiftRightArithmetic(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) ShiftRightLogical(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) Sign(x compute.Value) (compute.Value, error)
- func (f Function) Sin(x compute.Value) (compute.Value, error)
- func (f Function) Slice(x compute.Value, starts []int, limits []int, strides []int) (compute.Value, error)
- func (f Function) Sort(comparator compute.Function, axis int, isStable bool, inputs ...compute.Value) ([]compute.Value, error)
- func (f Function) Sqrt(x compute.Value) (compute.Value, error)
- func (f Function) Sub(lhs compute.Value, rhs compute.Value) (compute.Value, error)
- func (f Function) Tanh(x compute.Value) (compute.Value, error)
- func (f Function) Transpose(x compute.Value, permutation ...int) (compute.Value, error)
- func (f Function) Where(condition compute.Value, onTrue compute.Value, onFalse compute.Value) (compute.Value, error)
- func (f Function) While(cond, body compute.Function, initialState ...compute.Value) ([]compute.Value, error)
Constants ¶
This section is empty.
Variables ¶
var NotImplementedError = compute.ErrNotImplemented
NotImplementedError is returned by every method.
It doesn't contain a stack, attach a stack to with with errors.Wrapf(NotImplementedError, "...") when using it.
Functions ¶
This section is empty.
Types ¶
type Backend ¶
type Backend struct{}
Backend is a dummy backend that can be imported to create mock compute.
func (*Backend) BufferFromFlatData ¶
func (b *Backend) BufferFromFlatData( deviceNum compute.DeviceNum, flat any, shape shapes.Shape, ) (compute.Buffer, error)
BufferFromFlatData returns NotImplementedError.
func (*Backend) Capabilities ¶
func (b *Backend) Capabilities() compute.Capabilities
Capabilities returns empty capabilities.
func (*Backend) Description ¶
Description is a longer description of the Backend.
func (*Backend) DeviceDescription ¶
DeviceDescription returns a description of the device.
func (*Backend) Finalize ¶
func (b *Backend) Finalize()
Finalize does nothing for this dummy backend.
func (*Backend) HasSharedBuffers ¶
HasSharedBuffers returns false.
func (*Backend) IsFinalized ¶
IsFinalized always returns false for this dummy backend.
func (*Backend) NewSharedBuffer ¶
func (b *Backend) NewSharedBuffer( deviceNum compute.DeviceNum, shape shapes.Shape, ) (buffer compute.Buffer, flat any, err error)
NewSharedBuffer panics as shared buffers are not supported.
func (*Backend) NumDevices ¶
NumDevices returns 1 as the number of devices available.
type Builder ¶
type Builder struct {
// ErrFn is called to generate the error returned, if not nil. Otherwise NotImplementedError is returned directly.
//
// For non-ops methods (like Builder.Name and Builder.Compile) you will have to override them.
ErrFn func(op compute.OpType) error
// contains filtered or unexported fields
}
Builder implements compute.Builder and returns the NotImplementedError wrapped with the stack-trace, the operation name, and the custom message Builder.ErrMessage for every operation.
func (Builder) DeviceAssignment ¶
DeviceAssignment returns nil if it's an assignment to device #0. Otherwise, it returns a non-implemented error.
func (Builder) DistributedAutoSharding ¶
func (Builder) DistributedSPMD ¶
type Function ¶
type Function struct {
// ErrFn is called to generate the error returned, if not nil.
// Otherwise NotImplementedError is returned directly.
ErrFn func(op compute.OpType) error
}
Function implements compute.Function and returns NotImplementedError for every operation.
func (Function) Add ¶
Add returns the element-wise sum of the two values. Standard broadcasting rules apply (see documentation).
func (Function) ArgMinMax ¶
func (f Function) ArgMinMax(x compute.Value, axis int, outputDType dtypes.DType, isMin bool) (compute.Value, error)
ArgMinMax calculates the "argmin" or "argmax" across an axis of the given input array x.
outputDType defines the output of the argmin/argmax, it doesn't need to be the same as the input. It's a form of reduction on the given axis, and that axis goes away. So the rank of the result is one less than the rank of x.
If there is a NaN in the slice being examined, it is chosen for ArgMinMax -- this is inline with Jax, TensorFlow, and PyTorch.
Examples:
ArgMinMax(x={{2, 0, 7}, {-3, 4, 2}}, axis=1, isMin=true) -> {1, 0} // (it chooses the 0 and the -3)
ArgMinMax(x={{2, 0, 7}, {-3, 4, 2}}, axis=0, isMin=false) -> {0, 1, 0} // (it chooses the 2, 4, and 7)
Dynamic shapes: ArgMinMax on a dynamic axis removes that axis (and its name), preserving names of other dynamic axes.
func (Function) 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 (Function) BatchNormForInference ¶
func (Function) BatchNormForTraining ¶
func (Function) BatchNormGradient ¶
func (Function) BitCount ¶
BitCount returns the number of bits that are set to one. Also known as Population Count ("Popcnt") or Hamming Weight.
func (Function) 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 (Function) BitwiseAnd ¶
BitwiseAnd returns the element-wise bitwise AND operation.
func (Function) BitwiseNot ¶
BitwiseNot returns the element-wise bitwise AND operation.
func (Function) BitwiseXor ¶
BitwiseXor returns the element-wise bitwise XOR operator.
func (Function) BroadcastInDim ¶
func (f Function) BroadcastInDim(operand compute.Value, outputShape shapes.Shape, broadcastAxes []int) (compute.Value, error)
BroadcastInDim broadcasts the operand to an output with the given shape. broadcastAxes has an output axes value for each operand axes (len(broadcastAxes) == operand.Shape.Rank()). The i-th axis of the operand is mapped to the broadcastAxes[i]-th dimension of the output. broadcastAxes must be also increasing: this operation cannot be used to transpose axes, it will only broadcast and introduce new axes in-between. This also requires that the i-th input axis is either 1 or is the same as the output dimension it's broadcasting into. For example, say operand `operand = (s32)[2]{1, 2}`; outputShape = `(s32)[2,2]`:
- Specifying []int{1} as broadcastAxes will generate output {{1, 2}, {1, 2}}
- On the other hand, specifying []int{0} as broadcastAxes will generate output {{1 , 1}, {2 , 2}}
Dynamic shapes: When broadcasting, an operand axis with a dynamic length cannot be broadcast and must be preserved as dynamic in the output -- their axis names must exactly match in the outputShape. But new dynamic dimensions can be introduced in the output -- either mapping from an axis with dimension 1, or from a newly introduced axis. Notice that introducing new dynamic axis names that are not resolved by any input parameter will result in an error.
func (Function) Ceil ¶
Ceil returns the Op that represents the output of the corresponding operation.
func (Function) Clamp ¶
func (f Function) Clamp(min compute.Value, x compute.Value, max compute.Value) (compute.Value, error)
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 (Function) Clz ¶
Clz returns element-wise the "count leading zeros" bits of input node x -- for integer values.
func (Function) 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 (Function) Concatenate ¶
Concatenate operands on the given axis.
All axes that are not being concatenated must match dimensions, except on the axes being concatenated. It doesn't work with scalars -- use ExpandAxes. If there is only one operand, it is returned and this is a no-op.
Dynamic shapes: Concatenation on a dynamic axis is currently not supported, because the resulting size (e.g. batchSize + batchSize) cannot be represented symbolically yet (requires axis expressions).
func (Function) ConstantFromBuffer ¶ added in v0.1.30
func (Function) ConvGeneral ¶
func (f Function) ConvGeneral(input compute.Value, kernel compute.Value, axes compute.ConvolveAxesConfig, strides []int, paddings [][2]int, inputDilations []int, kernelDilations []int, channelGroupCount int, batchGroupCount int) (compute.Value, error)
ConvGeneral is a generic Convolution operation with arbitrary number of spatial axes, strides, paddings, dilations, and grouping.
Arguments:
- input: it must have one batch and one channel axis, and arbitrary number of spatial axes.
- kernel: its rank must match the input's spatial axes.
- axes: defines how the axes of input and kernel are mapped.
- strides: stride of the convolution window, how it moves. If set, one value per spatial axis, and values must be >= 1. If not set, strides default to 1.
- paddings: padding applied to the start and end of each axis of the input. If nil, it defaults to no padding.
- inputDilations: "virtually" expand the input by inserting `2-1` copies of `0` (or whatever is the reduciton "zero" value) between the elements in each dimension. If nil, it's assumed to be 1 (no dilation) for each axis. Values must be >= 1.
- kernelDilations: "virtually" expand the kernel by inserting `2-1` copies of `0` between the elements in each dimension. If nil, it's assumed to be 1 (no dilation) for each axis. Values must be >= 1. Also known as "atrous convolution".
- channelGroupCount: number of input channels to group together for the convolution. (aka "grouped convolution"). If <= 1 it's disabled.
- batchGroupCount: number of input batches to group together for the convolution. If <= 1 it's disabled.
There is a more detailed description in https://www.tensorflow.org/xla/operation_semantics#convwithgeneralpadding_convolution. Also useful, https://arxiv.org/pdf/1603.07285v1.pdf. Note:
- Another common term for "channels" is "features".
- "Kernel" is also commonly called "weights" or "filters".
Dynamic shapes: Operation on a dynamic spatial axis that changes its size (stride > 1, padding != 0, window > 1, etc.) is currently not supported (requires axis expressions).
func (Function) ConvertDType ¶
ConvertDType of x to dtype.
func (Function) CumMax ¶ added in v0.1.19
func (f Function) CumMax(operand compute.Value, axis int, options compute.CumSumOptions) (compute.Value, error)
CumMax returns the cumulative maximum of the elements along the given axis.
Parameters:
- operand: input value to compute the cumulative maximum on.
- axis: axis along which to compute the cumulative maximum. It must be in the range 0 <= axis < rank.
- options: CumSumOptions with Exclusive and Reverse flags. When Exclusive is true, the identity element is operand.DType().LowestValue() (-Inf for float types, MinInt* for signed ints, 0 for unsigned ints).
Examples:
CumMax([3, 1, 4, 2], 0, CumSumOptions{}) -> [3, 3, 4, 4]
CumMax([3, 1, 4, 2], 0, CumSumOptions{Exclusive: true}) -> [-Inf, 3, 3, 4]
CumMax([3, 1, 4, 2], 0, CumSumOptions{Reverse: true}) -> [4, 4, 4, 2]
CumMax([3, 1, 4, 2], 0, CumSumOptions{Exclusive: true, Reverse: true}) -> [4, 4, 2, -Inf]
func (Function) CumSum ¶ added in v0.1.5
func (f Function) CumSum(operand compute.Value, axis int, options compute.CumSumOptions) (compute.Value, error)
CumSum returns the cumulative sum of the elements along the given axis.
Parameters:
- operand: input value to sum.
- axis: axis along which to compute the cumulative sum. It must be in the range 0 <= axis < rank.
- options: CumSumOptions with Exclusive and Reverse flags.
Examples:
CumSum([1, 2, 3], 0, CumSumOptions{}) -> [1, 3, 6]
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 (Function) Div ¶
Div returns the element-wise division of the two values. Standard broadcasting rules apply (see documentation).
func (Function) DotGeneral ¶
func (f Function) DotGeneral(lhs compute.Value, lhsContractingAxes []int, lhsBatchAxes []int, rhs compute.Value, rhsContractingAxes []int, rhsBatchAxes []int, config compute.DotGeneralConfig) (compute.Value, error)
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.
The resulting shape is [batchIndices..., <lhs cross indices...>, <rhs cross indices...>], the indices come in the order they were provided. The output dtype is by default the same as the input, except if configured otherwise in config.OutputDType.
It provides the basic means of implementing Einsum.
Dynamic shapes: Aligned or contracted dynamic axes must have the same name for both lhs and rhs.
func (Function) DynamicBroadcastInDim ¶ added in v0.1.5
func (f Function) DynamicBroadcastInDim(operand compute.Value, broadcastAxes []int, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)
DynamicBroadcastInDim broadcasts the operand to target dimensions specified by dimensions.
broadcastAxes has an output axis value for each operand axis (len(broadcastAxes) == operand.Shape().Rank()). The i-th axis of the operand is mapped to the broadcastAxes[i]-th dimension of the output. broadcastAxes must also be strictly increasing: this operation cannot be used to transpose axes.
Each target dimension can be: - Static: specified with Static >= 0. - Dynamic: specified with Name and dynamic scalar Value, or Name only if the dynamic axis is already known from context.
Dynamic shapes:
- Static operand axis == 1: broadcasts to any static (>= 0) or dynamic output dimension.
- Static operand axis != 1 (0 or >= 2): if mapped to a static output dimension, they must match at build time. If mapped to a dynamic output dimension, shape inference narrows the output dimension to that static value (the only valid runtime outcome), while still validating at runtime that the dynamic target dimension matches.
- Dynamic operand axis: may map to a static output dimension (>= 0) or a compatible dynamic output dimension (with matching/compatible axis names, and either a Value or known axis binding when the target axis name differs from the operand's). At runtime, the concrete operand dimension must either equal 1 (broadcasting to the target, including 1 -> 0) or equal the concrete target dimension.
Usually, this operation is only supported if the backend supports dynamic axes (Capabilities.DynamicAxes).
func (Function) DynamicDimensionSize ¶
DynamicDimensionSize returns the dimension of the given axis of the operand as a dynamic scalar value. This is only supported by backends that support dynamic shapes (see Capabilities.DynamicShapes).
The returned scalar has dtype Capabilities.DynamicDimDType (typically Int64, or backend-dependent).
func (Function) DynamicIota ¶ added in v0.1.5
func (f Function) DynamicIota(dtype dtypes.DType, iotaAxis int, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)
DynamicIota creates a tensor with the given dynamic dimensions and dtype, filled with increasing numbers (starting from 0) along the specified iotaAxis.
Each dimension can be: - Static: specified with Static >= 0. - Dynamic: specified with Name and dynamic scalar Value, or Name only if the dynamic axis is already known from context.
Usually, this operation is only supported if the backend supports dynamic axes (Capabilities.DynamicAxes).
func (Function) DynamicPad ¶ added in v0.1.5
func (f Function) DynamicPad(x compute.Value, fillValue compute.Value, axesConfig ...compute.DynamicPadAxis) (compute.Value, error)
DynamicPad injects padding on the start, end, or interior of the given operand using static and/or dynamic scalar padding amounts, with the value given in fillValue (which must be a scalar of the same DType as x).
For each axis, interior padding is applied first (inserting Interior/InteriorValue copies of fillValue between adjacent elements, adding max(0, dim-1)*interior elements), followed by Start/StartValue and End/EndValue padding at the boundaries.
Start and End (and StartValue, EndValue) can be negative, in which case they truncate (crop) elements from the start or end of the axis (after interior padding is applied). Interior (and InteriorValue) must be non-negative (>= 0). The resulting dimension size for every axis must be >= 0.
There must be at most operand.Rank() axesConfig values. Missing axes are assumed to have no padding.
Usually, this operation is only supported if the backend supports dynamic axes (Capabilities.DynamicAxes).
func (Function) DynamicReshape ¶ added in v0.1.1
func (f Function) DynamicReshape(operand compute.Value, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)
DynamicReshape reshapes x to target dimensions specified by dimensions.
Each dimension can be: - Static; - Dynamic: a Name and (dynamic) Value are provided. - Auto-inferred: only a Name is provided, at most one axis can be auto-inferred.
Usually, this operation is only supported if the backend supports dynamic axes (Capabilities.DynamicAxes).
func (Function) DynamicShape ¶
DynamicShape returns the shape of the operand as a dynamic 1D tensor. This is only supported by backends that support dynamic shapes (see Capabilities.DynamicShapes).
The returned 1D tensor has dtype Capabilities.DynamicDimDType (typically Int64, or backend-dependent).
func (Function) DynamicSlice ¶
func (f Function) DynamicSlice(operand compute.Value, startIndices []compute.Value, sliceDims []int) (compute.Value, error)
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 (Function) DynamicUpdateSlice ¶
func (f Function) DynamicUpdateSlice(operand compute.Value, update compute.Value, startIndices []compute.Value) (compute.Value, error)
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 (Function) Equal ¶
Equal performs element-wise equality check, returns boolean results with the same dimensions as input.
func (Function) 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 (Function) Erf ¶
Erf returns the "error function", defined as erf(x) = 2/Pi * \int_{0}^{x}{e^{-t^2}dt}.
func (Function) Expm1 ¶
Expm1 returns the Op that represents the output of the corresponding operation.
func (Function) FFT ¶
func (f Function) FFT(operand compute.Value, fftType compute.FFTType, fftLength []int) (compute.Value, error)
FFT calls the XLA FFT operation, which implements {Forward, Inverse} x {Complex, Real} versions. See documentation in https://www.tensorflow.org/xla/operation_semantics. Underlying, CPU FFT is backed by Eigen's TensorFFT, and GPU FFT uses cuFFT.
func (Function) Floor ¶
Floor returns the Op that represents the output of the corresponding operation.
func (Function) FusedActivation ¶ added in v0.1.9
func (f Function) FusedActivation(x compute.Value, cfg compute.ActivationConfig) (compute.Value, error)
FusedActivation applies the configured activation function. cfg.Type is obligatory, other fields are optional and specific for activations.
func (Function) FusedActivationVJP ¶ added in v0.1.9
func (f Function) FusedActivationVJP(y compute.Value, x compute.Value, dOutput compute.Value, cfg compute.ActivationConfig) (compute.Value, error)
FusedActivationVJP computes the vector-jacobian product of the configured activation: dx = dOutput * f'(x) (or dOutput * f'(y)).
Parameters:
- y: output of the activation, calculated presumably by FusedActivation.
- x: input to the activation. If cfg.Type.VJPRequiresInput() is false, x can be nil if y is provided.
- dOutput: the incoming adjoint gradient (the "V" in "VJP"), with the same shape as y.
- cfg: the activation configuration.
func (Function) FusedAttentionQKVProjection ¶
func (Function) FusedDense ¶
func (f Function) FusedDense(x compute.Value, weight compute.Value, bias compute.Value, options compute.DenseConfig) (compute.Value, error)
FusedDense performs fused matmul + optional bias + optional activation.
It does y = activation(x @ W + bias) for DenseLayoutInputOutputs, or y = activation(x @ W^T + bias) for DenseLayoutOutputsInput. Where @ is a standard matmul.
- x: [batch..., in_features]
- weight: [in_features, out_features...] (if WeightLayout is DenseLayoutInputOutputs) or [out_features..., in_features] (if WeightLayout is DenseLayoutOutputsInput)
- bias: [out_features...] (nil-able).
- options: DenseConfig options (activation and weight layout).
Note: ActivationSwiGLU is explicitly not supported for FusedDense because it halves the last dimension (output shape changes). This would require allocating temporary memory and complicate the matmul implementation, eliminating the cache-locality gains of epilogue fusion. Instead, use FusedDense with no activation, followed by FusedActivation with ActivationSwiGLU as a separate operation.
func (Function) FusedDenseVJP ¶ added in v0.1.9
func (Function) FusedLayerNorm ¶
func (f Function) FusedLayerNorm(x compute.Value, gamma compute.Value, beta compute.Value, config compute.FusedLayerNormConfig) (compute.Value, error)
FusedLayerNorm applies layer normalization or RMS normalization over the axes specified in config. gamma and beta can be nil if no learned scale/offset is needed. See FusedLayerNormConfig for options (Axes, Epsilon, RMSNorm, GammaOffset, NormalizationDType). Backends that do not support a given option combination (e.g. RMSNorm, GammaOffset != 0, or a specific NormalizationDType) return ErrNotImplemented so callers can fall back cleanly.
func (Function) FusedLayerNormVJP ¶ added in v0.1.26
func (Function) FusedQuantizedDense ¶
func (f Function) FusedQuantizedDense(x compute.Value, weight compute.Value, bias compute.Value, options compute.FusedQuantizedDenseConfig) (compute.Value, error)
FusedQuantizedDense performs fused quantized matrix multiplication + optional bias + optional activation (+ optional output re-quantization), without materializing the full dequantized weight tensor in memory:
- Weight-only quantization (options.XQuantization == nil): z = x @ dequant(weight, options.WeightQuantization) + bias (transposing dequant(weight) when options.WeightLayout == DenseLayoutOutputsInput; if options.QuantizedMatmul is true, backends may dynamically quantize x internally to run integer SIMD dot products).
- Pre-quantized x + weight integer matmul (options.XQuantization != nil): supports QuantLinear (exact Int32 accumulation of (x - xZP) @ (w - wZP) rescaled by xScale * wScale) and QuantGGML (GGMLQ8_0 / GGMLQ8_K paired per-block Int32 dot products scaled by d_x * d_w into Float32).
- Bias conventions (when bias != nil, shape [N]): Floating-point bias (matching x's float DType when XQuantization == nil, or Float32/Float16/BFloat16 when XQuantization != nil) is already in real units and is added in floating-point AFTER dequantization / (xScale * wScale) rescaling and BEFORE options.Activation / options.OutputQuantization. Int32 bias (valid only for QuantLinear XQuantization when neither XQuantization.Scale nor WeightQuantization.Scale is sub-blocked along K) is pre-quantized at scale xScale * wScale[n] (i.e. bias_int32[n] = round(bias_float[n] / (xScale * wScale[n]))) and is added directly to the Int32 accumulator BEFORE converting to Float32 and multiplying by xScale * wScale: z[m, n] = float32(acc_int32[m, n] + bias[n]) * (xScale[m] * wScale[n]).
- Optional output quantization (options.OutputQuantization != nil): re-quantizes the post-activation float output to Int8 or Uint8.
Inputs:
- x: [batch..., K] floating-point (when XQuantization == nil) or quantized integer/block tensor ([batch..., K] Int8/Uint8 for QuantLinear, [batch..., bytesPerRowX] Uint8 for QuantGGML).
- weight: [K, N] (DenseLayoutInputOutputs) or [N, K] (DenseLayoutOutputsInput) with DType Int2/Uint2/Int4/Uint4/Int8/Uint8 for QuantLinear/QuantNF4; or [N, bytesPerRow] Uint8 for QuantGGML (requires DenseLayoutOutputsInput, bytesPerRow = (K / valuesPerBlock) * bytesPerBlock).
- bias: optional [N] tensor (nil for no bias); floating-point (added after dequantization/rescaling) or Int32 (added to the Int32 accumulator before xScale * wScale rescaling when XQuantization uses QuantLinear without K sub-blocking), applied before options.Activation and options.OutputQuantization.
- options: FusedQuantizedDenseConfig (WeightQuantization must not be nil).
Note: Like FusedDense, ActivationSwiGLU is not supported here because it halves the output dimension; emit FusedQuantizedDense with ActivationNone followed by FusedActivation(ActivationSwiGLU).
Migration note: quantization, layout, and activation options are grouped in FusedQuantizedDenseConfig, QuantGGML weights require WeightLayout = DenseLayoutOutputsInput, scalar [] and 1D [N] scales no longer need [K, NumBlocks] broadcasts, and QuantLinear ZeroPoint uses the standard pre-scale convention real = (float(q) - float(zp)) * scale (legacy additive offsets convert via zero_point = -offset / scale).
func (Function) FusedQuantizedDenseVJP ¶ added in v0.1.29
func (Function) FusedRoPE ¶ added in v0.1.37
func (f Function) FusedRoPE(x compute.Value, cos compute.Value, sin compute.Value, config compute.FusedRoPEConfig) (compute.Value, error)
FusedRoPE applies Rotary Position Embeddings (RoPE) to x using pre-computed cos and sin frequency tables.
Inputs:
- x: floating-point tensor (Float32, Float64, Float16, or BFloat16) of rank >= 2, shaped [..., seqLen, ..., headDim], where config.SeqAxis identifies the sequence axis and the last axis is the feature/head dimension.
- cos, sin: floating-point tensors with matching shape and dtype equal to x's dtype (or Float32 when x is Float16/BFloat16). Supported shapes:
- 2D: [seqLen, rotaryHalfDim] (broadcast across all batch and head axes of x).
- (seqAxis+2)D: [b_0, ..., b_{seqAxis-1}, seqLen, rotaryHalfDim] (batched positions).
- Full rank (x.Rank()): [d_0, ..., d_{rank-2}, rotaryHalfDim] with size-1 broadcast axes.
Rotation math for each pair (x1, x2) in [config.DimStart : config.DimStart + 2*rotaryHalfDim]:
- Forward (config.Inverse == false): y1 = x1*cos - x2*sin y2 = x1*sin + x2*cos
- Inverse (config.Inverse == true): y1 = x1*cos + x2*sin y2 = -x1*sin + x2*cos
Elements outside [config.DimStart : config.DimStart + 2*rotaryHalfDim] along the last axis are copied through unchanged (partial RoPE). For Float16/BFloat16 inputs, rotation arithmetic is performed in Float32 before rounding back to x's dtype.
Output: tensor with the same shape and dtype as x.
func (Function) FusedScaledDotProductAttention ¶
func (Function) FusedScaledDotProductAttentionVJP ¶
func (Function) FusedSoftmax ¶
FusedSoftmax computes softmax along the specified axis.
Supported dtypes include Float32, Float64, Float16, and BFloat16 (backends that do not support a given dtype return ErrNotImplemented). The output preserves x's shape and dtype. For half-precision inputs (Float16, BFloat16), internal max-subtraction, exponentials, summation, and normalization are performed in Float32 precision to avoid overflow/underflow before rounding back to x's dtype.
Note: unlike the generic softmax in GoMLX's graph package, the fused softmax only accepts one axis. The axis must be non-negative (the caller normalizes negative indices before calling).
func (Function) Gather ¶
func (f Function) Gather(operand compute.Value, startIndices compute.Value, indexVectorAxis int, offsetOutputAxes []int, collapsedSliceAxes []int, startIndexMap []int, sliceSizes []int, indicesAreSorted bool) (compute.Value, error)
Gather is a powerful but cumbersome Gather operation offered by XLA. Full details in https://www.tensorflow.org/xla/operation_semantics#gather or in https://openxla.org/stablehlo/spec#gather (StableHLO also adds batch axes).
The output of Gather has the same DType of the operand, from where we are pulling the data.
Its output shape will be composed of 2 parts:
- Batch axes: they come from the axes of startIndices, except the "indexVectorAxis" (usually the last) that is used as the indices into the operand. (*)
- "Offset axes": these are axes that come from the operand, the sizes given by sliceSizes. Notice that if sliceSizes for an axis is 1, and that axis is present in the collapsedSliceAxes list, this axis gets omitted in the output.
So in general output.Rank() = startIndices.Rank() - 1 + len(offsetAxes).
(*) One exception is if indexVectorAxis == startIndices.Rank(), in which case we assume there is an extra implicit axis in startIndices of size 1, in which case output.Rank() = startIndices.Rank() + len(offsetAxes).
Arguments:
- operand: the values from where we are gathering. The output DType will follow the operand one.
- startIndices: are the indices we want to gather. The axis pointed by indexVector lists the indices of the slice to be gathered in the operand array (their values are mapped to the axis in the operand according to startIndexMap). All other axes are "batch dimensions" and they will have equivalent axes (same dimensions) in the output.
- indexVectorAxis: which of the axis in startIndices is collected and used as the start index for slices to be gathered in the operand. It is typically the last axis of startIndices, so startIndices.Shape.Rank()-1. There is a special case where indexVectorAxis == startIndices.Rank() in which case we assume there is an extra virtual axis in startIndices of size 1, in which case output.Rank() = startIndices.Rank() + len(offsetAxes).
- offsetOutputAxes: _output_ axes (not the operand's) that will hold the "offset slices", slices that are not collapsed. It points in which position (axis) in the output these slices should show up. The len(offsetOutputAxes) must match the dimension of indexVectorAxis (== startIndices.Dimensions[indexVectorAxis]). Notice all axes in the operand will either become an "offset axis" in the output, of optionally collapsed (or "squeezed") in the output, if included in collapsedSliceAxes. The axes in the output (given in offsetAxes) to the axes in the operand (the axes not present in collapsedSliceAxes) sequentially. One must have Rank(operand) == len(collapsedSliceAxes) + len(offsetAxes).
- collapsedSliceAxes: _operand_ axes (for which sliceSizes are 1) not to be included in the output. One must have sliceSizes[collapsedSliceAxes[i]] == 1 for all i. Also, one must have Rank(operand) == len(collapsedSliceAxes) + len(offsetOutputAxes).
- startIndexMap: this maps which value in startIndices is used for which axis in the operand, select the slice to be gathered. Notice len(startIndexMap) must match the startIndices.Dimensions[indexVectorAxis]. Also, len(startIndexMap) == len(offsetOutputAxes) -- offsetOutputAxes maps the same axes in the output. E.g.: if startIndices.shape=(2, 3), indexVectorAxis=1, and operand.rank=4 and startIndexMap=[]int{0, 1, 2}, this means each row of the startIndices will point to the first 3 axes (0,1 and 2) in the operand. In many cases this is [0, 1, 2, ..., operand.Shape.Rank()-1], that is, each "index vector" fully defines an element on the operand. In some this is only a prefix of the operand's rank. For those axes in the operand not explicitly set (so if len(startIndexMap) < operand.Rank()), the corresponding axis start index is considered to be 0, and one sets the sliceSizes to take the slice one wants (typically the full slice).
- sliceSizes: a size for each operand's axis, so len(sliceSize) = operand.Rank(). once the start index from where to gather is resolved, this defines how much data in each axis to gather. Constraints: sliceSizes[collapsedSliceAxes[i]] == 1, for all i.
- indicesAreSorted: can be set to true if it's guaranteed that startIndices are sorted (in ascending order, after scattering its values according to start_index_map) by the user. This allows for some optimizations in some platforms.
Out-of-bound (and negative) indices <i> are adjusted with max(min(<i>, axisDimension-1), 0), meaning they are taken from the border of the axes.
Dynamic shapes: Batch axes (from startIndices) and offset axes (from operand) preserve their names in the output. If an offset axis is partially sliced (sliceSize != operand dimension), its name is dropped.
Packed sub-byte dtypes (Int4, Uint4, Int2, Uint2, Int1, Uint1) are not supported because arbitrary slices may not be byte-aligned; use [FusedOps.QuantizedGather] for row lookups on sub-byte tables, or [StandardOps.Bitcast] to Uint8 (or [StandardOps.ConvertDType]) first.
TODO: Add batch support: operandBatchingAxes and startIndicesBatchingAxes.
func (Function) GreaterOrEqual ¶
GreaterOrEqual performs element-wise comparison, returns boolean results with the same dimensions as input.
func (Function) GreaterOrEqualTotalOrder ¶
func (f Function) GreaterOrEqualTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
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 (Function) GreaterThan ¶
GreaterThan performs element-wise comparison, returns boolean results with the same dimensions as input.
func (Function) GreaterThanTotalOrder ¶
func (f Function) GreaterThanTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
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 (Function) Imag ¶
Imag returns the imaginary part of a complex number. It returns 0 if the x is a float number.
func (Function) 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]].
func (Function) 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 (Function) IsNaN ¶
IsNaN tests whether each element of operand is NaN, i.e., if it is not a finite number.
func (Function) LessOrEqual ¶
LessOrEqual performs element-wise comparison, returns boolean results with the same dimensions as input.
func (Function) LessOrEqualTotalOrder ¶
func (f Function) LessOrEqualTotalOrder(lhs compute.Value, rhs compute.Value) (compute.Value, error)
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 (Function) LessThan ¶
LessThan performs element-wise comparison, returns boolean results with the same dimensions as input.
func (Function) 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 (Function) LogicalAnd ¶
LogicalAnd returns the element-wise logical AND operation.
func (Function) LogicalNot ¶
LogicalNot returns the Op that represents the output of the corresponding operation.
func (Function) LogicalXor ¶
LogicalXor returns the element-wise logical XOR operator.
func (Function) Logistic ¶
Logistic returns the element-wise expression 1/(1+exp(-x)). Also known as the Sigmoid function.
func (Function) Mul ¶
Mul returns the element-wise multiplication of the two values. Standard broadcasting rules apply (see documentation).
func (Function) NonZero ¶ added in v0.1.29
NonZero returns row-major coordinates of nonzero elements as an int64 tensor [count, operand rank]. Options:
- cfg.Transpose: it returns the non-zero shaped like [operand rank, count].
- CountAxisName: name of the data-dependent count axis. If left empty, an automatically generated unique name will be chosen.
func (Function) NotEqual ¶
NotEqual performs element-wise inequality check, returns boolean results with the same dimensions as input.
func (Function) 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 (Function) OptimizationBarrier ¶
func (Function) Pad ¶
func (f Function) Pad(x compute.Value, fillValue compute.Value, axesConfig ...compute.PadAxis) (compute.Value, error)
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.
For each axis i:
- `Interior` elements of `fillValue` are first inserted between consecutive elements along the axis (only when `x.Dimensions[i] > 1`). `Interior` cannot be negative (`Interior >= 0`).
- `Start` and `End` specify padding at the start and end of the axis. They can be negative, in which case elements are truncated (cropped) from the start or end of the axis (after interior padding is applied).
- The resulting dimension size for axis i is: `output.Dimensions[i] = x.Dimensions[i] + max(x.Dimensions[i]-1, 0)*Interior + Start + End` which must be non-negative (`>= 0`).
Examples (for 1D `x = [1, 2, 3]` and `fillValue = 0`):
- `PadAxis{Start: 1, End: 2}` -> `[0, 1, 2, 3, 0, 0]` (shape `[6]`)
- `PadAxis{Interior: 1}` -> `[1, 0, 2, 0, 3]` (shape `[5]`)
- `PadAxis{Start: -1, End: -1}` -> `[2]` (shape `[1]`)
- `PadAxis{Start: -1, End: 1, Interior: 1}` -> `[0, 2, 0, 3, 0]` (shape `[5]`)
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 (Function) QuantizedGather ¶ added in v0.1.31
func (f Function) QuantizedGather(x compute.Value, indices compute.Value, xQuantization *compute.Quantization) (compute.Value, error)
QuantizedGather performs a quantized row gather (embedding lookup) with on-the-fly unpacking / dequantization.
This is the quantized analogue of row-level Gather (inspired by llama.cpp's ggml_get_rows) and is also the supported way to gather rows from packed sub-byte tables (Int2/Uint2/Int4/Uint4), which StandardOps.Gather does not support directly.
Supported modes:
- xQuantization == nil or QuantNone: gathers rows from Int2/Uint2/Int4/Uint4 (or Int8/Uint8) x and unpacks them losslessly into Int8 (for signed Int2/Int4/Int8) or Uint8 (for unsigned Uint2/Uint4/Uint8) without scaling. When PackedDType is set on QuantNone/QuantLinear/QuantNF4, x may be stored bit-packed in Uint8 with shape [vocabSize, K / ValuesPerStorageUnit] and logical element dtype PackedDType.
- QuantGGML: x is [vocabSize, bytesPerRow] Uint8 with native GGML block layout; output is Float32.
- QuantLinear: x is [vocabSize, K] Int2/Uint2/Int4/Uint4/Int8/Uint8 (or [vocabSize, K/vpb] Uint8 with PackedDType) with xQuantization.Scale (Float32/Float16/BFloat16; scalar, 1D [vocabSize], or 2D block-wise) and optional xQuantization.ZeroPoint; output matches Scale's DType.
- QuantNF4: x is [vocabSize, K] Int4/Uint4/Int8/Uint8 (or [vocabSize, K/2] Uint8 with PackedDType) with xQuantization.Scale (Float32/Float16/BFloat16); output matches Scale's DType.
Inputs:
- x: [vocabSize, bytesPerRow] Uint8 (QuantGGML), [vocabSize, K/vpb] Uint8 (when PackedDType is set), or [vocabSize, K] quantized integer (xQuantization == nil, QuantNone, QuantLinear, or QuantNF4).
- indices: integer tensor with last dimension = 1 (same as Gather convention). For embeddings: [batch, seqLen, 1].
- xQuantization: describes how to unpack/dequantize the rows of x, or nil to gather and unpack sub-byte/8-bit integer elements directly to Int8/Uint8.
Output: tensor with shape [batch..., K] (Float32 for QuantGGML, Scale.DType for QuantLinear/QuantNF4, or Int8/Uint8 when xQuantization == nil or QuantNone).
For embeddings with indices [batch, seqLen, 1]: output is [batch, seqLen, K].
func (Function) RNGBitGenerator ¶
func (Function) Real ¶
Real return the real part of a complex number. It returns x if the x is a float number.
func (Function) ReduceBitwiseAnd ¶
ReduceBitwiseAnd reduces x over the axes selected, performing a BitwiseAnd on the slices reduced.
The returned result rank is decreased by len(axes).
If no axes are given, it reduces the full array.
func (Function) ReduceBitwiseOr ¶
ReduceBitwiseOr reduces x over the axes selected, performing a BitwiseOr on the slices reduced.
The returned result rank is decreased by len(axes).
If no axes are given, it reduces the full array.
func (Function) ReduceBitwiseXor ¶
ReduceBitwiseXor reduces x over the axes selected, performing a BitwiseXor on the slices reduced.
The returned result rank is decreased by len(axes).
If no axes are given, it reduces the full array.
func (Function) ReduceLogicalAnd ¶
ReduceLogicalAnd reduces x over the axes selected, performing a LogicalAnd on the slices reduced.
The returned result rank is decreased by len(axes).
If no axes are given, it reduces the full array.
func (Function) ReduceLogicalOr ¶
ReduceLogicalOr reduces x over the axes selected, performing a LogicalOr on the slices reduced.
The returned result rank is decreased by len(axes).
If no axes are given, it reduces the full array.
func (Function) ReduceLogicalXor ¶
ReduceLogicalXor reduces x over the axes selected, performing a LogicalXor on the slices reduced.
The returned result rank is decreased by len(axes).
If no axes are given, it reduces the full array.
func (Function) ReduceMax ¶
ReduceMax reduces x over the axes selected, taking the Max value of the slices reduced.
The returned result rank is decreased by len(axes).
If no axes are given, it reduces the full array.
func (Function) ReduceMin ¶
ReduceMin reduces x over the axes selected, taking the Min value of the slices reduced.
The returned result rank is decreased by len(axes).
If no axes are given, it reduces the full array.
func (Function) ReduceProduct ¶
ReduceProduct reduces x over the axes selected, taking the product of the slices reduced.
The returned result rank is decreased by len(axes).
If no axes are given, it reduces the full array.
func (Function) ReduceSum ¶
ReduceSum reduces x over the axes selected, taking the sum of the slices reduced.
The returned result rank is decreased by len(axes).
If no axes are given, it reduces the full array.
func (Function) ReduceWindow ¶
func (Function) 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 (Function) Reshape ¶
Reshape reshapes x to the new dimensions. Total size cannot change, it's just a "reinterpretation" of the same flat data. The dtype remains the same, see ConvertDType to actually convert the values.
This version of reshape doesn't support reshaping dynamic dimensions (axes with shapes.DynamicDim). Any dynamic dimensions in the input must be matched by dynamic dimensions in the output, and their axis names are preserved. If new axes are created, the dynamic axis in the input x and dimensions are matched in order.
func (Function) 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 (Function) Round ¶
Round returns the Op that represents the output of the corresponding operation. This operation rounds to the nearest even.
func (Function) Rsqrt ¶
Rsqrt returns the element-wise reciprocal of square root operation 1/sqrt(x).
func (Function) ScatterMax ¶
func (f Function) ScatterMax(operand compute.Value, scatterIndices compute.Value, updates compute.Value, indexVectorAxis int, updateWindowAxes []int, insertedWindowAxes []int, scatterAxesToOperandAxes []int, indicesAreSorted bool, uniqueIndices bool) (compute.Value, error)
ScatterMax scatter values from updates pointed by scatterIndices to operand, by taking the Max.
Dynamic shapes: Operand and updates shapes can have dynamic dimensions. Currently operations that change the size of dynamic axes are not supported.
func (Function) ScatterMin ¶
func (f Function) ScatterMin(operand compute.Value, scatterIndices compute.Value, updates compute.Value, indexVectorAxis int, updateWindowAxes []int, insertedWindowAxes []int, scatterAxesToOperandAxes []int, indicesAreSorted bool, uniqueIndices bool) (compute.Value, error)
ScatterMin scatter values from updates pointed by scatterIndices to operand, by taking the Min.
Dynamic shapes: Operand and updates shapes can have dynamic dimensions. Currently operations that change the size of dynamic axes are not supported.
func (Function) ScatterSum ¶
func (f Function) ScatterSum(operand compute.Value, scatterIndices compute.Value, updates compute.Value, indexVectorAxis int, updateWindowAxes []int, insertedWindowAxes []int, scatterAxesToOperandAxes []int, indicesAreSorted bool, uniqueIndices bool) (compute.Value, error)
ScatterSum values from updates pointed by scatterIndices to operand.
Dynamic shapes: Operand and updates shapes can have dynamic dimensions. Currently operations that change the size of dynamic axes are not supported.
func (Function) SchedulingBarrier ¶
func (f Function) SchedulingBarrier(operand compute.Value, dependencies ...compute.Value) (compute.Value, error)
SchedulingBarrier introduces a scheduling barrier. Returned value is identity to the operand, but it is guaranteed to depend on all the dependencies.
func (Function) SelectAndScatterMax ¶
func (f Function) SelectAndScatterMax(operand compute.Value, source compute.Value, windowDimensions []int, windowStrides []int, paddings [][2]int) (compute.Value, error)
SelectAndScatterMax runs windows (similar to ReduceWindow) over the operand, selects values to update the output (like ScatterAdd) It selects the values in the window such that it works as reverse for a PoolMax operation. See details in https://openxla.org/xla/operation_semantics#selectandscatter
func (Function) SelectAndScatterMin ¶
func (f Function) SelectAndScatterMin(operand compute.Value, source compute.Value, windowDimensions []int, windowStrides []int, paddings [][2]int) (compute.Value, error)
SelectAndScatterMin runs windows (similar to ReduceWindow) over the operand, selects values to update the output (like ScatterAdd) It selects the values in the window such that it works as reverse for a PoolMin operation. See details in https://openxla.org/xla/operation_semantics#selectandscatter
func (Function) ShiftLeft ¶
ShiftLeft n bits. It implicitly preserves the sign bit if there is no overflow. So ShiftLeft(-1, 1) = -2.
func (Function) ShiftRightArithmetic ¶
ShiftRightArithmetic shifts right by n bits, preserving the sign bit. So ShiftRight(-2, 1) = -1.
func (Function) ShiftRightLogical ¶
ShiftRightLogical shifts right by n bits, destroying the sign bit.
func (Function) Sign ¶
Sign returns element-wise +1, +/-0 or -1 depending on the sign of x. It returns NaN if the input is NaN.
func (Function) Slice ¶
func (f Function) Slice(x compute.Value, starts []int, limits []int, strides []int) (compute.Value, error)
Slice extracts a subarray from the input array.
The subarray is of the same rank as the input and contains the values inside a bounding box within the input array where the dimensions and indices of the bounding box are given as arguments to the slice operation.
The strides set the input stride of the slice in each axis and must be >= 1. It is optional, and if missing, it is assumed to be 1 for every dimension.
The limits are defined on the x axes, and they are exclusive upper bounds, i.e. the slice includes elements from starts up to (but not including) limits.
Examples:
Slice(x={0, 1, 2, 3, 4}, starts={2}, limits={4}, strides=nil) -> {2, 3}
Slice(x={0, 1, 2, 3, 4}, starts={2}, limits={5}, strides={2}) -> {2, 4}
Dynamic shapes: A limit index can be set to `shapes.DynamicDim` (-1) to indicate the end of the dimension. Partial slices of dynamic axes are currently not supported if they result in a dynamic-sized output (requires axis expressions). Slicing a dynamic axis with static bounds (e.g. from 0 to 10) results in a static output size (e.g. 10).
Packed sub-byte dtypes (Int4, Uint4, Int2, Uint2, Int1, Uint1) are not supported because arbitrary slices may not be byte-aligned; [StandardOps.Bitcast] to Uint8 or [StandardOps.ConvertDType] first.
func (Function) Sqrt ¶
Sqrt returns the Op that represents the output of the corresponding operation.
func (Function) Sub ¶
Sub returns the element-wise subtraction of the two values. Standard broadcasting rules apply (see documentation).
func (Function) Tanh ¶
Tanh returns the Op that represents the output of the corresponding operation.
func (Function) Transpose ¶
Transpose axes of x. There should be one value in permutations for each axis in x. The output will have: output.Shape.Dimension[ii] = x.Shape.Dimension[permutations[i]].
func (Function) Where ¶
func (f Function) Where(condition compute.Value, onTrue compute.Value, onFalse compute.Value) (compute.Value, error)
Where takes element-wise values from onTrue or onFalse depending on the value of the condition (must be boolean).
The condition must be boolean, and onTrue and onFalse must have the same dtype.
Standard implicit broadcasting rules apply across all three operands:
- Scalar operands are implicitly broadcast to the shape of the other operands.
- Non-scalar operands must have the same rank, and for each axis, their dimensions must either match or be statically 1. A static dimension of 1 broadcasts to the other non-1 dimension (including 0, yielding an empty axis of size 0).
- Unknown/dynamic dimensions cannot be implicitly paired with a non-1 static dimension; reshape the dynamic operand via DynamicReshape (to assert the static dimension) or broadcast via DynamicBroadcastInDim where needed.