Documentation
¶
Overview ¶
Package compute defines abstractions for building, compiling, transferring data (buffers) and executing machine learning computation graphs in GoMLX.
The core interface is called Backend, and it is built around four core interfaces:
- DataInterface: Manages tensor data storage, memory allocation, and the transfer of data buffers to and from the backend. It abstracts the complexities of different hardware accelerators (e.g., CPU, GPU, TPU) and their respective memory models.
- Builder: Provides the API for constructing computation graphs. A graph is typically composed of a "main" function, potentially alongside other helper functions.
- Function: Represents a discrete sub-graph or logical unit of operations within a larger computation.
- Executable: Represents a compiled, ready-to-run computation graph that can be invoked with inputs on the target backend, yielding the resulting data buffers.
While conceptually inspired by OpenXLA's StableHLO, the API has diverged some. It aims to be backend-agnostic to support a diverse range of execution environments (CPU, GPU, TPU, etc.) and optimisations (e.g. JIT with static shapes vs dynamic shapes but less optimization)
Backend Implementations ¶
A Backend is not required to implement every defined operation. If a backend encounters an unsupported operation, it should gracefully return an ErrNotImplemented. There is also a Backend.Capabilities method that returns what the backend supports (e.g. supported dtypes, ops, or if it supports dynamic shapes).
Computations that do not rely on the missing operation work normally. In some cases, the computation can handle the error by using alternative fallbacks, and work around missing version (the strategy used for some fused ops).
The [notimplemented] package provides a default implementation (that returns ErrNotImplemented) for all methods of Builder. It's good practice for any Backend to wrap it: it greatly simplifies the implemention of the backend, and serves for future compatibility (if new ops are created, an existing backend doesn't need to be changed, it will simply gracefully fail).
Error Messages with Stack Traces ¶
By convention errors should be wrapped with a stack trace, using (for now until we find a better one) the "github.com/pkg/errors" package.
Example:
import "github.com/pkg/errors" ... return errors.Wrapf(ErrNotImplemented, "...")
[notimplemented]: pkg.go.dev/github.com/gomlx/compute/notimplemented
Index ¶
- Constants
- Variables
- func ActivationTypeStrings() []string
- func DynamicShapesSupportStrings() []string
- func FFTTypeStrings() []string
- func IsNotImplemented(err error) bool
- func List() []string
- func OpTypeStrings() []string
- func RNGAlgorithmStrings() []string
- func ReduceOpTypeStrings() []string
- func Register(name string, constructor Constructor)
- type ActivationConfig
- type ActivationType
- type AttentionAxesLayout
- type Backend
- type Buffer
- type Builder
- type Capabilities
- func (c Capabilities) Clone() Capabilities
- func (c Capabilities) DynamicDimDTypeOrDefault() dtypes.DType
- func (c Capabilities) HasDynamicShapes() bool
- func (c Capabilities) RNGStateFromSeed(algo RNGAlgorithm, seed int64) (flat any, shape shapes.Shape, err error)
- func (c Capabilities) RNGStateShape(algo RNGAlgorithm) (shapes.Shape, error)
- func (c Capabilities) ResolveRNGAlgorithm(algo RNGAlgorithm) RNGAlgorithm
- func (c Capabilities) SupportsRNG(algo RNGAlgorithm) bool
- type CollectiveOps
- type Constructor
- type ConvolveAxesConfig
- type CumSumOptions
- type DataInterface
- type DenseConfig
- type DenseLayout
- type DeviceNum
- type DotGeneralConfig
- type DynamicDimensionSpec
- type DynamicOps
- type DynamicPadAxis
- type DynamicShapesSupport
- type Executable
- type FFTType
- type Function
- type FusedOps
- type FusedQuantizedDenseConfig
- type FusedTopKConfig
- type GGMLQuantType
- type Mesh
- type NonZeroConfig
- type OpType
- type PadAxis
- type Quantization
- type QuantizationScheme
- type RNGAlgorithm
- type ReduceOpType
- type ScaledDotProductAttentionConfig
- type ShardingSpec
- type StandardOps
- type Value
Constants ¶
const ActivationSwish = ActivationSilu
ActivationSwish is an alias for ActivationSilu.
const ConfigEnvVar = "GOMLX_BACKEND"
ConfigEnvVar is the name of the environment variable with the default backend configuration to use: "GOMLX_BACKEND".
The format of the configuration is "<backend_name>:<backend_configuration>". The "<backend_name>" is the name of a registered backend (e.g.: "xla") and "<backend_configuration>" is backend-specific (e.g.: for xla backend, it is the pjrt plugin name).
const MainName = "main"
Main function name, created by Builder.Main().
Variables ¶
var DefaultConfig = "xla"
DefaultConfig is the name of the default backend configuration to use if specified.
See NewWithConfig for the format of the configuration string.
var ErrNotImplemented = stderrors.New("op not implemented")
ErrNotImplemented indicates an op is not implemented (typically a fused op, but normal ops may return this as well) for the given configuration (e.g. unsupported dtype or backend). Backends should wrap this error so InternalFusedOpCaller can distinguish "not supported" from genuine bugs and fall back to the decomposed implementation.
It doesn't contain a stack, attach a stack to with with errors.Wrapf(ErrNotImplemented, "...") when using it.
var IQ4NLLookupTable = [16]float32{
-127, -104, -83, -65, -49, -35, -22, -10,
1, 13, 25, 38, 53, 69, 89, 113,
}
IQ4NLLookupTable contains the 16 fixed IQ4_NL non-linear dequantization values. These map 4-bit nibble indices to pre-normalization integer values (not final floats). Final dequantized value = per-block scale * IQ4NLLookupTable[nibble]. Values from llama.cpp's kvalues_iq4nl.
var NF4LookupTable = [16]float32{
-1.0, -0.6961928009986877, -0.5250730514526367, -0.39491748809814453,
-0.28444138169288635, -0.18477343022823334, -0.09105003625154495, 0,
0.07958029955625534, 0.16093020141124725, 0.24611230194568634, 0.33791524171829224,
0.44070982933044434, 0.5626170039176941, 0.7229568362236023, 1.0,
}
NF4LookupTable contains the 16 fixed QLoRA NormalFloat4 dequantization values. Used by both the fused executor and the decomposed graph-level fallback.
var RNGStateShape = shapes.Make(dtypes.Uint64, 3) //nolint:mnd // This is a constant.
RNGStateShape is the legacy Philox state shape ([3]uint64).
Deprecated: use [RNGPhilox.StateShape] or Capabilities.RNGStateShape instead.
Functions ¶
func ActivationTypeStrings ¶ added in v0.1.9
func ActivationTypeStrings() []string
ActivationTypeStrings returns a slice of all String values of the enum
func DynamicShapesSupportStrings ¶ added in v0.1.5
func DynamicShapesSupportStrings() []string
DynamicShapesSupportStrings returns a slice of all String values of the enum
func FFTTypeStrings ¶
func FFTTypeStrings() []string
FFTTypeStrings returns a slice of all String values of the enum
func IsNotImplemented ¶
IsNotImplemented checks whether the error is a ErrNotImplemented.
func OpTypeStrings ¶
func OpTypeStrings() []string
OpTypeStrings returns a slice of all String values of the enum
func RNGAlgorithmStrings ¶ added in v0.1.32
func RNGAlgorithmStrings() []string
RNGAlgorithmStrings returns a slice of all String values of the enum
func ReduceOpTypeStrings ¶
func ReduceOpTypeStrings() []string
ReduceOpTypeStrings returns a slice of all String values of the enum
func Register ¶
func Register(name string, constructor Constructor)
Register backend with the given name and a default constructor that takes as input a configuration string that is passed along to the backend constructor.
To be safe, call Register during initialization of a package.
Types ¶
type ActivationConfig ¶ added in v0.1.9
type ActivationConfig struct {
// Type of activation, see ActivationType.
Type ActivationType
}
ActivationConfig holds the configuration for activation functions. The Type is obligatory, other fields are optional and specific for activations.
type ActivationType ¶
type ActivationType int
ActivationType specifies the activation function for fused operations.
const ( // ActivationNone specifies the identity function: y = x. ActivationNone ActivationType = iota // ActivationRelu is the Rectified Linear Unit activation: // // y = max(x, 0) // // Introduced in "Rectified Linear Units Improve Restricted Boltzmann Machines" // (Vinod Nair, Geoffrey E. Hinton, ICML 2010), https://icml.cc/Conferences/2010/papers/432.pdf. ActivationRelu // ActivationSigmoid is the standard logistic sigmoid activation: // // y = 1 / (1 + exp(-x)) ActivationSigmoid // ActivationHardSigmoid is a piecewise linear approximation of the sigmoid function: // // y = max(0, min(1, 0.2*x + 0.5)) // // It is computationally cheaper on hardware without fast transcendental functions. ActivationHardSigmoid // ActivationLeakyRelu allows a small gradient when the unit is not active (x < 0): // // y = x if x >= 0; 0.3*x if x < 0 // // Here the negative slope alpha is fixed at 0.3. // // Introduced in "Rectifier Nonlinearities Improve Neural Network Acoustic Models" // (Andrew L. Maas, Awni Y. Hannun, Andrew Y. Ng, ICML 2013). ActivationLeakyRelu // ActivationSelu stands for Scaled Exponential Linear Unit: // // y = scale * x if x > 0; scale * alpha * (exp(x) - 1) if x <= 0 // // with fixed constants alpha ≈ 1.67326324 and scale ≈ 1.05070098. // // Self-normalizing neural networks induce self-normalizing properties such as // variance stabilization. // // Introduced in "Self-Normalizing Neural Networks" // (Günter Klambauer, Thomas Unterthiner, Andreas Mayr, Sepp Hochreiter, NeurIPS 2017), // https://arxiv.org/abs/1706.02515. ActivationSelu // ActivationSilu (also known as Swish) is the Sigmoid-Weighted Linear Unit: // // y = x * sigmoid(x) // // Introduced in "Gaussian Error Linear Units (GELUs)" // (Dan Hendrycks, Kevin Gimpel, 2016), https://arxiv.org/abs/1606.08415 and // "Sigmoid-Weighted Linear Units for Neural Network Function Approximation in // Reinforcement Learning" (Stefan Elfwing, Eiji Uchibe, Kenji Doya, 2017), // https://arxiv.org/abs/1702.03118, and independently discovered (and called Swish) // in "Searching for Activation Functions" // (Prajit Ramachandran, Barret Zoph, Quoc V. Le, 2017), https://arxiv.org/abs/1710.05941. ActivationSilu // ActivationHardSwish is a piecewise linear approximation of Swish: // // y = x * ReLU6(x + 3) / 6 = x * max(0, min(1, x/6 + 0.5)) // // Introduced in "Searching for MobileNetV3" // (Andrew Howard et al., ICCV 2019), https://arxiv.org/abs/1905.02244. ActivationHardSwish // ActivationTanh is the hyperbolic tangent activation: // // y = tanh(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x)) ActivationTanh // ActivationGelu computes the Gaussian Error Linear Unit activation using the exact erf formulation: // // y = x * Φ(x) = x * 0.5 * (1 + erf(x / √2)) // // Introduced in "Gaussian Error Linear Units (GELUs)" // (Dan Hendrycks, Kevin Gimpel, 2016), https://arxiv.org/abs/1606.08415. ActivationGelu // ActivationGeluApproximate computes the GELU activation using the tanh approximation: // // y = 0.5 * x * (1 + tanh(√(2/π) * (x + 0.044715 * x^3))) // // Introduced in "Gaussian Error Linear Units (GELUs)" // (Dan Hendrycks, Kevin Gimpel, 2016), https://arxiv.org/abs/1606.08415. ActivationGeluApproximate // ActivationSwiGLU applies the Swish-Gated Linear Unit activation to a pre-projected // tensor of shape [..., 2*hiddenDim], splitting the last dimension in half into gate // and value components: // // SwiGLU(x) = Swish(x_gate) * x_value // // Output has shape [..., hiddenDim]. // // Introduced in "GLU Variants Improve Transformer" // (Noam Shazeer, 2020), https://arxiv.org/abs/2002.05202. ActivationSwiGLU )
func ActivationTypeString ¶ added in v0.1.9
func ActivationTypeString(s string) (ActivationType, error)
ActivationTypeString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.
func ActivationTypeValues ¶ added in v0.1.9
func ActivationTypeValues() []ActivationType
ActivationTypeValues returns all values of the enum
func (ActivationType) IsAActivationType ¶ added in v0.1.9
func (i ActivationType) IsAActivationType() bool
IsAActivationType returns "true" if the value is listed in the enum definition. "false" otherwise
func (ActivationType) String ¶
func (i ActivationType) String() string
func (ActivationType) VJPRequiresInput ¶ added in v0.1.9
func (a ActivationType) VJPRequiresInput() bool
VJPRequiresInput indicates whether the VJP of the activation requires the forward input `x` when the forward output `y` is already available.
This indicates whether FusedDense+FusedDenseVJP can fuse the activation into a single kernel during training:
- If false: the VJP can be calculated solely from `y` and `dOutput` (i.e. `x` does not need to be preserved during the forward pass). In this case, MatMul + Bias + Activation can be fully fused during training.
- If true: the VJP requires the pre-activation input `x` (output of MatMul+Bias). In this case, the activation cannot be fully fused with the dense layer during training, and MatMul+Bias should be fused while leaving Activation as a separate node.
Derivations when y is given:
- ActivationNone: dy/dx = 1 (no inputs needed).
- ActivationRelu: dy/dx = 1 if y > 0 else 0 (since y > 0 <=> x > 0).
- ActivationSigmoid: dy/dx = y * (1 - y).
- ActivationHardSigmoid: dy/dx = 0.2 if 0 < y < 1 else 0.
- ActivationLeakyRelu: dy/dx = 1 if y >= 0 else 0.3 (since alpha=0.3 > 0 preserves sign).
- ActivationSelu: dy/dx = scale if y > 0 else y + scale*alpha.
- ActivationTanh: dy/dx = 1 - y^2.
- ActivationSilu, ActivationHardSwish, ActivationGelu, ActivationGeluApproximate, ActivationSwiGLU: require x for the derivative computation.
type AttentionAxesLayout ¶
type AttentionAxesLayout int
AttentionAxesLayout specifies the ordering of axes in 4D attention tensors.
const ( // AttentionAxesLayoutBHSD is the [batch, heads, seq, dim] layout used by PyTorch's F.scaled_dot_product_attention, // ONNX, and most inference runtimes. AttentionAxesLayoutBHSD AttentionAxesLayout = iota // AttentionAxesLayoutBSHD is the [batch, seq, heads, dim] layout used internally by MultiHeadAttention // (after Dense projections which produce [batch, seq, heads, dim]). AttentionAxesLayoutBSHD )
func (AttentionAxesLayout) HeadsAxis ¶
func (l AttentionAxesLayout) HeadsAxis() int
HeadsAxis returns the axis index for the heads dimension.
func (AttentionAxesLayout) SeqAxis ¶
func (l AttentionAxesLayout) SeqAxis() int
SeqAxis returns the axis index for the sequence dimension.
func (AttentionAxesLayout) String ¶
func (l AttentionAxesLayout) String() string
String returns the name of the layout.
type Backend ¶
type Backend interface {
// Name returns the short name of the backend. E.g.: "xla" for the Xla/PJRT plugin.
Name() string
// String returns the same as Name.
String() string
// Description is a longer description of the Backend that can be used to pretty-print.
Description() string
// NumDevices return the number of devices available for this Backend.
NumDevices() int
// DeviceDescription returns a description of the device at the given deviceNum.
DeviceDescription(deviceNum DeviceNum) string
// Capabilities returns information about what is supported by this backend.
Capabilities() Capabilities
// Builder creates a new builder used to define a newly named computation.
Builder(name string) Builder
// DataInterface is the sub-interface that defines the API to transfer Buffer to/from accelerators for the backend.
DataInterface
// Finalize releases all the associated resources immediately and makes the backend invalid.
// Any operation on a Backend after Finalize is called is undefined, except IsFinalized.
Finalize()
// IsFinalized returns true if the backend is finalized.
//
// Tensors stored on a backend may hold a reference to a finalized backend, and when being garbage collected,
// check whether it is finalized before requesting the backend to finalize its buffers.
IsFinalized() bool
}
Backend is the API that needs to be implemented by a compute backend. See package compute for more information.
func MustNew ¶
func MustNew() Backend
MustNew returns a new default Backend or panics if it fails.
The default is:
1. The environment $GOMLX_BACKEND (ConfigEnvVar) is used as a configuration if defined. 2. Next, it uses the variable DefaultConfig as the configuration. 3. The first registered backend is used with an empty configuration.
It fails if no backends were registered.
func New ¶
New returns a new default Backend or an error if it fails.
The default is:
1. The environment $GOMLX_BACKEND (ConfigEnvVar) is used as a configuration if defined. 2. Next, it uses the variable DefaultConfig as the configuration. 3. The first registered backend is used with an empty configuration.
It fails if no backends were registered.
func NewOrErr
deprecated
NewOrErr returns a new default Backend or an error if it fails.
The default is:
1. The environment $GOMLX_BACKEND (ConfigEnvVar) is used as a configuration if defined. 2. Next, it uses the variable DefaultConfig as the configuration. 3. The first registered backend is used with an empty configuration.
It fails if no backends were registered.
Deprecated: at the next version this function will be removed. Use New instead.
func NewWithConfig ¶
NewWithConfig takes a configuration string formated as
The format of config is "<backend_name>:<backend_configuration>". The "<backend_name>" is the name of a registered backend (e.g.: "xla") and "<backend_configuration>" is backend-specific (e.g.: for xla backend, it is the PJRT plugin name).
type Buffer ¶
type Buffer interface {
// Backend returns the compute Backend that owns and manages this buffer.
Backend() Backend
// Finalize allows the client to inform the backend that the buffer is no longer needed and associated
// resources can be freed immediately, as opposed to waiting for a garbage collection.
//
// A finalized buffer should never be used again.
Finalize() error
// Shape returns the shape for the buffer.
Shape() (shapes.Shape, error)
// DeviceNum returns the deviceNum for the buffer.
DeviceNum() (DeviceNum, error)
// ToFlatData transfers the flat values of a buffer to a Go flat slice.
// The slice flat must have the exact number of elements required to store the Buffer shape,
// and be a slice of the corresponding DType -- see DType.GoType().
ToFlatData(flat any) error
// Data returns a slice pointing to the buffer storage memory directly.
// This only works if the backend's HasSharedBuffers is true.
//
// And the returned flat data is only valid while the Buffer is alive.
// If the Buffer is finalized, the flat data returned may no longer be valid.
// For shared buffers, the memory is not necessarily managed by Go.
Data() (flat any, err error)
// CopyToDevice copies the buffer to the deviceNum.
//
// Accelerators often have a much faster bus on which to transfer data, so this is expected to be potentially
// much faster than copying to the host and to the new device.
CopyToDevice(deviceNum DeviceNum) (bufferOnDevice Buffer, err error)
}
Buffer represents actual data (a tensor) stored in the accelerator that is actually going to execute the graph. It's used as input/output of computation execution. A Buffer is always associated to a DeviceNum, even if there is only one.
type Builder ¶
type Builder interface {
// Name of the computation being built.
Name() string
// Main returns the main function of this computation, named MainName.
// Operations added to Main become part of the compiled computation.
// This is the default function where all operations should be added
// unless explicitly building a sub-function.
Main() Function
// NewFunction creates a new named function within this builder.
// These are top-level functions that can be called form the main function.
//
// The name must be unique, and differnt from MainName (== "main"), the main function's name.
//
// These functions can be called from the main function or other functions.
//
// See also Function.Closure() to create unnamed local functions used in ops like While, If and others.
//
// Returns an error if the backend doesn't support sub-functions.
NewFunction(name string) (Function, error)
// OpShape returns the shape of a computation Op.
// Notice this is not an operation and doesn't change the graph being built.
//
// One can use the shape and create a constant out of it.
OpShape(op Value) (shapes.Shape, error)
// DistributedSPMD creates a computation that will be executed on multiple devices in SPMD fashion
// (SPMD = single program, multiple data).
//
// Use DeviceAssignment to assign the devices to the computation -- the default assignment is incremental
// devices starting from 0.
DistributedSPMD(numDevices int) error
// DistributedAutoSharding creates a computation that will be executed on multiple devices with auto-sharding.
// This currently aims at XLA Shardy [1] framework. But other backends can implement it with the same semantics,
// if appropriate.
//
// [1] https://github.com/openxla/shardy
DistributedAutoSharding(meshes ...Mesh) error
// DeviceAssignment assigns the concrete devices to the computation.
//
// The number of devices must match the number of devices in the computation.
// Usually, that is 1. But if DistributedSPMD was used, it can be more.
DeviceAssignment(devices ...DeviceNum) error
// Compile the computation built. This immediately invalidates the Builder
// and returns an Executable that can be used to run the computation.
//
// The Main function must have had Return() called before compilation.
Compile() (Executable, error)
}
Builder defines the interface for building a computation.
A Builder manages one or more Functions, with Main() being the primary entry point that gets compiled into an Executable. Operations are added to Functions (not directly to Builder), and Function.Return() must be called before Builder.Compile().
Each Builder can also:
- Not implement standard operations by returning an error -- this restricts what type of models it can support. See Backend.Capabilities and package github.com/gomlx/compute/notimplemented.
- Support specialized operations beyond those defined in this interface -- this requires careful interface casting by the caller.
type Capabilities ¶
type Capabilities struct {
// Operations supported by a backend.
// If not listed, it's assumed to be false, hence not supported.
Operations map[OpType]bool
// Functions indicates whether the backend supports functions (top-level functions or closures).
// Without functions, it's not possible to support Call() op or any other
// op that takes as input a closure (While, If, etc.)
Functions bool
// DTypes list the data types supported by a backend.
// If not listed, it's assumed to be false, hence not supported.
DTypes map[dtypes.DType]bool
// DynamicAxes indicates whether the backend supports named dynamic axes
// and shape specialization. When true, graph parameters can have symbolic
// dimensions (shapes.DynamicDim) with named axes, and the backend will
// lazily specialize execution for each concrete axis binding.
//
// Deprecated: DynamicShapesSupport provides more fine-grained control
// over dynamic shapes and is the recommended way to specify backend
// capabilities regarding dynamic shapes. It is set to true if
// DynamicShapes is not DynamicShapesNone.
DynamicAxes bool
// DynamicShapes indicates whether the backend supports dynamic shapes
// during graph building. If supported the same computation graph can be
// used for different shapes of inputs. Some operations can also produce
// data-dependent dynamic dimensions (for example, NonZero); support for
// those operations is backend-specific.
//
// A backend may not support dynamic shapes at all -- in which case GoMLX
// recreates and recompiles the whole graph at runtime for each different
// input shape. Or it can support dynamic shapes by JIT-recompiling behind
// the scenes. In either these two cases, the user need to know and properly
// bucket/pad inputs to avoid excessive recompilations (if inputs vary in size).
DynamicShapes DynamicShapesSupport
// DynamicDimDType specifies the DType used or returned by the backend for dynamic dimensions
// (such as DynamicDimensionSize and DynamicShape).
// If not set (or set to dtypes.InvalidDType), it defaults to dtypes.Int64.
DynamicDimDType dtypes.DType
// PreferConstantsForVariables indicates that the backend prefers context variables
// (model weights) to be embedded as constants in the computation graph rather than
// passed as parameters (inputs) at execution time. This enables optimizations like
// weight blob storage and eliminates per-inference data transfer overhead.
// When true, libraries like onnx-gomlx should use graph.Const() instead of
// Variable.ValueGraph() for model weights.
PreferConstantsForVariables bool
// can be reused across multiple Functions and Builders created on the same Backend.
// When true, model variables converted to constants (e.g., when donating a model.Store
// for inference) can be cached as a compute.Value and shared across graph recompilations.
SharedConstants bool
// RNGAlgorithms lists which Random Number Generator (RNG) algorithms are natively
// supported by this backend (paralleling Operations and DTypes).
// Backends supporting OpTypeRNGBitGenerator should at least set RNGAlgorithms[RNGDefault] = true.
RNGAlgorithms map[RNGAlgorithm]bool
// DefaultRNGAlgorithm indicates which concrete [RNGAlgorithm] this backend uses when
// [RNGDefault] is requested (for example, [RNGPhilox] or [RNGThreeFry]).
//
// If the backend uses a backend-private native Pseudo-Random Number Generator (PRNG)
// that does not correspond to a portable RNGAlgorithm constant, DefaultRNGAlgorithm
// remains [RNGDefault] and DefaultRNGStateShape must specify its state tensor shape.
DefaultRNGAlgorithm RNGAlgorithm
// DefaultRNGStateShape specifies the state tensor shape for [RNGDefault] ONLY when
// DefaultRNGAlgorithm == RNGDefault (a backend-private native PRNG).
// When DefaultRNGAlgorithm != RNGDefault, DefaultRNGAlgorithm.StateShape() is used.
DefaultRNGStateShape shapes.Shape
}
Capabilities holds mappings of what is supported by a backend.
func (Capabilities) Clone ¶
func (c Capabilities) Clone() Capabilities
Clone makes a deep copy of the Capabilities.
func (Capabilities) DynamicDimDTypeOrDefault ¶ added in v0.1.12
func (c Capabilities) DynamicDimDTypeOrDefault() dtypes.DType
DynamicDimDTypeOrDefault returns DynamicDimDType if set and valid, or dtypes.Int64 by default.
func (Capabilities) HasDynamicShapes ¶ added in v0.1.5
func (c Capabilities) HasDynamicShapes() bool
HasDynamicShapes returns true if the backend supports dynamic shapes in any mode.
func (Capabilities) RNGStateFromSeed ¶ added in v0.1.32
func (c Capabilities) RNGStateFromSeed(algo RNGAlgorithm, seed int64) (flat any, shape shapes.Shape, err error)
RNGStateFromSeed creates an initial host flat slice and state Shape from seed for algo on this backend. Returns an error wrapping ErrNotImplemented if algo is not supported.
func (Capabilities) RNGStateShape ¶ added in v0.1.32
func (c Capabilities) RNGStateShape(algo RNGAlgorithm) (shapes.Shape, error)
RNGStateShape returns the expected state tensor Shape for algo on this backend, or an error wrapping ErrNotImplemented if algo is not natively supported.
func (Capabilities) ResolveRNGAlgorithm ¶ added in v0.1.32
func (c Capabilities) ResolveRNGAlgorithm(algo RNGAlgorithm) RNGAlgorithm
ResolveRNGAlgorithm resolves RNGDefault to c.DefaultRNGAlgorithm (which remains RNGDefault if the backend uses a backend-private native PRNG), or returns algo unchanged.
func (Capabilities) SupportsRNG ¶ added in v0.1.32
func (c Capabilities) SupportsRNG(algo RNGAlgorithm) bool
SupportsRNG reports whether the backend natively implements the given RNGAlgorithm.
type CollectiveOps ¶
type CollectiveOps interface {
// AllReduce is a distributed (multi-device) operation that reduces over the build the AllReduce operation
// across replica groups.
//
// - operands: list of operands to be replicated -- often this operation is called over all the parameters
// of a model, hence the option to pass a variable number of parameters to them.
// - reductionType: how the operands should be reduced.
// - replicaGroups: a collection of replica groups: each replica group ([]int) is a collection of devices that
// will participate in the distributed operation. The devices are given as indices (hence []int) into the
// device assignments (not absolute DeviceNum).
AllReduce(operands []Value, reductionType ReduceOpType, replicaGroups [][]int) ([]Value, error)
}
CollectiveOps is an interface for collective operations, that is, operations executed across multiple devices.
EXPERIMENTAL: currently the best supported distribution model is "GSPMD" (Global Single Program Multiple Data), which automatically distributes the computation across all devices, without having to use explicit collective operations.
type Constructor ¶
Constructor takes a config string (optionally empty) and returns a Backend.
type ConvolveAxesConfig ¶
type ConvolveAxesConfig struct {
InputBatch, InputChannels int
InputSpatial []int
KernelInputChannels, KernelOutputChannels int
KernelSpatial []int
OutputBatch, OutputChannels int
OutputSpatial []int
}
ConvolveAxesConfig defines the interpretation of the input/kernel/output tensor axes. There must be the same number of spatial dimensions (axes) for each of the 3 tensors. Input and output have batch and channel axes. Kernel has inputChannel and outputChannel axes.
See Builder.ConvGeneral.
func (ConvolveAxesConfig) Clone ¶
func (c ConvolveAxesConfig) Clone() ConvolveAxesConfig
Clone returns a deep copy of the structure.
type CumSumOptions ¶ added in v0.1.5
type CumSumOptions struct {
// Exclusive if not to include the current element in the cumulative operation:
// CumSum([1, 2, 3], 0, CumSumOptions{Exclusive:true}) -> [0, 1, 3].
// CumMax([3, 1, 4], 0, CumSumOptions{Exclusive:true}) -> [-Inf, 3, 3].
Exclusive bool
// Reverse to accumulate in the reverse direction.
Reverse bool
}
CumSumOptions are options for the CumSum and CumMax operations.
type DataInterface ¶
type DataInterface interface {
// BufferFromFlatData transfers data from Go given as a flat slice (of the type corresponding to the shape DType)
// to the deviceNum, and returns the corresponding Buffer.
BufferFromFlatData(deviceNum DeviceNum, flat any, shape shapes.Shape) (Buffer, error)
// that can be used directly by the engine and has a local address that can be read or mutated
// directly by the client.
HasSharedBuffers() bool
// computations and directly read or mutated by the clients.
//
// It panics if the backend doesn't support shared buffers -- see HasSharedBuffers.
NewSharedBuffer(deviceNum DeviceNum, shape shapes.Shape) (buffer Buffer, flat any, err error)
}
DataInterface is the Backend's subinterface that defines the API to transfer Buffer to/from accelerators for the backend.
type DenseConfig ¶
type DenseConfig struct {
// Activation is applied after the matmul+bias; set to ActivationNone for no activation.
Activation ActivationConfig
// WeightLayout specifies the layout of the weight matrix (DenseLayoutInputOutputs or DenseLayoutOutputsInput).
WeightLayout DenseLayout
}
DenseConfig holds configuration parameters for FusedDense operations.
type DenseLayout ¶
type DenseLayout int
DenseLayout specifies the layout (axis ordering) of the weight matrix in Dense operations.
const ( // DenseLayoutInputOutputs specifies that weights have shape [in_features, out_features...] (0, default). DenseLayoutInputOutputs DenseLayout = iota // DenseLayoutOutputsInput specifies that weights have shape [out_features..., in_features]. DenseLayoutOutputsInput )
func (DenseLayout) String ¶
func (l DenseLayout) String() string
String returns the name of the dense weight layout.
type DeviceNum ¶
type DeviceNum int
DeviceNum represents which device holds a buffer or should execute a computation. It's up to the backend to interpret it, but it should be between 0 and Backend.NumDevices.
type DotGeneralConfig ¶
type DotGeneralConfig struct {
// AccumulatorDType is the data type of the accumulator during the matrix multiplication.
// Commonly set to Float32 for half-precision (Float16 and BFloat16) operations, or maybe for Int32
// for small quantized values operations.
//
// If left empty, it defaults to the same dtype as the inputs.
//
// Some backends may not support this option and this will cause it to simply convert the input to the accumulation
// type upfront, which is less efficient.
AccumulatorDType dtypes.DType
// OutputDType is the data type of the output of the matrix multiplication.
//
// If left empty, it defaults to the same dtype as the AccumulatorDType.
//
// Some backends may not support this option and this will cause it to simply convert the input to the output
// type upfront, which is less efficient.
OutputDType dtypes.DType
}
DotGeneralConfig are optional configurations for the DotGeneral operation.
type DynamicDimensionSpec ¶ added in v0.1.1
type DynamicDimensionSpec struct {
// Static dimension size (>= 0). It is ignored if a Name is set.
Static int
// Name of a dynamic axis dimension or for an inferred dimension (at most one inferred
// dimension). Empty string for static dimensions.
Name string
// Scalar integer (Int32 or Int64) value for runtime dimension size (nil if static or auto-inferred).
Value Value
}
DynamicDimensionSpec specifies a target dimension for dynamic shape operations (e.g., DynamicReshape, DynamicBroadcastInDim). It can be one of three:
- Static: known at graph building time, e.g.: `DynamicDimensionSpec{Static: 16}`.
- Dynamic: named dynamic dimension given with a graph.Value: e.g.: `DynamicDimensionSpec{Name: "batch", Value: batchSize}`.
- Inferred / Known: named dynamic dimension given with a name: e.g.: `DynamicDimensionSpec{Name: "seq_len"}`.
type DynamicOps ¶ added in v0.1.5
type DynamicOps interface {
// 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).
DynamicDimensionSize(operand Value, axis int) (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).
DynamicReshape(operand Value, dimensions ...DynamicDimensionSpec) (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).
DynamicBroadcastInDim(operand Value, broadcastAxes []int, dimensions ...DynamicDimensionSpec) (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).
DynamicIota(dtype dtypes.DType, iotaAxis int, dimensions ...DynamicDimensionSpec) (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).
DynamicPad(x, fillValue Value, axesConfig ...DynamicPadAxis) (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.
NonZero(operand Value, cfg NonZeroConfig) (Value, error)
}
DynamicOps defines the operations that expect or operate on dynamic shapes.
type DynamicPadAxis ¶ added in v0.1.5
type DynamicPadAxis struct {
// Static padding amounts (used when corresponding Value is nil).
// Start and End may be negative to truncate the axis; Interior must be >= 0.
Start, End, Interior int
// Dynamic scalar integer values for runtime padding (nil if static).
// StartValue and EndValue may evaluate to negative integers to truncate the axis;
// InteriorValue must evaluate to a non-negative integer (>= 0).
StartValue, EndValue, InteriorValue Value
// TargetAxisName is the optional name for the resulting dynamic axis if padding a dynamic dimension
// or dynamically expanding a dimension into a named dynamic axis.
TargetAxisName string
}
DynamicPadAxis defines the amount of padding preceding one axis (Start), at the end of axis (End), or in between the inputs (Interior). Each field can be static (when Value is nil) or dynamic (when Value is set).
Start and End (as well as StartValue and EndValue) can be negative, in which case they truncate (crop) elements from the start or end of the axis respectively (applied after interior padding). Interior (as well as InteriorValue) must be non-negative (>= 0).
type DynamicShapesSupport ¶ added in v0.1.5
type DynamicShapesSupport int
DynamicShapesSupport enumeration values indicating whether and how a backend supports dynamic shapes.
const ( // DynamicShapesNone: Backend only supports static shapes (e.g., XLA PJRT). DynamicShapesNone DynamicShapesSupport = iota // DynamicShapesNative: Backend compiles once for dynamic graphs; zero // recompilation overhead across variable input dimensions (e.g., Go backend, ONNX Runtime). DynamicShapesNative // DynamicShapesRecompiling: Backend accepts dynamic input shapes and shares // weights/constants, but JIT-specializes/recompiles kernels per concrete shape. DynamicShapesRecompiling )
func DynamicShapesSupportString ¶ added in v0.1.5
func DynamicShapesSupportString(s string) (DynamicShapesSupport, error)
DynamicShapesSupportString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.
func DynamicShapesSupportValues ¶ added in v0.1.5
func DynamicShapesSupportValues() []DynamicShapesSupport
DynamicShapesSupportValues returns all values of the enum
func (DynamicShapesSupport) IsADynamicShapesSupport ¶ added in v0.1.5
func (i DynamicShapesSupport) IsADynamicShapesSupport() bool
IsADynamicShapesSupport returns "true" if the value is listed in the enum definition. "false" otherwise
func (DynamicShapesSupport) String ¶ added in v0.1.5
func (i DynamicShapesSupport) String() string
type Executable ¶
type Executable interface {
// Finalize immediately frees resources associated to the executable.
//
// It is the responsibility of the caller to guarantee that there are no unfinished executions
// (calls to [Executable.Execute]) before calling Finalize. Calling Finalize while an execution
// is still running may lead to undefined behavior and potentially crash depending on the backend.
//
// Calling Finalize is optional: one can always leave it to the garbage collector (GC), which will
// properly clean up native resources eventually. Alternatively, callers can rely on higher-level
// coordinator objects such as graph.Exec or model.Exec to coordinate safe concurrent execution and teardown.
Finalize()
// Inputs returns the parameters' names and shapes, in order created by the Builder.Parameter calls.
Inputs() (names []string, inputShapes []shapes.Shape)
// Outputs return the computation's output shapes, in the order given to the Builder.Compile call.
Outputs() (outputShapes []shapes.Shape)
// Execute the computation.
// The number and shapes of the inputs must match those of the Executable parameters (returned by [Executable.Inputs]).
//
// The inputs marked as donate will become invalid after use.
// This is useful if the input buffer is no longer needed or if updating a variable
// so its Buffer space can be reused as an output Buffer.
//
// Donated buffers are no longer valid after the call.
// If donate is nil, it is assumed to be false for all buffers, and no buffer is donated.
//
// For portable computations (not compiled with a fixed device assignment), the execution runs on the defaultDevice.
// For non-portable computations (where the device assignment is fixed), the defaultDevice is ignored.
//
// For SPMD distributed computations (see [Builder.DistributedSPMD]), the executable is replicated on each device.
// There will be multiple inputs per executable parameter, one per device.
// They are organized as "device-major", that is the input for parameter i on device j is given by inputs[j*numParams + i].
Execute(inputs []Buffer, donate []bool, defaultDevice DeviceNum) ([]Buffer, error)
}
Executable is the API for compiled programs ready to execute.
type FFTType ¶
type FFTType int
FFTType select among the basic types of Fast Fourier Transform (FFT) supported.
func FFTTypeString ¶
FFTTypeString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.
func (FFTType) IsAFFTType ¶
IsAFFTType returns "true" if the value is listed in the enum definition. "false" otherwise
type Function ¶
type Function interface {
// Name of the function. It will return "" for closures.
Name() string
// Builder returns the builder of which this function is part of.
Builder() Builder
// Parent returns the parent function of the current function.
// This is only set for "closures" within another functions.
// For top-level functions, like "main", or for backends that don't support fun this returns nil.
Parent() Function
// Closure returns a new local function, that can be used by certain operations like While, If, Sort.
// Closure functions can access values from its parent function.
Closure() (Function, error)
// StandardOps includes all standard math/ML operations.
StandardOps
// DynamicOps includes operations that expect or operate on dynamic shapes.
DynamicOps
// FusedOps includes optional fused operations for better performance.
FusedOps
// CollectiveOps includes all collective (distributed cross-device) operations.
CollectiveOps
// Parameter creates an input parameter for this function.
//
// For the Main function, these become the computation's input parameters
// that must be provided when executing the compiled computation.
//
// For sub-functions, these define the function's input signature.
//
// The sharding defines how the parameter will be sharded for distributed
// operations. Set it to nil if not using distribution.
Parameter(name string, shape shapes.Shape, sharding *ShardingSpec) (Value, error)
// Constant creates a constant in the function with the given flat values
// and the shape defined by the dimensions.
//
// The flat value must be a slice of a basic type supported (that can be
// converted to a DType).
//
// The value is copied into the graph.
//
// Very large constants (like the weights of a model, or large constants) they are usually passed as
// parameters instead -- except if the backend sets Capabilities.PreferConstantsForVariables.
Constant(flat any, dims ...int) (Value, error)
// ConstantFromBuffer creates a constant in the function backed by the given backend buffer,
// avoiding the host slice copy of Constant when supported by the backend.
//
// The buffer must belong to the same backend as the function.
//
// If donate is true, ownership of buf is transferred to the function (the caller must not use buf
// afterwards, and the backend may reuse or free the buffer).
// If donate is false, the caller retains ownership of buf and must ensure it remains valid and unmodified
// for the lifetime of any executable built from this function (or copy/pin it as needed by the backend).
//
// Backends that do not support adopting a Buffer as a constant return ErrNotImplemented.
ConstantFromBuffer(buf Buffer, donate bool) (Value, error)
// Shape returns the shape of the given Value.
//
// Notice, this doesn't create an op on the graph, it's purely for reporting/introspection.
// See DynamicShape and DynamicDimensionSize for the dynamic value of a shape when using dynamic shapes.
Shape(v Value) (shapes.Shape, error)
// Return marks the outputs of this function.
// Once called, the function can no longer be futher modified.
//
// For the Main function, this defines what values will be returned when
// the compiled computation is executed.
//
// For sub-functions, this defines what values are returned when the
// function is called.
//
// The shardings parameter optionally specifies output sharding for
// distributed computation with AutoSharding. Set to nil otherwise.
//
// Return must be called exactly once before Builder.Compile().
Return(outputs []Value, shardings []*ShardingSpec) error
// Call a function with the given inputs.
//
// The function f must be from the same builder.
Call(f Function, inputs ...Value) ([]Value, error)
// Sort sorts one or more tensors along the specified axis using a comparator closure.
//
// The comparator is a closure that takes 2*N scalar inputs (where N is the number of tensors)
// and returns a single boolean. For each pair of positions being compared, it receives
// (lhs_0, lhs_1, ..., lhs_N-1, rhs_0, rhs_1, ..., rhs_N-1) where lhs_i and rhs_i are scalars
// from tensor i at the two positions being compared.
//
// The comparator should return true if lhs should come before rhs in the sorted order.
// For a standard ascending sort on a single tensor, the comparator returns lhs < rhs.
//
// All input tensors must have the same shape. The axis must be valid for the input shape.
// If isStable is true, the sort maintains the relative order of equal elements.
//
// Returns the sorted tensors in the same order as inputs.
Sort(comparator Function, axis int, isStable bool, inputs ...Value) ([]Value, error)
// While executes a loop while a condition is true.
//
// The condition closure (cond) takes N values (the current state) and returns a single
// boolean scalar indicating whether to continue looping.
//
// The body closure takes N values (the current state) and returns N values (the new state).
// The shapes of the outputs must match the shapes of the inputs.
//
// The initialState values are passed to both cond and body on the first iteration.
// On subsequent iterations, the outputs of body become the new state.
//
// Returns the final state values when cond returns false.
While(cond, body Function, initialState ...Value) ([]Value, error)
// If executes one of two branches based on a boolean predicate.
//
// The pred must be a scalar boolean value.
//
// The trueBranch and falseBranch are closures that take no parameters (they can capture
// values from the parent scope) and return N values each. Both branches must return
// the same number of outputs with matching shapes.
//
// Returns the outputs of the executed branch.
If(pred Value, trueBranch, falseBranch Function) ([]Value, error)
}
Function represents a computation function within a Builder.
A Function contains operations (via StandardOps and CollectiveOps), constants, and parameters. Multiple functions can be composed within a Builder, with Main() being the entry point that gets compiled.
Other top-level functions created via Builder.NewFunction() can be used for modular computation, while-loop bodies, conditional branches, reduce operations, etc.
The typical lifecycle is:
- Create parameters via Parameter()
- Build computation using StandardOps/CollectiveOps methods
- Mark outputs via Return()
After all functions of a Builder are finished (and Return() has been called), one compiles the Builder with Builder.Compile().
type FusedOps ¶
type FusedOps interface {
// FusedActivation applies the configured activation function.
// cfg.Type is obligatory, other fields are optional and specific for activations.
FusedActivation(x Value, cfg ActivationConfig) (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.
FusedActivationVJP(y, x, dOutput Value, cfg ActivationConfig) (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).
FusedSoftmax(x Value, axis int) (Value, error)
// FusedLayerNorm applies layer normalization over specified axes.
// gamma and beta can be nil if no learned scale/offset.
// epsilon: numerical stability constant (typically 1e-5).
FusedLayerNorm(x Value, axes []int, epsilon float64, gamma, beta Value) (Value, error)
// FusedLayerNormVJP computes the vector-jacobian product (gradients) of FusedLayerNorm
// with respect to its inputs (x, gamma, and beta).
//
// Parameters:
// - x: original input tensor to FusedLayerNorm.
// - dOutput: incoming adjoint gradient with respect to the output of FusedLayerNorm (same shape as x).
// - axes: normalization axes passed to the forward FusedLayerNorm call.
// - epsilon: numerical stability constant passed to the forward FusedLayerNorm call.
// - gamma: scale tensor passed to FusedLayerNorm (can be nil if FusedLayerNorm was called without gamma).
// - beta: offset tensor passed to FusedLayerNorm (can be nil if FusedLayerNorm was called without beta).
//
// Outputs:
// - dx: gradient with respect to x (same shape as x).
// - dGamma: gradient with respect to gamma (same shape as gamma, or nil if gamma was nil).
// - dBeta: gradient with respect to beta (same shape as beta, or nil if beta was nil).
FusedLayerNormVJP(x, dOutput Value, axes []int, epsilon float64, gamma, beta Value) (dx, dGamma, dBeta Value, err 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.
FusedDense(x, weight, bias Value, options DenseConfig) (Value, error)
// FusedDenseVJP computes the vector-jacobian product (gradients) of FusedDense with respect to
// its inputs (x, weight, and bias).
//
// Parameters:
// - x: original input tensor to FusedDense, of shape [batch..., in_features].
// - weight: weight tensor to FusedDense.
// - bias: bias tensor to FusedDense (can be nil if FusedDense was called without bias).
// - y: output of the forward FusedDense call.
// - dOutput: incoming adjoint gradient with respect to y (same shape as y).
// - options: configuration passed to the forward FusedDense call.
//
// Outputs:
// - dx: gradient with respect to x (same shape as x).
// - dWeight: gradient with respect to weight (same shape as weight).
// - dBias: gradient with respect to bias (same shape as bias, or nil if bias was nil).
//
// Note: FusedDenseVJP only works for activations that return false to
// ActivationType.VJPRequiresInput() (such as ActivationNone, ActivationRelu, ActivationSigmoid,
// ActivationHardSigmoid, ActivationLeakyRelu, ActivationSelu, and ActivationTanh).
// If the activation requires the input (where VJPRequiresInput() returns true, such as
// ActivationSilu, ActivationHardSwish, ActivationGelu, and ActivationGeluApproximate), it is
// recommended to use FusedDense without an activation (ActivationNone), and then use
// FusedActivation separately so that the pre-activation intermediate can be preserved for
// FusedActivationVJP.
FusedDenseVJP(x, weight, bias, y, dOutput Value, options DenseConfig) (dx, dWeight, dBias Value, err error)
// FusedScaledDotProductAttention computes multi-head scaled dot-product attention.
//
// output = softmax(query @ key^T * scale + mask) @ value, computed per-head with GQA support.
//
// Conventions:
// - "numHeads" refers to the number of heads for the query, and "numKVHeads" for the key and value.
// - "seqLen" refers to the sequence length of the query, and "kvLen" is the sequence length for the key and value.
//
// Inputs:
// - query, key, value: 4D tensors with matching floating-point dtype (Float32, Float64,
// Float16, or BFloat16, as supported by the backend) whose axis ordering is determined
// by axesLayout:
// For AttentionAxesLayoutBHSD: query [batch, numHeads, seqLen, headDim],
// key/value [batch, numKVHeads, kvLen, headDim].
// For AttentionAxesLayoutBSHD: query [batch, seqLen, numHeads, headDim],
// key/value [batch, kvLen, numKVHeads, headDim].
// - axesLayout: determines the axis ordering of query/key/value tensors
// - options: optional parameters (nil uses defaults). See ScaledDotProductAttentionConfig.
// When options.Mask (non-Bool additive mask) or options.Bias is provided, its dtype
// must match query's dtype.
//
// Half-precision behavior:
// - For Float16 and BFloat16 inputs, Q@K^T, scaling, mask/bias addition, softmax
// reductions, and P@V weighted accumulation are performed in Float32 precision (or
// higher) before rounding the final output tensor back to query's dtype. Backends
// that do not support half-precision (or a given options combination) return
// ErrNotImplemented so callers can fall back cleanly.
//
// Outputs:
// - output: same shape and dtype as query.
// - statesForVJP: optional (may be nil/empty). When the backend supports a fused backward
// (FusedScaledDotProductAttentionVJP), it returns whatever backward-pass state that
// backend's fused VJP needs.
// The number, semantics and shapes of these values are backend-specific; the VJP is only
// ever called with the exact slice this call returned.
// Backends without a fused backward return nil/empty here and ErrNotImplemented from the
// VJP, so the caller differentiates the decomposed attention instead.
FusedScaledDotProductAttention(
query, key, value Value,
axesLayout AttentionAxesLayout,
options *ScaledDotProductAttentionConfig) (output Value, statesForVJP []Value, err error)
// FusedScaledDotProductAttentionVJP computes the gradients (dQuery, dKey, dValue) of
// FusedScaledDotProductAttention given the forward output, the statesForVJP it returned, and
// the adjoint output gradient dOutput. The query/key/value and options parameters are
// the same values passed to the forward call.
//
// Backends that return non-nil/non-empty statesForVJP from the forward and implement a fused
// backward (e.g. the cuDNN flash backward) implement this. Others return ErrNotImplemented so
// the caller falls back to differentiating the decomposed attention.
FusedScaledDotProductAttentionVJP(
query, key, value Value,
axesLayout AttentionAxesLayout,
options *ScaledDotProductAttentionConfig,
output Value, statesForVJP []Value, dOutput Value) (dQuery, dKey, dValue Value, err 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].
QuantizedGather(x, indices Value,
xQuantization *Quantization) (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).
FusedQuantizedDense(x, weight, bias Value, options FusedQuantizedDenseConfig) (Value, error)
// FusedQuantizedDenseVJP computes the vector-Jacobian product (backward pass) of FusedQuantizedDense
// with respect to floating-point x and optional floating-point bias, keeping quantized weight frozen
// (essential for QLoRA and quantized fine-tuning where gradients flow through frozen base weights into
// trainable adapters without materializing [K, N] float weights in memory).
//
// Let z = x @ dequant(weight) + bias and y = activation(z). Given upstream dOutput = dL/dy:
// dZ = dOutput * activation'(z) (derived from y when Activation != ActivationNone)
// dx = dZ @ dequant(weight)^T (respecting options.WeightLayout)
// dBias = sum_{batch...}(dZ) (nil if bias == nil)
//
// Memory-saving nil inputs:
// - x may be nil if !options.Activation.VJPRequiresInput() (since quantized weights are frozen,
// dWeight is not computed, so x does not need to be saved across the forward-backward boundary!).
// - y may be nil when options.Activation.Type == ActivationNone.
//
// Only supported when options.XQuantization == nil and options.OutputQuantization == nil.
FusedQuantizedDenseVJP(x, weight, bias, y, dOutput Value, options FusedQuantizedDenseConfig) (dx, dBias Value, err error)
// FusedAttentionQKVProjection performs fused Query-Key-Value projection: a single large matmul
// merged with a scatter into separate query (Q), key (K), value (V) outputs with optional
// per-projection bias.
//
// The caller is expected to flatten any leading dimensions (e.g. batch and sequence) into a
// single "batch" axis before calling, and reshape the outputs afterwards. For example, with
// BSHD layout the caller reshapes [batch, seqLen, inFeatures] → [batch*seqLen, inFeatures],
// calls this method, then reshapes each output back to [batch, seqLen, ...].
//
// Inputs:
// - x: [batch, inFeatures] (batch may include a merged sequence dimension)
// - wQKV: [inFeatures, queryDim+2*keyValueDim] (Q/K/V weights concatenated along last axis)
// - biasQ: [queryDim] (optional, nil for no bias)
// - biasK: [keyValueDim] (optional, nil for no bias)
// - biasV: [keyValueDim] (optional, nil for no bias)
//
// Parameters:
// - queryDim: output dimension for query projection
// - keyValueDim: output dimension for key and value projections
//
// Outputs: query [batch, queryDim], key [batch, keyValueDim], value [batch, keyValueDim]
FusedAttentionQKVProjection(
x, wQKV, biasQ, biasK, biasV Value,
queryDim, keyValueDim int) (
query, key, value Value, err error)
// FusedTopK returns sorted values and Int32 indices of the k largest (or
// smallest when cfg.Smallest is true) elements along cfg.Axis. Ties prefer the
// lower original index. k must be positive and no larger than the axis.
FusedTopK(operand Value, k int, cfg FusedTopKConfig) (values, indices Value, err error)
}
FusedOps defines optional fused operations. Backends may implement these for better performance; the graph layer falls back to decomposed operations when unavailable.
Like with standard ops, if the backend doesn't implement the fused op, return ErrNotImplemented (wrapped with a stack).
type FusedQuantizedDenseConfig ¶ added in v0.1.29
type FusedQuantizedDenseConfig struct {
// WeightQuantization describes how weight is quantized. Required (must not be nil).
WeightQuantization *Quantization
// XQuantization optionally describes a pre-quantized input activation x.
// - nil (default): x is floating-point (Float32, Float16, BFloat16).
// - QuantLinear: x is Int8 or Uint8 [batch..., K]; matmul accumulates in Int32
// (adding optional Int32 bias before rescaling, or floating-point bias after rescaling
// by xScale * wScale into Float32) before Activation and OutputQuantization.
// - QuantGGML: x is Uint8 [batch..., bytesPerRowX] with GGMLType == GGMLQ8_0 (paired with
// 32-element weight blocks Q4_0/Q8_0/IQ4NL) or GGMLQ8_K (paired with 256-element K-quant
// weight blocks Q2_K..Q6_K).
XQuantization *Quantization
// OutputQuantization optionally specifies re-quantization of the post-activation output
// (e.g. for ONNX QLinearMatMul where output is Int8 or Uint8 given yScale and yZeroPoint).
// When nil (default), the output is floating-point (matching x's float dtype, or Float32
// when x is pre-quantized).
OutputQuantization *Quantization
// QuantizedMatmul is an optimization hint used only when XQuantization == nil:
// if true, backends with fast integer dot-product kernels may dynamically quantize
// floating-point x on-the-fly (e.g. to Q8_0/Q8_K blocks for QuantGGML weights, or
// per-row symmetric Int8 for QuantLinear weights) and accumulate in Int32.
// Backends that do not support on-the-fly dynamic quantization ignore this hint.
QuantizedMatmul bool
// Activation is applied after matmul/rescaling and bias (and before OutputQuantization if set).
// Defaults to ActivationNone (zero value).
Activation ActivationConfig
// WeightLayout specifies the logical axis order of weight:
// - DenseLayoutInputOutputs (0, default for Linear/NF4): weight is [K, N].
// - DenseLayoutOutputsInput (1, required for QuantGGML, also supported for Linear/NF4):
// weight is [N, K] (or [N, bytesPerRow] for QuantGGML).
WeightLayout DenseLayout
}
FusedQuantizedDenseConfig configures FusedQuantizedDense and FusedQuantizedDenseVJP.
Like ScaledDotProductAttentionConfig, fields fall into two categories:
- Correctness-affecting fields (WeightQuantization, XQuantization, OutputQuantization, Activation, WeightLayout): backends that cannot honor the requested combination MUST return errors.Wrapf(compute.ErrNotImplemented, ...) so callers fall back cleanly.
- Pure optimization hints (QuantizedMatmul): backends that do not support dynamic integer matmul when XQuantization == nil may ignore the hint and compute in float.
type FusedTopKConfig ¶ added in v0.1.29
type FusedTopKConfig struct {
// Axis is the axis along which to select the top k elements.
Axis int
// Smallest selects the k smallest elements when true. The default selects the largest.
Smallest bool
}
FusedTopKConfig configures FusedTopK.
type GGMLQuantType ¶
type GGMLQuantType int
GGMLQuantType identifies the specific GGML block quantization format. Enum values are aligned with go-highway's gguf.QuantType for future integration.
const ( GGMLQ4_0 GGMLQuantType = iota // 18 bytes/block, 32 values GGMLQ8_0 // 34 bytes/block, 32 values GGMLIQ4NL // 18 bytes/block, 32 values (non-linear lookup) GGMLQ2_K // 84 bytes/block, 256 values GGMLQ3_K // 110 bytes/block, 256 values GGMLQ4_K // 144 bytes/block, 256 values GGMLQ5_K // 176 bytes/block, 256 values GGMLQ6_K // 210 bytes/block, 256 values GGMLQ8_K // 292 bytes/block, 256 values (used for paired K-quant activations) GGMLQ4_1 // 20 bytes/block, 32 values (fp16 d + fp16 m + 16B nibbles) GGMLQ5_0 // 22 bytes/block, 32 values (fp16 d + 4B high bits + 16B nibbles) GGMLQ5_1 // 24 bytes/block, 32 values (fp16 d + fp16 m + 4B high bits + 16B nibbles) )
func (GGMLQuantType) BytesPerBlock ¶
func (t GGMLQuantType) BytesPerBlock() int
BytesPerBlock returns the byte size of one quantized block.
func (GGMLQuantType) String ¶
func (t GGMLQuantType) String() string
String returns the name of the GGML quantization type.
func (GGMLQuantType) ValuesPerBlock ¶
func (t GGMLQuantType) ValuesPerBlock() int
ValuesPerBlock returns the number of float32 values represented by one block.
type Mesh ¶
type Mesh struct {
Name string
AxesSizes []int
AxesNames []string
// LogicalDeviceAssignment is the logical assignment of devices to the mesh.
// The numbers here correspond to the indices on the "hard" device assignment set with
// Builder.DeviceAssignment() method.
//
// If left empty, the default assignment is incremental devices starting from 0.
LogicalDeviceAssignment []int
}
Mesh represents a mesh of devices, passed to the Builder.DistributedAutoSharding method.
AxesSizes and AxesNames define the mesh topology.
type NonZeroConfig ¶ added in v0.1.29
type NonZeroConfig struct {
// CountAxisName names the data-dependent number of nonzero elements.
// If empty, the backend generates a unique axis name.
CountAxisName string
// Transpose returns coordinates with shape [rank, count] instead of [count, rank].
Transpose bool
}
NonZeroConfig configures NonZero's output shape.
type OpType ¶
type OpType int
OpType is an enum of all generic operations that can be supported by a Backend.Builder.
Notice: nothing precludes a specialized backend Builder to support other ops not included here. It requires some careful casting of interfaces by the caller.
const ( OpTypeInvalid OpType = iota OpTypeParameter OpTypeConstant OpTypeIdentity OpTypeReduceWindow OpTypeRNGBitGenerator OpTypeBatchNormForInference OpTypeBatchNormForTraining OpTypeBatchNormGradient OpTypeBitCount OpTypeAbs OpTypeAdd OpTypeArgMinMax OpTypeAtan2 OpTypeBitcast OpTypeBitwiseAnd OpTypeBitwiseNot OpTypeBitwiseOr OpTypeBitwiseXor OpTypeBroadcastInDim OpTypeDynamicBroadcastInDim OpTypeCall OpTypeClamp OpTypeCeil OpTypeClz OpTypeComplex OpTypeConcatenate OpTypeConj OpTypeConvGeneral OpTypeConvertDType OpTypeCos OpTypeCumMax OpTypeCumSum OpTypeDiv OpTypeDot OpTypeDotGeneral OpTypeDynamicSlice OpTypeDynamicUpdateSlice OpTypeDynamicDimensionSize OpTypeDynamicShape OpTypeEqual OpTypeEqualTotalOrder OpTypeErf OpTypeExp OpTypeExpm1 OpTypeFFT OpTypeFloor OpTypeGather OpTypeGreaterOrEqual OpTypeGreaterOrEqualTotalOrder OpTypeGreaterThan OpTypeGreaterThanTotalOrder OpTypeImag OpTypeIota OpTypeDynamicIota OpTypeIsFinite OpTypeIsNaN OpTypeLessOrEqual OpTypeLessOrEqualTotalOrder OpTypeLessThan OpTypeLessThanTotalOrder OpTypeLog OpTypeLog1p OpTypeLogicalAnd OpTypeLogicalNot OpTypeLogicalOr OpTypeLogicalXor OpTypeLogistic OpTypeMax OpTypeMin OpTypeMul OpTypeNeg OpTypeNotEqual OpTypeNotEqualTotalOrder OpTypePad OpTypeDynamicPad OpTypePow OpTypeReal OpTypeReduceBitwiseAnd OpTypeReduceBitwiseOr OpTypeReduceBitwiseXor OpTypeReduceLogicalAnd OpTypeReduceLogicalOr OpTypeReduceLogicalXor OpTypeReduceMax OpTypeReduceMin OpTypeReduceProduct OpTypeReduceSum OpTypeRem OpTypeReshape OpTypeDynamicReshape OpTypeReverse OpTypeRound OpTypeRsqrt OpTypeScatterMax OpTypeScatterMin OpTypeScatterSum OpTypeSelectAndScatterMax OpTypeSelectAndScatterMin OpTypeSelectAndScatterSum OpTypeShiftLeft OpTypeShiftRightArithmetic OpTypeShiftRightLogical OpTypeSign OpTypeSin OpTypeSlice OpTypeSqrt OpTypeSub OpTypeTanh OpTypeTranspose OpTypeWhere OpTypeOptimizationBarrier OpTypeSchedulingBarrier OpTypeSort OpTypeWhile OpTypeIf // OpTypeCapturedValue represents a value captured from a parent scope in a closure. // This allows closures to reference values computed in enclosing functions. OpTypeCapturedValue OpTypeAllReduce OpTypeCollectiveBroadcast OpTypeAllGather // OpTypeBlockForDotGeneral pre-blocks a tensor for efficient DotGeneral execution. // This is an internal optimization used by the go backend. OpTypeBlockForDotGeneral OpTypeFusedActivation OpTypeFusedActivationVJP OpTypeFusedSoftmax OpTypeFusedLayerNorm OpTypeFusedLayerNormVJP OpTypeFusedGelu OpTypeFusedDense OpTypeFusedDenseVJP OpTypeFusedScaledDotProductAttention OpTypeFusedScaledDotProductAttentionVJP OpTypeFusedAttentionQKVProjection OpTypeFusedQuantizedDense OpTypeFusedQuantizedDenseVJP OpTypeQuantizedGather OpTypeNonZero OpTypeFusedTopK // OpTypeLast should always be kept the last, it is used as a counter/marker for OpType. OpTypeLast )
func OpTypeString ¶
OpTypeString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.
type PadAxis ¶
type PadAxis struct {
Start, End, Interior int
}
PadAxis defines the amount of padding preceding one axis (Start), at the end of axis (End) or in between the inputs (Interior). This is used as a parameter for the Pad operation.
Start and End can be negative, in which case they truncate (crop) elements from the start or end of the axis respectively. Interior must be non-negative (Interior >= 0).
type Quantization ¶
type Quantization struct {
// Scheme selects QuantNone, QuantLinear, QuantNF4, or QuantGGML.
Scheme QuantizationScheme
// Scale is the multiplicative scale factor (Float32, Float16, or BFloat16).
// Supported shapes for a 2D weight tensor:
// - Scalar [] or [1]: per-tensor scale.
// - 1D [N]: per-output-channel scale (broadcast along K).
// - 2D [ceil(D0/BlockSize), D1] when BlockAxis == 0, or [D0, ceil(D1/BlockSize)] when BlockAxis == 1.
// Note: [1, N] on [K, N] weights is naturally BlockAxis=0, BlockSize=K (or BlockSize=0 meaning full axis).
// Supported shapes for activations / outputs ([batch..., features]):
// - Scalar [] or [1] (per-tensor), [features] (per-channel), or broadcast-compatible per-token/per-block shapes.
// Unused (must be nil) for QuantNone and QuantGGML.
Scale Value
// ZeroPoint is the pre-scale offset subtracted from quantized values (only for QuantLinear).
// May have integer dtype matching the quantized tensor (e.g. Int8, Uint8, Int4, Uint4) or float dtype
// matching Scale. Its shape must match Scale (or be broadcast-compatible with Scale).
// Unused (must be nil) for QuantNone, QuantNF4, and QuantGGML.
// Note: PackedDType does not apply to ZeroPoint; ZeroPoint uses its own DType (unpacked integer/float
// or native sub-byte when supported).
ZeroPoint Value
// BlockAxis is the axis of the quantized tensor partitioned into blocks of BlockSize elements:
// - For 2D weights [K, N]: BlockAxis=0 blocks along K (standard GPTQ/AWQ/ONNX MatMulNBits [K/G, N]);
// BlockAxis=1 blocks along N ([K, N/G]).
// - For 2D weights [N, K]: BlockAxis=1 blocks along K ([N, K/G]); BlockAxis=0 blocks along N ([N/G, K]).
// Ignored when Scale is scalar or 1D, or when Scheme == QuantGGML.
BlockAxis int
// BlockSize is the number of elements along BlockAxis sharing one scale/zero-point.
// When BlockSize == 0 and Scale is 2D, BlockSize is inferred as ceil(dim(BlockAxis) / scale.Dim(BlockAxis))
// when divisible.
// Unused for QuantGGML.
BlockSize int
// GGMLType specifies the concrete GGML block format (Q4_0, Q8_0, Q4_K, Q8_K, etc.).
// Only used when Scheme == QuantGGML.
GGMLType GGMLQuantType
// QuantizedDType optionally specifies the target quantized integer dtype (Int8 or Uint8)
// when Quantization is used as OutputQuantization. If InvalidDType, the dtype is inferred
// from ZeroPoint (if ZeroPoint is Int8 or Uint8), or defaults to Int8.
QuantizedDType dtypes.DType
// PackedDType optionally specifies the logical sub-byte integer dtype (Int2, Uint2, Int4, or Uint4)
// when the primary quantized tensor (e.g., x in QuantizedGather) is stored bit-packed in Uint8
// (shape [vocabSize, K / ValuesPerStorageUnit] with low bits first). Allows backends without native
// sub-byte dtype support to store and gather packed Uint8 rows without unpacking the whole table.
// Unused (must be InvalidDType) when the tensor already has a sub-byte/8-bit DType or for QuantGGML.
PackedDType dtypes.DType
}
Quantization describes how a quantized tensor maps to floating-point values (or how a floating-point output is re-quantized).
For QuantLinear, the dequantization formula is the standard integer zero-point convention shared by ONNX QuantizeLinear/DequantizeLinear/QLinearMatMul/MatMulNBits, TFLite, PyTorch, and CoreML:
real_value = (float(quant_value) - float(zero_point)) * scale
When ZeroPoint is nil, zero_point = 0 (symmetric quantization: real_value = float(quant_value) * scale).
Migration note for existing callers:
- Callers with standard pre-scale integer/float zero-points (e.g. ONNX, PyTorch, TFLite, GPTQ/AWQ qzeros) can pass them directly as ZeroPoint without negating or pre-multiplying by Scale.
- Callers migrating from the legacy post-scale additive offset convention (real_value = float(quant_value) * scale + offset) should convert the offset via zero_point = -offset / scale (in weight-only float mode XQuantization == nil, float ZeroPoint values are subtracted directly in Float32 without integer rounding, preserving exact equivalence).
- Scalar [] / [1] and 1D [N] Scale/ZeroPoint tensors can now be passed directly without broadcasting across K to [K, NumBlocks].
type QuantizationScheme ¶
type QuantizationScheme int
QuantizationScheme specifies how quantized integer values map to floating-point values.
const ( // QuantNone indicates no scaling/zero-point/GGML dequantization (only optional sub-byte // unpacking to Int8 or Uint8 in QuantizedGather, optionally from a packed Uint8 input // when PackedDType is set). Scale and ZeroPoint must be nil. QuantNone QuantizationScheme = iota // QuantLinear is standard affine quantization: real_value = (float(quant_value) - float(zero_point)) * scale. // Used with Int2/Uint2/Int4/Uint4/Int8/Uint8 weights or activations (symmetric when ZeroPoint == nil). QuantLinear // QuantNF4 is 4-bit NormalFloat from QLoRA: nibble indices are looked up in a fixed // 16-entry table, then multiplied by scale. QuantNF4 // QuantGGML indicates that the values are stored in native GGML block format // (e.g. Q4_0, Q8_0, K-quants, Q8_K). The scales and zero points are embedded in the // blocks themselves, so Scale/ZeroPoint/BlockAxis/BlockSize in Quantization are // unused; the GGMLType field specifies the concrete block format. // Weights must be [N, bytesPerRow] Uint8 with native GGML block layout; // GGML activations must be [batch..., bytesPerRow] Uint8 (GGMLQ8_0 or GGMLQ8_K). QuantGGML )
func (QuantizationScheme) String ¶
func (q QuantizationScheme) String() string
String returns the name of the quantization scheme.
type RNGAlgorithm ¶ added in v0.1.32
type RNGAlgorithm int
RNGAlgorithm specifies the Pseudo-Random Number Generator (PRNG) algorithm used by StandardOps.RNGBitGenerator.
An RNG (Random Number Generator) in compute graphs is implemented as a pure, deterministic PRNG (Pseudo-Random Number Generator): given an explicit input state tensor, it produces both an updated state tensor and a tensor of uniformly distributed random bits.
const ( // RNGDefault (the zero value) instructs the backend to use its preferred native // Random Number Generator (RNG) algorithm. // // Guarantees: // - Fast and native to the target backend. // - Deterministic across runs on the same backend given the same initial state and shapes. // - Not guaranteed to produce identical bitstreams across different backends (unless two // backends resolve RNGDefault to the same Capabilities.DefaultRNGAlgorithm). // // State shape: queried via backend.Capabilities().RNGStateShape(RNGDefault). // Native backend support: all backends supporting OpTypeRNGBitGenerator ("go", "xla", "onnx", "mlx", "mps"). RNGDefault RNGAlgorithm = iota // RNGPhilox specifies the counter-based Philox-4x32-10 Pseudo-Random Number Generator // (Salmon et al., "Parallel Random Numbers: As Easy as 1, 2, 3", SC 2011, // https://dl.acm.org/doi/10.1145/2063384.2063405), matching OpenXLA's PHILOX specification. // // Uses 10 rounds of 32-bit multiplication (mulhi/mullo) and XOR mixing over a 64-bit key // and 128-bit counter. Parallelizable across CPU workers/SIMD, GPUs, and TPUs. // // Canonical state shape: [3]uint64 ([key, counter_lo, counter_hi]). // Native backend support: "xla", "go" (plus automatic graph decomposition fallback in GoMLX). RNGPhilox // RNGThreeFry specifies the counter-based ThreeFry-2x32-20 Pseudo-Random Number Generator // (Salmon et al., "Parallel Random Numbers: As Easy as 1, 2, 3", SC 2011, // https://dl.acm.org/doi/10.1145/2063384.2063405), matching OpenXLA's THREE_FRY specification. // // Uses 20 rounds of pure 32-bit additions, bitwise rotations, and XORs (requiring no // integer multiplications), making it fast and portable across CPUs, GPUs, and TPUs. // // Canonical state shape: [2]uint64 ([key, counter]). // Native backend support: "xla", "go", "onnx", "mps" (plus automatic graph decomposition fallback in GoMLX). RNGThreeFry // RNGSplitMix64 specifies a counter-based 64-bit SplitMix64 Pseudo-Random Number Generator // (Steele, Lea, and Flood, OOPSLA 2014). // // Uses two 64-bit shift-XOR-multiply mixing steps per output word, making it very compact // and fast when cryptographic strength is not required. // // Canonical state shape: [2]uint64 ([key, counter]). // Native backend support: "go", "onnx" (plus automatic graph decomposition fallback in GoMLX // on backends supporting Uint64). RNGSplitMix64 // RNGPCG specifies the 128-bit PCG-DXSM (Permuted Congruential Generator — Double Xorshift // Multiply) sequential Pseudo-Random Number Generator matching Go's standard library // math/rand/v2.PCG. // // Note: PCG is a sequential state-transition generator rather than a counter-based PRNG, // so it is intended for CPU execution and is not decomposed into parallel GPU graph ops. // // Canonical state shape: [2]uint64 ([hi, lo]). // Native backend support: "go". RNGPCG // RNGChaCha8 specifies the counter-mode 8-round ChaCha8 stream cipher // Cryptographically Secure Pseudo-Random Number Generator (CSPRNG) (Bernstein, 2008). // // Generates 64-byte (16 x uint32) blocks independently from a 256-bit key and 64-bit block // counter, providing cryptographic-grade randomness while remaining fully parallelizable // across CPU threads/SIMD and GPUs. // // Canonical state shape: [5]uint64 ([key0, key1, key2, key3, blockCounter]). // Native backend support: "go" (plus automatic graph decomposition fallback in GoMLX). RNGChaCha8 )
func RNGAlgorithmString ¶ added in v0.1.32
func RNGAlgorithmString(s string) (RNGAlgorithm, error)
RNGAlgorithmString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.
func RNGAlgorithmValues ¶ added in v0.1.32
func RNGAlgorithmValues() []RNGAlgorithm
RNGAlgorithmValues returns all values of the enum
func (RNGAlgorithm) IsARNGAlgorithm ¶ added in v0.1.32
func (i RNGAlgorithm) IsARNGAlgorithm() bool
IsARNGAlgorithm returns "true" if the value is listed in the enum definition. "false" otherwise
func (RNGAlgorithm) IsCounterBased ¶ added in v0.1.32
func (a RNGAlgorithm) IsCounterBased() bool
IsCounterBased reports whether a is a parallel counter-based PRNG algorithm whose output blocks depend only on (key, counter+blockIndex).
func (RNGAlgorithm) StateFromSeed ¶ added in v0.1.32
StateFromSeed deterministically initializes a flat []uint64 slice and canonical state Shape for an explicit RNGAlgorithm from a 64-bit seed (expanding key words via SplitMix64 and setting counter words to 0; for RNGPCG, seeding hi/lo identically to rand.NewPCG).
Returns an error if called on RNGDefault; use Capabilities.RNGStateFromSeed instead.
func (RNGAlgorithm) StateShape ¶ added in v0.1.32
func (a RNGAlgorithm) StateShape() shapes.Shape
StateShape returns the canonical state tensor shape for an explicit RNGAlgorithm:
- RNGPhilox: [3]uint64
- RNGThreeFry: [2]uint64
- RNGSplitMix64: [2]uint64
- RNGPCG: [2]uint64
- RNGChaCha8: [5]uint64
- RNGDefault: shapes.Invalid (backend-dependent; use Capabilities.RNGStateShape)
func (RNGAlgorithm) String ¶ added in v0.1.32
func (i RNGAlgorithm) String() string
type ReduceOpType ¶
type ReduceOpType int
ReduceOpType select among the basic types of reduction supported.
const ( // ReduceOpUndefined is an undefined value. ReduceOpUndefined ReduceOpType = iota // ReduceOpSum reduces by summing all elements being reduced. ReduceOpSum // ReduceOpProduct reduces by multiplying all elements being reduced. ReduceOpProduct // ReduceOpMax reduces by taking the maximum value. ReduceOpMax // ReduceOpMin reduces by taking the minimum value. ReduceOpMin )
func ReduceOpTypeString ¶
func ReduceOpTypeString(s string) (ReduceOpType, error)
ReduceOpTypeString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.
func ReduceOpTypeValues ¶
func ReduceOpTypeValues() []ReduceOpType
ReduceOpTypeValues returns all values of the enum
func (ReduceOpType) IsAReduceOpType ¶
func (i ReduceOpType) IsAReduceOpType() bool
IsAReduceOpType returns "true" if the value is listed in the enum definition. "false" otherwise
func (ReduceOpType) String ¶
func (i ReduceOpType) String() string
type ScaledDotProductAttentionConfig ¶
type ScaledDotProductAttentionConfig struct {
// QuantizedMatmuls: if true, the backend may use dynamic per-head symmetric
// affine quantization (scale-only, no zero point) to convert float32 Q/K/V slices
// to uint8 for the Q@K^T and attn@V matmul stages. Accumulation is done in int32,
// then dequantized back to float32. Softmax and masking remain in float32.
// This matches ONNX DynamicQuantizeLinear semantics and trades some numerical
// precision for throughput on hardware with fast integer dot-product instructions
// (e.g. ARM SDOT/UDOT, x86 VNNI). Backends that do not support quantized matmuls
// ignore this flag and use float arithmetic.
QuantizedMatmuls bool
// QuerySeqLen, KeyValueSeqLen are optional per-batch actual sequence lengths
// (int32 tensors, shape [B]). When set, the backend masks by sequence length
// (padding mask) instead of a materialized [S,Skv] mask. Combined with causal=true
// this is a padding-causal mask. nil = unused.
QuerySeqLen, KeyValueSeqLen Value
// Bias is an optional additive attention-score bias broadcast to [B,H,S,Skv]
// (ALiBi / relative-position). NOT the Q/K/V projection bias. nil = unused.
Bias Value
// Scale is the scaling factor applied to query @ key^T.
// If 0 (the default), it means 1/sqrt(headDim).
Scale float64
// Causal specifies whether to apply causal (lower-triangular) masking.
Causal bool
// Mask is an optional attention mask of shape [seqLen, kvLen] (or broadcastable).
// Boolean mask: true = attend, false = ignore.
// Float/additive mask: added to scores before softmax.
Mask Value
}
ScaledDotProductAttentionConfig holds optional optimization hints and fused-attention parameters for FusedScaledDotProductAttention. A nil *ScaledDotProductAttentionConfig means "use defaults" (all optimizations disabled). Correctness-affecting fields (Bias, QuerySeqLen, KeyValueSeqLen, dropout, etc.): backends that cannot honor them MUST return ErrNotImplemented so the caller falls back to the decomposed path. Pure optimization hints (e.g. QuantizedMatmuls): backends that do not support them may silently ignore them and compute a numerically equivalent result in float arithmetic. nil/zero means "unused".
type ShardingSpec ¶
ShardingSpec holds a list of per tensor (or Node) axis of a list of Mesh axes names. Any tensor axis that doesn't have a corresponding ShardingSpec is considered replicated. And any tensor axis for which the list of Mesh axes is empty is also considered replicated.
The ShardingSpec also holds the Mesh name over which it is defined.
type StandardOps ¶
type StandardOps interface {
// Abs returns the Op that represents the output of the corresponding operation.
Abs(x Value) (Value, error)
// Add returns the element-wise sum of the two values.
// Standard broadcasting rules apply (see documentation).
Add(lhs, rhs Value) (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).
Atan2(lhs, rhs Value) (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.
ArgMinMax(x Value, axis int, outputDType dtypes.DType, isMin bool) (Value, error)
// BatchNormForInference implements batch normalization for inference.
//
// See details in https://www.tensorflow.org/xla/operation_semantics#batchnorminference.
//
// Based on the paper "Batch Normalization: Accelerating Deep Network Training by Reducing
// Internal Covariate Shift" (Sergey Ioffe, Christian Szegedy), https://arxiv.org/abs/1502.03167.
BatchNormForInference(operand, scale, offset, mean, variance Value, epsilon float32, featureAxis int) (Value, error)
// BatchNormForTraining implements batch normalization for training.
//
// See details in https://www.tensorflow.org/xla/operation_semantics#batchnormtraining.
//
// It returns the normalized tensor, the batchMean, and the batchVariance.
//
// Based on the paper "Batch Normalization: Accelerating Deep Network Training by Reducing
// Internal Covariate Shift" (Sergey Ioffe, Christian Szegedy), https://arxiv.org/abs/1502.03167.
BatchNormForTraining(
operand, scale, offset Value,
epsilon float32,
featureAxis int,
) (normalized Value, batchMean Value, batchVariance Value, err error)
// BatchNormGradient calculates the batch normalization gradients with respect to the input, scale, and offset.
//
// See details in https://openxla.org/xla/operation_semantics#batchnormgrad
//
// The gradOutput is the adjoint gradient (the "V" in "VJP"), that is, the gradient with respect to the output of the
// batch normalization.
//
// Based on the paper "Batch Normalization: Accelerating Deep Network Training by Reducing
// Internal Covariate Shift" (Sergey Ioffe, Christian Szegedy), https://arxiv.org/abs/1502.03167.
BatchNormGradient(
operand, scale, mean, variance, gradOutput Value,
epsilon float32,
featureAxis int,
) (gradOperand Value, gradScale Value, gradOffset Value, err 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).
Bitcast(operand Value, targetDType dtypes.DType) (Value, error)
// BitCount returns the number of bits that are set to one.
// Also known as Population Count ("Popcnt") or Hamming Weight.
BitCount(operand Value) (Value, error)
// BitwiseAnd returns the element-wise bitwise AND operation.
BitwiseAnd(lhs, rhs Value) (Value, error)
// BitwiseNot returns the element-wise bitwise AND operation.
BitwiseNot(x Value) (Value, error)
// BitwiseOr returns the element-wise bitwise OR operation.
BitwiseOr(lhs, rhs Value) (Value, error)
// BitwiseXor returns the element-wise bitwise XOR operator.
BitwiseXor(lhs, rhs Value) (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.
BroadcastInDim(operand Value, outputShape shapes.Shape, broadcastAxes []int) (Value, error)
// Ceil returns the Op that represents the output of the corresponding operation.
Ceil(x Value) (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.
Clamp(min, x, max Value) (Value, error)
// Clz returns element-wise the "count leading zeros" bits of input node x -- for integer values.
Clz(x Value) (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.
Complex(lhs, rhs Value) (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).
Concatenate(axis int, operands ...Value) (Value, error)
// Conj returns the conjugate of a complex number. E.g: Conj(1+3i) = 1-3i
Conj(x Value) (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).
ConvGeneral(
input, kernel Value,
axes ConvolveAxesConfig,
strides []int,
paddings [][2]int,
inputDilations, kernelDilations []int,
channelGroupCount, batchGroupCount int,
) (Value, error)
// ConvertDType of x to dtype.
ConvertDType(x Value, dtype dtypes.DType) (Value, error)
// Cos returns the Op that represents the output of the corresponding operation.
Cos(x Value) (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]
CumMax(operand Value, axis int, options CumSumOptions) (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]
CumSum(operand Value, axis int, options CumSumOptions) (Value, error)
// Div returns the element-wise division of the two values.
// Standard broadcasting rules apply (see documentation).
Div(lhs, rhs Value) (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.
DotGeneral(
lhs Value,
lhsContractingAxes, lhsBatchAxes []int,
rhs Value,
rhsContractingAxes, rhsBatchAxes []int,
config DotGeneralConfig,
) (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).
DynamicShape(operand Value) (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
DynamicSlice(operand Value, startIndices []Value, sliceDims []int) (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])
DynamicUpdateSlice(operand, update Value, startIndices []Value) (Value, error)
// Equal performs element-wise equality check, returns boolean results with the same dimensions as input.
Equal(lhs, rhs Value) (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`.
EqualTotalOrder(lhs, rhs Value) (Value, error)
// Erf returns the "error function", defined as erf(x) = 2/Pi * \int_{0}^{x}{e^{-t^2}dt}.
Erf(x Value) (Value, error)
// Exp returns the Op that represents the output of the corresponding operation.
Exp(x Value) (Value, error)
// Expm1 returns the Op that represents the output of the corresponding operation.
Expm1(x Value) (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.
FFT(operand Value, fftType FFTType, fftLength []int) (Value, error)
// Floor returns the Op that represents the output of the corresponding operation.
Floor(x Value) (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.
Gather(
operand, startIndices Value,
indexVectorAxis int,
offsetOutputAxes, collapsedSliceAxes, startIndexMap, sliceSizes []int,
indicesAreSorted bool,
) (Value, error)
// GreaterOrEqual performs element-wise comparison, returns boolean results with the same dimensions as input.
GreaterOrEqual(lhs, rhs Value) (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`.
GreaterOrEqualTotalOrder(lhs, rhs Value) (Value, error)
// GreaterThan performs element-wise comparison, returns boolean results with the same dimensions as input.
GreaterThan(lhs, rhs Value) (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`.
GreaterThanTotalOrder(lhs, rhs Value) (Value, error)
// Identity returns an Op whose output is the same as its input.
// It's a no-op that can serve as a place-holder.
Identity(x Value) (Value, error)
// Imag returns the imaginary part of a complex number. It returns 0 if the x is a float number.
Imag(x Value) (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]].
Iota(shape shapes.Shape, iotaAxis int) (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.
IsFinite(x Value) (Value, error)
// IsNaN tests whether each element of operand is NaN, i.e., if it is not a finite number.
IsNaN(x Value) (Value, error)
// LessOrEqual performs element-wise comparison, returns boolean results with the same dimensions as input.
LessOrEqual(lhs, rhs Value) (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`.
LessOrEqualTotalOrder(lhs, rhs Value) (Value, error)
// LessThan performs element-wise comparison, returns boolean results with the same dimensions as input.
LessThan(lhs, rhs Value) (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`.
LessThanTotalOrder(lhs, rhs Value) (Value, error)
// Log returns the Op that represents the output of the corresponding operation.
Log(x Value) (Value, error)
// Log1p returns the expression log(x+1).
Log1p(x Value) (Value, error)
// LogicalAnd returns the element-wise logical AND operation.
LogicalAnd(lhs, rhs Value) (Value, error)
// LogicalNot returns the Op that represents the output of the corresponding operation.
LogicalNot(x Value) (Value, error)
// LogicalOr returns the element-wise logical OR operation.
LogicalOr(lhs, rhs Value) (Value, error)
// LogicalXor returns the element-wise logical XOR operator.
LogicalXor(lhs, rhs Value) (Value, error)
// Logistic returns the element-wise expression 1/(1+exp(-x)). Also known as the Sigmoid function.
Logistic(x Value) (Value, error)
// Max returns the element-wise highest value among the two.
Max(lhs, rhs Value) (Value, error)
// Min returns the element-wise smallest value among the two.
Min(lhs, rhs Value) (Value, error)
// Mul returns the element-wise multiplication of the two values.
// Standard broadcasting rules apply (see documentation).
Mul(lhs, rhs Value) (Value, error)
// Neg returns the Op that represents the output of the corresponding operation.
Neg(x Value) (Value, error)
// NotEqual performs element-wise inequality check, returns boolean results with the same dimensions as input.
NotEqual(lhs, rhs Value) (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`.
NotEqualTotalOrder(lhs, rhs Value) (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).
Pad(x, fillValue Value, axesConfig ...PadAxis) (Value, error)
// Pow returns the Op that represents the output of the corresponding operation.
Pow(lhs, rhs Value) (Value, error)
// Real return the real part of a complex number. It returns x if the x is a float number.
Real(x Value) (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.
ReduceBitwiseAnd(x Value, axes ...int) (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.
ReduceBitwiseOr(x Value, axes ...int) (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.
ReduceBitwiseXor(x Value, axes ...int) (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.
ReduceLogicalAnd(x Value, axes ...int) (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.
ReduceLogicalOr(x Value, axes ...int) (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.
ReduceLogicalXor(x Value, axes ...int) (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.
ReduceMax(x Value, axes ...int) (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.
ReduceMin(x Value, axes ...int) (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.
ReduceProduct(x Value, axes ...int) (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.
ReduceSum(x Value, axes ...int) (Value, error)
// ReduceWindow runs a reduction function of the type given by reductionType,
// it can be either ReduceMaxNode, ReduceSumNode, or ReduceMultiplyNode.
//
// - reductionType: the type of reduction to perform. E.g.: [ReduceOpMax], [ReduceOpSum],...
// - windowDimensions: the dimensions of the window, must be defined for each axis.
// - strides: stride over elements in each axis for each window reduction. If nil, it's assume to be the
// same as the windowDimensions -- that is, the strides jump a window at a time.
// - inputDilations: "virtually" expand the input by introducing "holes" between elements. I.e. if
// inputDilations are 2, then the input is expanded 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.
// - windowDilations: "virtually" expand the window 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.
// - paddings: virtual padding to be added to the input at the edges (start and end) of each axis.
// If nil, it's assumed to be 0 for each axis.
//
// Dynamic shapes: Operation on a dynamic axis that changes its size (stride > 1, padding != 0,
// window > 1, etc.) is currently not supported (requires axis expressions).
ReduceWindow(
input Value,
reductionType ReduceOpType,
windowDimensions, strides, inputDilations, windowDilations []int,
paddings [][2]int,
) (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.
Rem(lhs, rhs Value) (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.
Reshape(x Value, dimensions ...int) (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.
Reverse(x Value, axes ...int) (Value, error)
// RNGBitGenerator generates a tensor of the given shape filled with uniformly distributed
// random bits using the specified Random Number Generator (RNG) algorithm, returning the
// updated state tensor and the generated random bits.
//
// - state: 1D state tensor matching backend.Capabilities().RNGStateShape(algorithm)
// (which equals algorithm.StateShape() for all explicit algorithms).
// - shape: target output shape. Its DType must be an unsigned integer type
// (Uint8, Uint16, Uint32, or Uint64). Dimensions may be dynamic on backends
// that support dynamic shapes.
// - algorithm: Pseudo-Random Number Generator (PRNG) algorithm to execute
// ([RNGDefault] for the backend's preferred native generator, or an explicit algorithm
// such as [RNGPhilox] or [RNGThreeFry] for cross-backend reproducibility).
// If unsupported by the backend, returns an error wrapping [ErrNotImplemented].
RNGBitGenerator(state Value, shape shapes.Shape, algorithm RNGAlgorithm) (newState Value, values Value, err error)
// Round returns the Op that represents the output of the corresponding operation.
// This operation rounds to the nearest even.
Round(x Value) (Value, error)
// Rsqrt returns the element-wise reciprocal of square root operation 1/sqrt(x).
Rsqrt(x Value) (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.
ScatterMax(
operand, scatterIndices, updates Value,
indexVectorAxis int,
updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int,
indicesAreSorted, uniqueIndices bool,
) (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.
ScatterMin(
operand, scatterIndices, updates Value,
indexVectorAxis int,
updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int,
indicesAreSorted, uniqueIndices bool,
) (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.
ScatterSum(
operand, scatterIndices, updates Value,
indexVectorAxis int,
updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int,
indicesAreSorted, uniqueIndices bool,
) (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
SelectAndScatterMax(operand, source Value, windowDimensions, windowStrides []int, paddings [][2]int) (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
SelectAndScatterMin(operand, source Value, windowDimensions, windowStrides []int, paddings [][2]int) (Value, error)
// ShiftLeft n bits. It implicitly preserves the sign bit if there is no overflow. So ShiftLeft(-1, 1) = -2.
ShiftLeft(lhs, rhs Value) (Value, error)
// ShiftRightArithmetic shifts right by n bits, preserving the sign bit. So ShiftRight(-2, 1) = -1.
ShiftRightArithmetic(lhs, rhs Value) (Value, error)
// ShiftRightLogical shifts right by n bits, destroying the sign bit.
ShiftRightLogical(lhs, rhs Value) (Value, error)
// Sign returns element-wise +1, +/-0 or -1 depending on the sign of x. It returns NaN if the input is NaN.
Sign(x Value) (Value, error)
// Sin returns the Op that represents the output of the corresponding operation.
Sin(x Value) (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.
Slice(x Value, starts, limits, strides []int) (Value, error)
// Sqrt returns the Op that represents the output of the corresponding operation.
Sqrt(x Value) (Value, error)
// Sub returns the element-wise subtraction of the two values.
// Standard broadcasting rules apply (see documentation).
Sub(lhs, rhs Value) (Value, error)
// Tanh returns the Op that represents the output of the corresponding operation.
Tanh(x Value) (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]].
Transpose(x Value, permutation ...int) (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.
Where(condition, onTrue, onFalse Value) (Value, error)
// OptimizationBarrier introduces an optimization barrier.
// Returned values are identity to the operands, but they prevent the compiler from optimizing across the barrier.
OptimizationBarrier(operands ...Value) ([]Value, error)
// SchedulingBarrier introduces a scheduling barrier.
// Returned value is identity to the operand, but it is guaranteed to depend on all the dependencies.
SchedulingBarrier(operand Value, dependencies ...Value) (Value, error)
}
StandardOps lists the bulk of the operations that a backends.Builder must support.
Standard Implicit Broadcasting Rules ¶
Element-wise binary operations (such as Add, Sub, Mul, Div, comparisons, logical/bitwise ops, and shifts) and Where follow strict compile-time implicit broadcasting rules:
- Scalar operands (rank 0) are implicitly broadcast to the shape of the other operand(s).
- Non-scalar operands must have the exact same rank (use Reshape / DynamicReshape or BroadcastInDim / DynamicBroadcastInDim to insert size-1 axes when ranks differ).
- For each axis, operand dimensions must either match or be statically 1. A static dimension of 1 is broadcast (replicated N times) to the other operand's dimension N — including N == 0, which yields an empty axis of size 0 (whereas a non-1 dimension such as 0 cannot be broadcast to N > 0).
- Dynamic shapes: Whether an axis broadcasts is strictly a compile-time property. A static dimension of 1 implicitly broadcasts to a dynamic dimension, and two compatible dynamic dimensions (matching user axis names, or '#'-prefixed generated axis names verified equal at runtime) pair element-wise without broadcasting. However, an unknown/dynamic dimension will fail to implicitly broadcast with a non-1 static dimension (e.g., pairing ["batch", "#features"] with ["batch", 12] fails at graph-build time); callers can explicitly assert equality by reshaping the dynamic operand's axis to the known static value via DynamicReshape (or explicitly request runtime 1-or-match broadcasting via DynamicBroadcastInDim).
type Value ¶
type Value any
Value represents the output of an operation, during the computation graph building time.
It is opaque from the GoMLX perspective: it passes Value as input to the other methods.
func BitsToUniformFloat ¶ added in v0.1.32
BitsToUniformFloat builds standard Function operations (Constant, ShiftRightLogical, ConvertDType, Mul) to convert uniformly distributed unsigned integer bits (Uint8, Uint16, Uint32, or Uint64) into uniformly distributed floating-point values in the half-open interval [0.0, 1.0) of floatDType (dtypes.BFloat16, dtypes.Float16, dtypes.Float32, or dtypes.Float64).
It preserves exact IEEE-754 significand precision p by right-shifting (bits >> (W - p)) before converting to floatDType and scaling by 2^-p, guaranteeing every output is strictly < 1.0 without rounding artifacts or clamping.
Required minimum bit width W of randomBits:
- dtypes.Float64 (p=53): Uint64
- dtypes.Float32 (p=24): Uint32 or Uint64
- dtypes.Float16 (p=11): Uint16, Uint32, or Uint64
- dtypes.BFloat16 (p=8): Uint8, Uint16, Uint32, or Uint64
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package distributed defines the following objects related to cross-device execution:
|
Package distributed defines the following objects related to cross-device execution: |
|
Package dtypes includes the DType enum for all supported data types for GoMLX and the compute backends.
|
Package dtypes includes the DType enum for all supported data types for GoMLX and the compute backends. |
|
bfloat16
Package bfloat16 is a trivial implementation for the bfloat16 type, based on https://github.com/x448/float16 and the pending issue in https://github.com/x448/float16/issues/22
|
Package bfloat16 is a trivial implementation for the bfloat16 type, based on https://github.com/x448/float16 and the pending issue in https://github.com/x448/float16/issues/22 |
|
float16
Package float16 implements the IEEE 754 half-precision floating-point format (binary16).
|
Package float16 implements the IEEE 754 half-precision floating-point format (binary16). |
|
gotype
Package gotype defines several constraints based on Go types supported by the dtypes package.
|
Package gotype defines several constraints based on Go types supported by the dtypes package. |
|
Package gobackend implements a native Go compute.Backend: very portable (including WASM) but not very fast.
|
Package gobackend implements a native Go compute.Backend: very portable (including WASM) but not very fast. |
|
internal
|
|
|
cmd/alternates_generator
command
|
|
|
cmd/gobackend_dtypemap
command
|
|
|
cmd/gobackend_ops_generator
command
gobackend_generator auto-generates parts of the Go backend:
|
gobackend_generator auto-generates parts of the Go backend: |
|
cmd/gobackend_opsregistration
command
gobackends_ops_registration generates a registration system for each of the compute.StandardOps methods, so they can be implemented separated by separate packages, as well as stub methods for `gobackends.Backend` that calls the corresponding registered method if configured.
|
gobackends_ops_registration generates a registration system for each of the compute.StandardOps methods, so they can be implemented separated by separate packages, as well as stub methods for `gobackends.Backend` that calls the corresponding registered method if configured. |
|
cmd/notimplemented_generator
command
notimplemented_generator generates "notimplemented" stubs for every API of the compute.Backend interface
|
notimplemented_generator generates "notimplemented" stubs for every API of the compute.Backend interface |
|
exceptions
Package exceptions provide helper functions to leverage Go's `panic`, `recover` and `defer` as an "exceptions" system.
|
Package exceptions provide helper functions to leverage Go's `panic`, `recover` and `defer` as an "exceptions" system. |
|
fastmath
Package fastmath provides faster float32 approximations of selected math functions for use in go-backend kernels where small errors are acceptable (e.g.
|
Package fastmath provides faster float32 approximations of selected math functions for use in go-backend kernels where small errors are acceptable (e.g. |
|
gobackend
Package gobackend implements a compute.Backend using Go only.
|
Package gobackend implements a compute.Backend using Go only. |
|
gobackend/activations/avx2
Package avx2 provides AVX2 SIMD implementations for activations.
|
Package avx2 provides AVX2 SIMD implementations for activations. |
|
gobackend/activations/avx512
Package avx512 provides AVX-512 SIMD implementations for activations.
|
Package avx512 provides AVX-512 SIMD implementations for activations. |
|
gobackend/activations/neon
Package neon provides ARM64 AdvSIMD (NEON) implementations for activations.
|
Package neon provides ARM64 AdvSIMD (NEON) implementations for activations. |
|
gobackend/avx2
Package avx2 provides AVX2 SIMD implementations for gobackend helpers.
|
Package avx2 provides AVX2 SIMD implementations for gobackend helpers. |
|
gobackend/avx512
Package avx512 provides AVX-512 SIMD implementations for gobackend helpers.
|
Package avx512 provides AVX-512 SIMD implementations for gobackend helpers. |
|
gobackend/defaultpkgs
Package defaultpkgs imports all the sub-packages that implement the gobackend.
|
Package defaultpkgs imports all the sub-packages that implement the gobackend. |
|
gobackend/dot
Package dot implements a general-purpose "dot product" ("Einsum") computation.
|
Package dot implements a general-purpose "dot product" ("Einsum") computation. |
|
gobackend/dot/matmul
package matmul provides the base implementations of matrx multiply for DotGeneral.
|
package matmul provides the base implementations of matrx multiply for DotGeneral. |
|
gobackend/dot/matmul/avx2
Package avx2 provides AVX2 accelerated matrix multiplication kernels.
|
Package avx2 provides AVX2 accelerated matrix multiplication kernels. |
|
gobackend/dot/matmul/avx512
Package avx512 provides AVX-512 accelerated matrix multiplication kernels.
|
Package avx512 provides AVX-512 accelerated matrix multiplication kernels. |
|
gobackend/dot/matmul/matmultest
Package matmultest provides test helpers for verifying matrix multiplication packing and output routines.
|
Package matmultest provides test helpers for verifying matrix multiplication packing and output routines. |
|
gobackend/dot/matmul/neon
Package neon implements ARM64 NEON accelerated matrix multiplication (DotGeneral) kernels for the Go backend.
|
Package neon implements ARM64 NEON accelerated matrix multiplication (DotGeneral) kernels for the Go backend. |
|
gobackend/fusedops/avx2
Package avx2 provides AVX2 SIMD implementations for fused operations.
|
Package avx2 provides AVX2 SIMD implementations for fused operations. |
|
gobackend/fusedops/avx512
Package avx512 provides AVX2 SIMD implementations for fused operations.
|
Package avx512 provides AVX2 SIMD implementations for fused operations. |
|
gobackend/fusedops/neon
Package neon provides ARM64 NEON SIMD implementations for fused operations.
|
Package neon provides ARM64 NEON SIMD implementations for fused operations. |
|
gobackend/neon
Package neon provides ARM64 NEON SIMD implementations for gobackend helpers.
|
Package neon provides ARM64 NEON SIMD implementations for gobackend helpers. |
|
gobackend/ops
Package ops has the base implementation for most operations for the Go backend.
|
Package ops has the base implementation for most operations for the Go backend. |
|
gobackend/ops/avx2
Package avx2 provides AVX2 SIMD implementations for normal operations.
|
Package avx2 provides AVX2 SIMD implementations for normal operations. |
|
gobackend/ops/avx512
Package avx512 provides AVX2 SIMD implementations for normal operations.
|
Package avx512 provides AVX2 SIMD implementations for normal operations. |
|
gobackend/ops/neon
Package neon provides ARM64 AdvSIMD (NEON) accelerated kernels for standard operations.
|
Package neon provides ARM64 AdvSIMD (NEON) accelerated kernels for standard operations. |
|
gobackend/scheduler
Package scheduler implements the runtime execution scheduler for the Go compute backend.
|
Package scheduler implements the runtime execution scheduler for the Go compute backend. |
|
gobackend/simdarch
Package simdarch provides CPU SIMD architecture detection, feature flags, assembly toggle switches, and hardware SME cluster topology and locking for the Go backend.
|
Package simdarch provides CPU SIMD architecture detection, feature flags, assembly toggle switches, and hardware SME cluster topology and locking for the Go backend. |
|
must
Package must provide a set of functions that check for errors and panic on error.
|
Package must provide a set of functions that check for errors and panic on error. |
|
Package notimplemented implements a compute.Builder interface that returns a "not implemented" error for all operations.
|
Package notimplemented implements a compute.Builder interface that returns a "not implemented" error for all operations. |
|
Package shapeinference calculates the shape resulting from operations and validates its inputs.
|
Package shapeinference calculates the shape resulting from operations and validates its inputs. |
|
Package shapes define Shape and DType and associated tools.
|
Package shapes define Shape and DType and associated tools. |
|
Package support and its subpackages contains various supporting functionality for gomlx/compute that may be also useful for other users or GoMLX projects, as well as to other compute.Backend implementations.
|
Package support and its subpackages contains various supporting functionality for gomlx/compute that may be also useful for other users or GoMLX projects, as well as to other compute.Backend implementations. |
|
backendparser
Package backendparser parses the compute interfaces (Backend, Builder, Function, etc.) and enumerate their methods.
|
Package backendparser parses the compute interfaces (Backend, Builder, Function, etc.) and enumerate their methods. |
|
envutil
Package envutil provides utility functions for working with environment variables.
|
Package envutil provides utility functions for working with environment variables. |
|
humanize
Package humanize provides human-readable representations of numbers, bytes, durations, speed (units/sec), etc.
|
Package humanize provides human-readable representations of numbers, bytes, durations, speed (units/sec), etc. |
|
sets
Package sets implement a set type as a `map[T]struct{}` but with better ergonomics.
|
Package sets implement a set type as a `map[T]struct{}` but with better ergonomics. |
|
simdmath
Package simdmath provides vector SIMD approximations of mathematical operations (Exp, Tanh, Erf, Sqrt, Inv, Sigmoid, Gelu) across floating-point data types using Go's portable simd package.
|
Package simdmath provides vector SIMD approximations of mathematical operations (Exp, Tanh, Erf, Sqrt, Inv, Sigmoid, Gelu) across floating-point data types using Go's portable simd package. |
|
testutil
Package testutil provides utilities for testing a compute.Backend.
|
Package testutil provides utilities for testing a compute.Backend. |
|
xslices
Package xslices provide missing functionality to the slices package.
|
Package xslices provide missing functionality to the slices package. |
|
xsync
Package xsync implements some extra synchronization tools.
|
Package xsync implements some extra synchronization tools. |