notimplemented

package
v0.1.37 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: Apache-2.0 Imports: 6 Imported by: 3 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Constants

This section is empty.

Variables

View Source
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) Builder

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

Builder creates a new builder.

func (*Backend) Capabilities

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

Capabilities returns empty capabilities.

func (*Backend) Description

func (b *Backend) Description() string

Description is a longer description of the Backend.

func (*Backend) DeviceDescription

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

DeviceDescription returns a description of the device.

func (*Backend) Finalize

func (b *Backend) Finalize()

Finalize does nothing for this dummy backend.

func (*Backend) HasSharedBuffers

func (b *Backend) HasSharedBuffers() bool

HasSharedBuffers returns false.

func (*Backend) IsFinalized

func (b *Backend) IsFinalized() bool

IsFinalized always returns false for this dummy backend.

func (*Backend) Name

func (b *Backend) Name() string

Name returns the short name of the 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

func (b *Backend) NumDevices() int

NumDevices returns 1 as the number of devices available.

func (*Backend) String

func (b *Backend) String() string

String returns the same as Name.

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) Compile

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

func (Builder) DeviceAssignment

func (b Builder) DeviceAssignment(devices ...compute.DeviceNum) error

DeviceAssignment returns nil if it's an assignment to device #0. Otherwise, it returns a non-implemented error.

func (Builder) DistributedAutoSharding

func (b Builder) DistributedAutoSharding(meshes ...compute.Mesh) error

func (Builder) DistributedSPMD

func (b Builder) DistributedSPMD(numDevices int) error

func (Builder) Main

func (b Builder) Main() compute.Function

func (Builder) Name

func (b Builder) Name() string

func (Builder) NewFunction

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

func (Builder) OpShape

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

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) Abs

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

Abs returns the Op that represents the output of the corresponding operation.

func (Function) Add

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

Add returns the element-wise sum of the two values. Standard broadcasting rules apply (see documentation).

func (Function) AllReduce

func (f Function) AllReduce(inputs []compute.Value, reduceOp compute.ReduceOpType, replicaGroups [][]int) (
	[]compute.Value, error)

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

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

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 (f Function) BatchNormForInference(operand, scale, offset, mean, variance compute.Value, epsilon float32, axis int) (
	compute.Value, error)

func (Function) BatchNormForTraining

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

func (Function) BatchNormGradient

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

func (Function) BitCount

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

BitCount returns the number of bits that are set to one. Also known as Population Count ("Popcnt") or Hamming Weight.

func (Function) Bitcast

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

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

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

BitwiseAnd returns the element-wise bitwise AND operation.

func (Function) BitwiseNot

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

BitwiseNot returns the element-wise bitwise AND operation.

func (Function) BitwiseOr

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

BitwiseOr returns the element-wise bitwise OR operation.

func (Function) BitwiseXor

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

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) Builder

func (f Function) Builder() compute.Builder

func (Function) Call

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

func (Function) Ceil

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

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) Closure

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

func (Function) Clz

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

Clz returns element-wise the "count leading zeros" bits of input node x -- for integer values.

func (Function) Complex

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

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

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

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) Conj

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

Conj returns the conjugate of a complex number. E.g: Conj(1+3i) = 1-3i

func (Function) Constant

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

func (Function) ConstantFromBuffer added in v0.1.30

func (f Function) ConstantFromBuffer(buf compute.Buffer, donate bool) (compute.Value, error)

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

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

ConvertDType of x to dtype.

func (Function) Cos

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

Cos returns the Op that represents the output of the corresponding operation.

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

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

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

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

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

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

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

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

Equal performs element-wise equality check, returns boolean results with the same dimensions as input.

func (Function) EqualTotalOrder

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

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

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

Erf returns the "error function", defined as erf(x) = 2/Pi * \int_{0}^{x}{e^{-t^2}dt}.

func (Function) Exp

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

Exp returns the Op that represents the output of the corresponding operation.

func (Function) Expm1

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

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

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

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 (f Function) FusedAttentionQKVProjection(x, wQKV, biasQ, biasK, biasV compute.Value, queryDim, keyValueDim int) (query, key, value compute.Value, err error)

func (Function) FusedDense

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

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 (f Function) FusedDenseVJP(x, weight, bias, y, dOutput compute.Value, options compute.DenseConfig) (dx, dWeight, dBias compute.Value, err error)

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 (f Function) FusedLayerNormVJP(x, dOutput, gamma, beta compute.Value, config compute.FusedLayerNormConfig) (dx, dGamma, dBeta compute.Value, err error)

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 (f Function) FusedQuantizedDenseVJP(x, weight, bias, y, dOutput compute.Value, options compute.FusedQuantizedDenseConfig) (dx, dBias compute.Value, err error)

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 (f Function) FusedScaledDotProductAttention(query, key, value compute.Value, axesLayout compute.AttentionAxesLayout, options *compute.ScaledDotProductAttentionConfig) (output compute.Value, statesForVJP []compute.Value, err error)

func (Function) FusedScaledDotProductAttentionVJP

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

func (Function) FusedSoftmax

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

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) FusedTopK added in v0.1.29

func (f Function) FusedTopK(operand compute.Value, k int, cfg compute.FusedTopKConfig) (compute.Value, compute.Value, error)

func (Function) Gather

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

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

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

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

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

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) Identity

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

func (Function) If

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

func (Function) Imag

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

Imag returns the imaginary part of a complex number. It returns 0 if the x is a float number.

func (Function) Iota

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

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

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

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

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

IsNaN tests whether each element of operand is NaN, i.e., if it is not a finite number.

func (Function) LessOrEqual

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

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

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

LessThan performs element-wise comparison, returns boolean results with the same dimensions as input.

func (Function) LessThanTotalOrder

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

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) Log

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

Log returns the Op that represents the output of the corresponding operation.

func (Function) Log1p

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

Log1p returns the expression log(x+1).

func (Function) LogicalAnd

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

LogicalAnd returns the element-wise logical AND operation.

func (Function) LogicalNot

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

LogicalNot returns the Op that represents the output of the corresponding operation.

func (Function) LogicalOr

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

LogicalOr returns the element-wise logical OR operation.

func (Function) LogicalXor

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

LogicalXor returns the element-wise logical XOR operator.

func (Function) Logistic

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

Logistic returns the element-wise expression 1/(1+exp(-x)). Also known as the Sigmoid function.

func (Function) Max

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

Max returns the element-wise highest value among the two.

func (Function) Min

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

Min returns the element-wise smallest value among the two.

func (Function) Mul

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

Mul returns the element-wise multiplication of the two values. Standard broadcasting rules apply (see documentation).

func (Function) Name

func (f Function) Name() string

func (Function) Neg

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

Neg returns the Op that represents the output of the corresponding operation.

func (Function) NonZero added in v0.1.29

func (f Function) NonZero(operand compute.Value, cfg compute.NonZeroConfig) (compute.Value, error)

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

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

NotEqual performs element-wise inequality check, returns boolean results with the same dimensions as input.

func (Function) NotEqualTotalOrder

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

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 (f Function) OptimizationBarrier(operands ...compute.Value) ([]compute.Value, error)

func (Function) Pad

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

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) Parameter

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

func (Function) Parent

func (f Function) Parent() compute.Function

func (Function) Pow

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

Pow returns the Op that represents the output of the corresponding operation.

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 (f Function) RNGBitGenerator(state compute.Value, shape shapes.Shape, algorithm compute.RNGAlgorithm) (newState, values compute.Value, err error)

func (Function) Real

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

Real return the real part of a complex number. It returns x if the x is a float number.

func (Function) ReduceBitwiseAnd

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 (f Function) ReduceWindow(input compute.Value, reductionType compute.ReduceOpType,
	windowDimensions, strides, inputDilations, windowDilations []int, paddings [][2]int) (compute.Value, error)

func (Function) Rem

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

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

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

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) Return

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

func (Function) Reverse

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

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

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

Round returns the Op that represents the output of the corresponding operation. This operation rounds to the nearest even.

func (Function) Rsqrt

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

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) Shape

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

func (Function) ShiftLeft

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

ShiftLeft n bits. It implicitly preserves the sign bit if there is no overflow. So ShiftLeft(-1, 1) = -2.

func (Function) ShiftRightArithmetic

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

ShiftRightArithmetic shifts right by n bits, preserving the sign bit. So ShiftRight(-2, 1) = -1.

func (Function) ShiftRightLogical

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

ShiftRightLogical shifts right by n bits, destroying the sign bit.

func (Function) Sign

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

Sign returns element-wise +1, +/-0 or -1 depending on the sign of x. It returns NaN if the input is NaN.

func (Function) Sin

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

Sin returns the Op that represents the output of the corresponding operation.

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) Sort

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

func (Function) Sqrt

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

Sqrt returns the Op that represents the output of the corresponding operation.

func (Function) Sub

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

Sub returns the element-wise subtraction of the two values. Standard broadcasting rules apply (see documentation).

func (Function) Tanh

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

Tanh returns the Op that represents the output of the corresponding operation.

func (Function) Transpose

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

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.

func (Function) While

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

Jump to

Keyboard shortcuts

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