xla

package
v0.4.21 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 31 Imported by: 2 modules, 1 package

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

README

XLA Backend for the github.com/gomlx/compute package.

Package xla implements a GoMLX backend, that is, a github.com/gomlx/compute.Backend interface using Google's XLA (PJRT) as a backend.

The backend is registered with the aliases "xla", "stablehlo", "shlo" or "hlo" (all aliases to the same backend).

XLA/PJRT uses C++ written PJRT "plugins", .so files that implements XLA(PRJT). They are loaded dynamically in the program.

By default, the this XLA backend loads the requested plugins after the program starts and specifies the desired plugin name (default to "cpu") using dlopen.

If the plugins are not available, the backend can download them automatically ("auto-install") if the autoinstall package is imported (e.g. import _ "github.com/gomlx/go-xla/compute/xla/autoinstall"):

  • From github.com/gomlx/pjrt-cpu-binaries for CPU PJRT plugins.
  • From pypi.org, using the Jax packages for the CUDA and TPU PJRT plugins.

Auto-install has no effect if default plugins are already installed. But to control it you can:

  • Import _ "github.com/gomlx/go-xla/compute/xla/autoinstall" to enable auto-installation.
  • Call xla.AutoInstall() directly if you want to call it immediately (requires autoinstall to be imported).
  • Configure it with xla.EnableAutoInstall() if you want to enable/disable it globally (default is enabled).
  • Set GOMLX_NO_AUTO_INSTALL, which sets the global auto-install flag to false -- but it can be overridden by calling xla.EnableAutoInstall().

Experimentally, one can get this backend to work with pre-linked PJRT plugins, but it will require the user to add the .so files in a library in LD_LIBRARY_PATH, or precompile a .a static library.

  • Pre-link the CPU PJRT plugin statically: this will generate a bigger binary (+ ~200Mb, so slower to build), but allows one to build a static binary that can be deployed without extra dependencies (except the standard C and C++ libraries, usually available in most machines). To enable, build using the tag pjrt_cpu_static (e.g.: go build --tags pjrt_cpu_static ...), or import github.com/gomlx/gomlx/backends/xla/cpu/static. Both methods have the same effect.
  • Pre-link the CPU PJRT plugin dynamically: build with the build tag pjrt_cpu_dynamic (e.g.: go test --tags pjrt_cpu_dynamic ...), or import github.com/gomlx/gomlx/backends/xla/cpu/dynamic. Not much difference from linking the PJRT plugin after the program starts, as default.

Shared Buffers Support:

XLA/PJRT for CPU allows the "device buffer" (where device=CPU) to be addressed directly, which saves the copy from "host/local tensor" to the "on-device tensor" when executing a computation. This is enabled by default if the plugin is called "cpu". To force advertising support for this for other PJRTs provide the "shared_buffers" option, e.g.: GOMLX_BACKEND="xla:my_pjrt,shared_buffers". Or to force disabling the support, provide the "noshared_buffers" option.

Options

Those can be passed after the plugin name, e.g.: GOMLX_BACKEND="xla:my_pjrt,notf32,shared_buffers".

  • "tf32", "notf32": controls whether to use TF32 for DotGeneral operations that are using float32 (it can be faster in modern GPUs). It's enabled by default.
  • "shared_buffers", "noshared_buffers": controls whether to use shared buffers for the device buffer (where device=CPU). It's enabled by default if the plugin is called "cpu".

Documentation

Overview

Package xla implements a GoMLX backend, that is, a `github.com/gomlx/compute.Backend` interface using [Google's XLA (PJRT)](https://openxla.org/) as a backend.

The backend is registered with the aliases "xla", "stablehlo", "shlo" or "hlo" (all aliases to the same backend).

XLA/PJRT uses C++ written PJRT "plugins", `.so` files that implements XLA(PRJT). They are loaded dynamically in the program.

By default, the this XLA backend loads the requested plugins after the program starts and specifies the desired plugin name (default to "cpu") using `dlopen`.

If the plugins are not available, the backend can download them automatically ("auto-install") if the autoinstall package is imported (e.g. `import _ "github.com/gomlx/go-xla/compute/xla/autoinstall"`):

- From github.com/gomlx/pjrt-cpu-binaries for CPU PJRT plugins. - From pypi.org, using the Jax packages for the CUDA and TPU PJRT plugins.

Auto-install has no effect if default plugins are already installed. But to control it you can:

  • Call xla.AutoInstall() directly if you want to call it immediately.
  • Configure it with xla.EnableAutoInstall() if you want to enable/disable it globally (default is enabled).
  • Set GOMLX_NO_AUTO_INSTALL, which sets the global auto-install flag to false -- but it can be overridden by calling xla.EnableAutoInstall().

Experimentally, one can get this backend to work with pre-linked PJRT plugins, but it will require the user to add the `.so` files in a library in LD_LIBRARY_PATH, or precompile a `.a` static library.

  • Pre-link the CPU PJRT plugin statically: this will generate a bigger binary (+ ~200Mb, so slower to build), but allows one to build a static binary that can be deployed without extra dependencies (except the standard C and C++ libraries, usually available in most machines). To enable, build using the tag `pjrt_cpu_static` (e.g.: `go build --tags pjrt_cpu_static ...`), or import `github.com/gomlx/gomlx/backends/xla/cpu/static`. Both methods have the same effect.
  • Pre-link the CPU PJRT plugin dynamically: build with the build tag `pjrt_cpu_dynamic` (e.g.: `go test --tags pjrt_cpu_dynamic ...`), or import `github.com/gomlx/gomlx/backends/xla/cpu/dynamic`. Not much difference from linking the PJRT plugin after the program starts, as default.

Shared Buffers Support:

XLA/PJRT for CPU allows the "device buffer" (where device=CPU) to be addressed directly, which saves the copy from "host/local tensor" to the "on-device tensor" when executing a computation. This is enabled by default if the plugin is called "cpu". To force advertising support for this for other PJRTs provide the "shared_buffers" option, e.g.: GOMLX_BACKEND="xla:my_pjrt,shared_buffers". Or to force disabling the support, provide the "noshared_buffers" option.

Options

Those can be passed after the plugin name, e.g.: GOMLX_BACKEND="xla:cuda,tf32=false,preallocate=false".

  • "tf32" (boolean, default=true): controls whether to use TF32 for DotGeneral operations that are using float32 (it can be faster in modern GPUs). It's enabled by default.
  • "shared_buffer" (boolean, default=true): controls whether to use shared buffers for the device buffer (where device=CPU). It's enabled by default if the plugin is called "cpu".
  • "preallocate" (boolean, default=true): whether the CUDA PJRT preallocates a large portion of the memory.
  • "memory_fraction" (float, default=0.75): how much memory to preallocate.
  • "allocator" (string, default="default"): which allocator to use. For CUDA the available ones are "default" (== "bfc"), "bfc" ("best-fit for coalescing", avoids framementation), "cuda_async" (dynamic, no preallocation), "platform" (slow, good for debugging), "vmm"
  • "visible_devices" (list of integers, e.g., "0;1;2"): list IDs of the devices made visible to the backend.
  • "use_tfrt_gpu_client" (boolean, default=false): uses the "TFRT" dispatcher for GPU.

(NO) Dynamic Shapes

XLA doesn't support dynamic shapes. Sort of ... it suppots, but any new shape triggers a re-compilation, something that GoMLX and other compute.Backend clients already supprot.

So it does NOT support dynamic shapes in the compute.Backend sense, which implies a low cost execution overhead for various shapes.

Index

Constants

View Source
const BackendName = "xla"

BackendName is the name of the backend.

The stablehlo backend also accepts the "xla", "hlo" and "pjrt" aliases.

View Source
const NoAutoInstallEnv = "GOMLX_NO_AUTO_INSTALL"

Variables

View Source
var Capabilities = compute.Capabilities{
	Operations: map[compute.OpType]bool{

		compute.OpTypeParameter: true,
		compute.OpTypeConstant:  true,

		compute.OpTypeAbs:        true,
		compute.OpTypeBitCount:   true,
		compute.OpTypeBitwiseNot: true,
		compute.OpTypeCeil:       true,
		compute.OpTypeClz:        true,
		compute.OpTypeCos:        true,
		compute.OpTypeErf:        true,
		compute.OpTypeExp:        true,
		compute.OpTypeExpm1:      true,
		compute.OpTypeFloor:      true,
		compute.OpTypeIsFinite:   true,
		compute.OpTypeIsNaN:      true,
		compute.OpTypeLog1p:      true,
		compute.OpTypeLog:        true,
		compute.OpTypeLogicalNot: true,
		compute.OpTypeLogistic:   true,
		compute.OpTypeNeg:        true,
		compute.OpTypeRound:      true,
		compute.OpTypeRsqrt:      true,
		compute.OpTypeSign:       true,
		compute.OpTypeSin:        true,
		compute.OpTypeSqrt:       true,
		compute.OpTypeTanh:       true,

		compute.OpTypeAdd:        true,
		compute.OpTypeBitwiseAnd: true,
		compute.OpTypeBitwiseOr:  true,
		compute.OpTypeBitwiseXor: true,
		compute.OpTypeDiv:        true,
		compute.OpTypeLogicalAnd: true,
		compute.OpTypeLogicalOr:  true,
		compute.OpTypeLogicalXor: true,
		compute.OpTypeMax:        true,
		compute.OpTypeMin:        true,
		compute.OpTypeMul:        true,
		compute.OpTypePow:        true,
		compute.OpTypeRem:        true,
		compute.OpTypeSub:        true,

		compute.OpTypeEqual:                    true,
		compute.OpTypeEqualTotalOrder:          true,
		compute.OpTypeGreaterOrEqual:           true,
		compute.OpTypeGreaterOrEqualTotalOrder: true,
		compute.OpTypeGreaterThan:              true,
		compute.OpTypeGreaterThanTotalOrder:    true,
		compute.OpTypeLessOrEqual:              true,
		compute.OpTypeLessOrEqualTotalOrder:    true,
		compute.OpTypeLessThan:                 true,
		compute.OpTypeLessThanTotalOrder:       true,
		compute.OpTypeNotEqual:                 true,
		compute.OpTypeNotEqualTotalOrder:       true,

		compute.OpTypeComplex: true,
		compute.OpTypeConj:    true,
		compute.OpTypeImag:    true,
		compute.OpTypeReal:    true,

		compute.OpTypeArgMinMax:             true,
		compute.OpTypeBatchNormForInference: true,
		compute.OpTypeBatchNormForTraining:  true,
		compute.OpTypeBatchNormGradient:     true,
		compute.OpTypeBitcast:               true,
		compute.OpTypeBroadcastInDim:        true,
		compute.OpTypeClamp:                 true,
		compute.OpTypeConcatenate:           true,
		compute.OpTypeConvertDType:          true,
		compute.OpTypeConvGeneral:           true,
		compute.OpTypeDynamicSlice:          true,
		compute.OpTypeDynamicUpdateSlice:    true,
		compute.OpTypeDot:                   true,
		compute.OpTypeDotGeneral:            true,
		compute.OpTypeFFT:                   true,
		compute.OpTypeGather:                true,
		compute.OpTypeIdentity:              true,
		compute.OpTypeIota:                  true,
		compute.OpTypePad:                   true,
		compute.OpTypeReduceBitwiseAnd:      true,
		compute.OpTypeReduceBitwiseOr:       true,
		compute.OpTypeReduceBitwiseXor:      true,
		compute.OpTypeReduceLogicalAnd:      true,
		compute.OpTypeReduceLogicalOr:       true,
		compute.OpTypeReduceLogicalXor:      true,
		compute.OpTypeReduceMax:             true,
		compute.OpTypeReduceMin:             true,
		compute.OpTypeReduceProduct:         true,
		compute.OpTypeReduceSum:             true,
		compute.OpTypeReduceWindow:          true,
		compute.OpTypeReshape:               true,
		compute.OpTypeReverse:               true,
		compute.OpTypeRNGBitGenerator:       true,
		compute.OpTypeScatterSum:            true,
		compute.OpTypeScatterMax:            true,
		compute.OpTypeScatterMin:            true,
		compute.OpTypeSelectAndScatterMax:   true,
		compute.OpTypeSelectAndScatterMin:   true,
		compute.OpTypeShiftLeft:             true,
		compute.OpTypeShiftRightArithmetic:  true,
		compute.OpTypeShiftRightLogical:     true,
		compute.OpTypeSlice:                 true,
		compute.OpTypeTranspose:             true,
		compute.OpTypeWhere:                 true,
		compute.OpTypeOptimizationBarrier:   true,
		compute.OpTypeSchedulingBarrier:     true,

		compute.OpTypeAllReduce: true,
	},

	Functions:   true,
	DynamicAxes: false,

	DynamicShapes:   compute.DynamicShapesNone,
	DynamicDimDType: dtypes.Int32,

	DTypes: map[dtypes.DType]bool{
		dtypes.Bool:       true,
		dtypes.Int8:       true,
		dtypes.Int16:      true,
		dtypes.Int32:      true,
		dtypes.Int64:      true,
		dtypes.Uint8:      true,
		dtypes.Uint16:     true,
		dtypes.Uint32:     true,
		dtypes.Uint64:     true,
		dtypes.Float32:    true,
		dtypes.Float64:    true,
		dtypes.BFloat16:   true,
		dtypes.Complex64:  true,
		dtypes.Complex128: true,
	},
}

Capabilities of the Go backends: the set of supported operations and data types.

View Source
var (
	// DefaultPlugins is the list of plugins to use in preference order, if not otherwise specified.
	DefaultPlugins = []string{"cuda", "rocm", "cpu"}
)
View Source
var ErrNoAutoInstaller = stderrors.New("auto-installer not linked: please import _ \"github.com/gomlx/go-xla/compute/xla/autoinstall\" to enable automatic PJRT downloads")

ErrNoAutoInstaller is returned when AutoInstall or AutoInstallPlugin is called but the auto-installer has not been linked into the binary. Import `github.com/gomlx/go-xla/compute/xla/autoinstall` to enable automatic downloads.

Functions

func AutoInstall

func AutoInstall() error

AutoInstall the standard plugin version tested for the current go-xla version. If GPU or TPU are detected, it will also install the corresponding plugins.

This calls the registered auto-installer if available (typically by importing `github.com/gomlx/go-xla/compute/xla/autoinstall`). If no auto-installer is registered, it returns ErrNoAutoInstaller wrapped with a stack-trace.

func AutoInstallPlugin added in v0.4.4

func AutoInstallPlugin(pluginName string) error

AutoInstallPlugin automatically installs only the specified PJRT plugin (e.g. "cpu", "cuda", "rocm", "tpu") for the current platform.

This calls the registered auto-installer if available (typically by importing `github.com/gomlx/go-xla/compute/xla/autoinstall`). If no auto-installer is registered, it returns ErrNoAutoInstaller wrapped with a stack-trace.

func EnableAutoInstall

func EnableAutoInstall(enable bool)

EnableAutoInstall sets whether AutoInstall should be triggered automatically for GetAvailablePlugins or New.

If enabled, the default, the AutoInstall function will be called automatically when GetAvailablePlugins or New is called.

func GetAvailablePlugins

func GetAvailablePlugins() []string

GetAvailablePlugins lists the available platforms -- it caches and reuses the result in future calls.

This function triggers AutoInstall if it is enabled (the default) and an auto-installer is registered. See EnableAutoInstall to disable it.

Plugins are searched in the PJRT_PLUGIN_LIBRARY_PATH directory -- or directories if it is a ":" separated list. If it is not set, it will search the system "/usr/local/lib/go-xla", the users $HOME/.local/lib/go-xla (or "$HOME/Library/Application Support/go-xla" in MacOS) and the standard libraries directories of the system (in linux in LD_LIBRARY_PATH and /etc/ld.so.conf file) in that order.

If there are plugins with the same name but different versions in different directories, it respects the order of the directories given by PJRT_PLUGIN_LIBRARY_PATH or by the system.

See details in pjrt.AvailablePlugins.

func New

func New(config string) (compute.Backend, error)

New returns a new Backend using the config as a configuration. The config string should be the name of the PJRT plugin to use.

This function triggers AutoInstall if it is enabled (the default). See EnableAutoInstall to disable it.

func RegisterAutoInstaller added in v0.4.5

func RegisterAutoInstaller(installer AutoInstaller)

RegisterAutoInstaller registers the implementation for automatic plugin downloads. Typically called from the init() of github.com/gomlx/go-xla/compute/xla/autoinstall.

func ShapeFromXLA

func ShapeFromXLA(shape xlashapes.Shape) shapes.Shape

ShapeFromXLA converts a go-xla shape to a GoMLX shape.

func ShapeToXLA

func ShapeToXLA(shape shapes.Shape) xlashapes.Shape

ShapeToXLA converts a GoMLX shape to a go-xla shape.

Types

type AutoInstaller added in v0.4.5

type AutoInstaller interface {
	// AutoInstall automatically installs the default PJRT plugins for the current platform.
	AutoInstall() error

	// AutoInstallPlugin automatically installs the specified PJRT plugin for the current platform.
	AutoInstallPlugin(pluginName string) error
}

AutoInstaller defines the interface for automatic PJRT plugin installation.

type Backend

type Backend struct {

	// DotGeneralUseTF32 controls whether to use TF32 for DotGeneral operations that are using float32.
	// (it can be faster in modern GPUs, and it's enabled by default)
	DotGeneralUseTF32 bool
	// contains filtered or unexported fields
}

Backend implements the XLA/PJRT compute.Backend for GoMLX.

func NewWithOptions

func NewWithOptions(config string, options pjrt.NamedValuesMap) (*Backend, error)

NewWithOptions creates a StableHLO backend with the given client options. It allows more control, not available with the default New constructor.

This function triggers AutoInstall if it is enabled (the default). See EnableAutoInstall to disable it.

func (*Backend) BufferFromFlatData

func (backend *Backend) BufferFromFlatData(deviceNum compute.DeviceNum, flat any, shape shapes.Shape) (compute.Buffer, error)

BufferFromFlatData transfers data from Go given as a flat slice (of the type corresponding to the shape DType) to the deviceNum, and returns the corresponding Buffer.

func (*Backend) Builder

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

Builder creates a new builder used to define a new computation.

func (*Backend) Capabilities

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

Capabilities returns information about what is supported by this backend.

func (*Backend) CheckValid

func (backend *Backend) CheckValid() error

CheckValid returns an error if the backend is not valid: if it's nil or has already been finalized.

func (*Backend) Config

func (backend *Backend) Config() string

Config returns the config used to create the backend. If no configuration was used, it returns "".

func (*Backend) Description

func (backend *Backend) Description() string

Description is a longer description of the Backend that can be used to pretty-print.

func (*Backend) DeviceDescription

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

DeviceDescription returns a description of the deviceNum.

func (*Backend) Finalize

func (backend *Backend) Finalize()

Finalize releases all the associated resources immediately and makes the backend invalid.

func (*Backend) HasSharedBuffers

func (backend *Backend) HasSharedBuffers() bool

HasSharedBuffers returns whether this PJRT plugin supports "shared buffers". In PJRT that means supporting pjrt.Client.CreateViewOfDeviceBuffer.

func (*Backend) IsCPU

func (b *Backend) IsCPU() bool

IsCPU returns whether it's a CPU PJRT.

func (*Backend) IsCUDA

func (b *Backend) IsCUDA() bool

IsCUDA returns whether it's a CUDA PJRT plugin: it has an exclusive set of custome calls (cuDNN) that we want to specialize.

func (*Backend) IsFinalized

func (backend *Backend) IsFinalized() bool

IsFinalized returns true if the backend is in an invalid state.

func (*Backend) Name

func (backend *Backend) Name() string

Name returns the short name of the backend. E.g.: "xla" for the StableHLO/PJRT plugin.

func (*Backend) NewSharedBuffer

func (backend *Backend) NewSharedBuffer(deviceNum compute.DeviceNum, shape shapes.Shape) (buffer compute.Buffer, flat any, err error)

NewSharedBuffer implements compute.Backend interface.

For XLA this means allocating the aligned memory and calling pjrt.Client.CreateViewOfDeviceBuffer to create a buffer that shares the memory.

func (*Backend) NumDevices

func (backend *Backend) NumDevices() int

NumDevices return the number of devices available for this Backend.

func (*Backend) PluginName

func (backend *Backend) PluginName() string

PluginName returns the name of the PJRT plugin.

func (*Backend) String

func (backend *Backend) String() string

String returns Name().

type Buffer

type Buffer struct {
	// contains filtered or unexported fields
}

Buffer implements compute.Buffer for XLA/PJRT.

func (*Buffer) Backend

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

Backend implements compute.Buffer.

func (*Buffer) CopyToDevice

func (b *Buffer) CopyToDevice(deviceNum compute.DeviceNum) (compute.Buffer, error)

CopyToDevice implements compute.Buffer.

func (*Buffer) Data

func (b *Buffer) Data() (flat any, err error)

Data implements compute.Buffer.

func (*Buffer) DeviceNum

func (b *Buffer) DeviceNum() (compute.DeviceNum, error)

DeviceNum implements compute.Buffer.

func (*Buffer) Finalize

func (b *Buffer) Finalize() error

Finalize implements compute.Buffer.

func (*Buffer) Shape

func (b *Buffer) Shape() (shapes.Shape, error)

Shape implements compute.Buffer.

func (*Buffer) ToFlatData

func (b *Buffer) ToFlatData(flat any) error

ToFlatData implements compute.Buffer.

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder keeps track of the computation graph being defined.

func (*Builder) CheckValid

func (b *Builder) CheckValid() error

CheckValid returns an error if the backend or the builder are not ok.

E.g.: they have been finalized or the builder has already been compiled.

func (*Builder) Compile

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

func (*Builder) DeviceAssignment

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

DeviceAssignment assigns the 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.

func (*Builder) DistributedAutoSharding

func (b *Builder) DistributedAutoSharding(meshes ...compute.Mesh) 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

func (*Builder) DistributedSPMD

func (b *Builder) DistributedSPMD(numDevices int) error

DistributedSPMD creates a computation that will be executed on multiple devices in SPMD fashion (SPMD = single program, multiple data).

func (*Builder) Main

func (b *Builder) Main() compute.Function

Main returns the main function of this computation.

func (*Builder) Name

func (b *Builder) Name() string

Name returns the name of the builder.

func (*Builder) NewFunction

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

NewFunction creates a new named function within this builder.

func (*Builder) OpShape

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

OpShape returns the shape of a computation Op.

type Executable

type Executable struct {
	// contains filtered or unexported fields
}

Executable implements the compute.Executable for XLA/PJRT github.com/gomlx/gopjrt.

func (*Executable) CheckValid

func (e *Executable) CheckValid() error

CheckValid returns an error if the backend or the executable are not ok -- e.g.: if they have been finalized or the builder has already been compiled.

func (*Executable) Execute

func (e *Executable) Execute(
	inputs []compute.Buffer,
	donate []bool,
	defaultDevice compute.DeviceNum,
) ([]compute.Buffer, error)

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].

func (*Executable) Finalize

func (e *Executable) Finalize()

Finalize immediately frees resources associated with the executable.

func (*Executable) Inputs

func (e *Executable) Inputs() (names []string, inputShapes []shapes.Shape)

Inputs returns the parameters' names and shapes, in order created by the Builder.Parameter calls.

func (*Executable) Outputs

func (e *Executable) Outputs() (outputShapes []shapes.Shape)

Outputs return the computation's output shapes, in the order given to the Builder.Compile call.

type Function

type Function struct {
	notimplemented.Function
	// contains filtered or unexported fields
}

Function implements compute.Function for XLA.

func (*Function) Abs

func (f *Function) Abs(operand compute.Value) (compute.Value, error)

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

It is special-cased here because StableHLO doesn't define the Abs() of complex numbers.

func (*Function) Add

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

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

func (*Function) AllReduce

func (f *Function) AllReduce(operands []compute.Value, reductionType compute.ReduceOpType,
	replicaGroups [][]int) ([]compute.Value, error)

AllReduce implements the collective AllReduce operation.

func (*Function) ArgMinMax

func (f *Function) ArgMinMax(x compute.Value, axis int, outputDType dtypes.DType, isMin bool) (compute.Value, error)

ArgMinMax calculates the "argmin" or "argmax" across an axis of the given input array x.

outputDType defines the output of the argmin/argmax, it doesn't need to be the same as the input. It's a form of reduction on the given axis, and that axis goes away. So the rank of the result is one less than the rank of x.

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 choose the 2, 4 and 7)

func (*Function) Atan2

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

Atan2 returns element-wise the arc tangent of y/x, using the signs of both arguments to determine the correct quadrant of the result. Standard broadcasting rules apply (see documentation).

func (*Function) BatchNormForInference

func (f *Function) BatchNormForInference(input, scale, offset, mean, variance compute.Value, epsilon float32, featureAxis int) (compute.Value, error)

BatchNormForInference implements compute.Function interface.

func (*Function) BatchNormForTraining

func (f *Function) BatchNormForTraining(input, scale, offset compute.Value, epsilon float32, featureAxis int) (output, batchMean, batchVar compute.Value, err error)

BatchNormForTraining implements compute.Function interface.

func (*Function) BatchNormGradient

func (f *Function) BatchNormGradient(gradOutput, input, scale, mean, variance compute.Value, epsilon float32, featureAxis int) (gradInput, gradScale, gradOffset compute.Value, err error)

BatchNormGradient implements compute.Function interface.

func (*Function) BitCount

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

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

func (*Function) Bitcast

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

Bitcast implements compute.Function interface.

func (*Function) BitwiseAnd

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

BitwiseAnd returns the element-wise bitwise AND operation.

func (*Function) BitwiseNot

func (f *Function) BitwiseNot(operand compute.Value) (compute.Value, error)

BitwiseNot returns the element-wise bitwise AND operation.

func (*Function) BitwiseOr

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

BitwiseOr returns the element-wise bitwise OR operation.

func (*Function) BitwiseXor

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

BitwiseXor returns the element-wise bitwise XOR operator.

func (*Function) BroadcastInDim

func (f *Function) BroadcastInDim(x compute.Value, outputShape shapes.Shape, broadcastAxes []int) (compute.Value, error)

BroadcastInDim broadcasts x to an output with the given shape. broadcastAxes has an output axes value for each x axes (len(broadcastAxes) == x.Shape.Rank()). The i-th axis of x 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 `x = (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}}

func (*Function) Builder

func (f *Function) Builder() compute.Builder

Builder returns the builder for this function.

func (*Function) Call

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

Call implements the compute.Function interface.

func (*Function) Ceil

func (f *Function) Ceil(operand compute.Value) (compute.Value, error)

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

func (*Function) CheckValid

func (f *Function) CheckValid() error

CheckValid returns an error if the builder or the function are not ok.

func (*Function) Clamp

func (f *Function) Clamp(min, a compute.Value, max compute.Value) (compute.Value, error)

Clamp returns the element-wise clamping operation.

The values max and min can either be a scalar or have the same shape as x.

func (*Function) Closure

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

Closure creates a new closure function, within this function.

func (*Function) Clz

func (f *Function) Clz(operand compute.Value) (compute.Value, error)

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

func (*Function) Complex

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

Complex returns the complex number taking x0 as the real part and x1 as the imaginary part. The real (x0) and imaginary (x1) must have the same dtype, and they must be either `dtypes.Float32` or `dtypes.Float64`. The output will be either `dtypes.Complex64` or `dtypes.Complex128`, depending on x0 and x1 dtypes. The shapes of `real` or `imaginary` must be the same, or one must be a scalar, in which case the value is broadcast to every other value.

func (*Function) Concatenate

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

Concatenate operands on the given axis.

All axes that are not being concatenated must match dimensions, except on the axes being concatenated. It doesn't work with scalars -- use ExpandAxes. If there is only one operand, it is returned and this is a no-op.

func (*Function) Conj

func (f *Function) Conj(operand compute.Value) (compute.Value, error)

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

func (*Function) Constant

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

Constant creates a constant in the function with the given flat values and the shape defined by the dimensions.

func (*Function) ConvGeneral

func (f *Function) ConvGeneral(input, kernel compute.Value,
	axes compute.ConvolveAxesConfig, strides []int, paddings [][2]int,
	inputDilations, kernelDilations []int, channelGroupCount, batchGroupCount int) (compute.Value, error)

ConvGeneral is a generic Convolution operation with arbitrary number of spatial axes, strides, paddings, dilations, and grouping.

Arguments:

  • input: it must have one batch and one channel axis, and arbitrary number of spatial axes.
  • kernel: its rank must match the input's spatial axes.
  • axes: defines how the axes of input and kernel are mapped.
  • strides: stride of the convolution window, how it moves. If set, one value per spatial axis, and values must be >= 1. If not set, strides default to 1.
  • paddings: padding applied to the start and end of each axis of the input. If nil, it defaults to no padding.
  • inputDilations: "virtually" expand the input by inserting `2-1` copies of `0` (or whatever is the reduciton "zero" value) between the elements in each dimension. If nil, it's assumed to be 1 (no dilation) for each axis. Values must be >= 1.
  • kernelDilations: "virtually" expand the kernel by inserting `2-1` copies of `0` between the elements in each dimension. If nil, it's assumed to be 1 (no dilation) for each axis. Values must be >= 1. Also known as "atrous convolution".
  • channelGroupCount: number of input channels to group together for the convolution. (aka "grouped convolution"). If <= 1 it's disabled.
  • batchGroupCount: number of input batches to group together for the convolution. If <= 1 it's disabled.

There is a more detailed description in https://www.tensorflow.org/xla/operation_semantics#convwithgeneralpadding_convolution. Also useful, https://arxiv.org/pdf/1603.07285v1.pdf. Note:

  • Another common term for "channels" is "features".
  • "Kernel" is also commonly called "weights" or "filters".

func (*Function) ConvertDType

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

ConvertDType implements compute.Function interface.

func (*Function) Cos

func (f *Function) Cos(operand compute.Value) (compute.Value, error)

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

func (*Function) Div

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

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

func (*Function) DotGeneral

func (f *Function) DotGeneral(
	lhs compute.Value, lhsContractingAxes, lhsBatchAxes []int,
	rhs compute.Value, rhsContractingAxes []int, rhsBatchAxes []int,
	config compute.DotGeneralConfig) (compute.Value, error)

DotGeneral takes as input lhs (left-hand-side) and rhs (right-hand-side) specifications for a general vector product -- a generalized "Einsum". Each axis can be:

  • Just aligned (batch axes), so the output has the same axes as the inputs. The dimensions must match in lhs and rhs.
  • Crossed (default), in which case the output is the combination (concatenation) of the dimensions.
  • Contracted (contracting axes), where the output does multiply the values and reduce sum those dimensions.

The resulting shape is [batchIndices..., <lhs cross indices...>, <rhs cross indices...>], the indices come in the order they were provided. The output dtype is by default the same as the input, except if configured otherwise in config.OutputDType.

It provides the basic means of implementing Einsum.

The XLA implementation only supports accumulation in F32 (if different than the input dtypes). So when it receives a different accumulation dtype, it simply converts the inputs to F32.

func (*Function) DynamicSlice

func (f *Function) DynamicSlice(operand compute.Value, startIndices []compute.Value, sliceDims []int) (compute.Value, error)

DynamicSlice extracts a slice from the operand at the startIndices position and the given sliceSizes.

- operand: tensor from where to take the slice. - startIndices: scalar tensors, one per axis of operand: len(startIndices) == operand.Rank(). - sliceSizes: static values and fixed to keep the shape of the output static.

The startIndices are adjusted as follows:

adjustedStartIndices[i] = clamp(0, StartIndices[i], operand.Dimensions[i] - sliceSizes[i])

See description in https://openxla.org/xla/operation_semantics#dynamicslice

func (*Function) DynamicUpdateSlice

func (f *Function) DynamicUpdateSlice(operand, update compute.Value, startIndices []compute.Value) (compute.Value, error)

DynamicUpdateSlice updates the operand with the values given in update, at the position given by startIndices.

- operand: original value that to be updated. - update: values to "paste" on top of operand, at position startIndices. - startIndices: scalar tensors, one per axis of operand: len(startIndices) == operand.Rank(). - sliceSizes: static values and fixed to keep the shape of the output static.

It returns a value with the same shape as the operand, with the values updated.

The startIndices are adjusted as follows:

adjustedStartIndices[i] = clamp(0, StartIndices[i], operand.Dimensions[i] - update.Dimensions[i])

func (*Function) Equal

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

Equal returns the element-wise operation. Standard broadcasting rules apply (see documentation).

func (*Function) EqualTotalOrder

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

EqualTotalOrder returns the element-wise operation. Standard broadcasting rules apply (see documentation).

The "TotalOrder" version of the operation enforces `-NaN < -Inf < -Finite < -0 < +0 < +Finite < +Inf < +NaN`.

func (*Function) Erf

func (f *Function) Erf(operand compute.Value) (compute.Value, error)

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

func (*Function) Exp

func (f *Function) Exp(operand compute.Value) (compute.Value, error)

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

func (*Function) Expm1

func (f *Function) Expm1(operand compute.Value) (compute.Value, error)

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

func (*Function) FFT

func (f *Function) FFT(x compute.Value, fftType compute.FFTType, fftLength []int) (compute.Value, error)

FFT implements the Fast Fourier Transform operation. fftType specifies the type of FFT operation to perform. fftLength specifies the length of the transform for each axis.

func (*Function) Floor

func (f *Function) Floor(operand compute.Value) (compute.Value, error)

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

func (*Function) FusedAttentionQKVProjection

func (f *Function) FusedAttentionQKVProjection(x, wQKV, biasQ, biasK, biasV compute.Value, queryDim, keyValueDim int) (query, key, value compute.Value, err error)

func (*Function) FusedDense

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

func (*Function) FusedGelu

func (f *Function) FusedGelu(x compute.Value, exact bool) (compute.Value, error)

func (*Function) FusedLayerNorm

func (f *Function) FusedLayerNorm(x compute.Value, axes []int, epsilon float64, gamma, beta compute.Value) (compute.Value, error)

func (*Function) FusedQuantizedDense

func (f *Function) FusedQuantizedDense(x, weights, bias compute.Value, weightsQuantization *compute.Quantization, activation compute.ActivationType) (compute.Value, error)

func (*Function) FusedScaledDotProductAttention

func (f *Function) FusedScaledDotProductAttention(query, key, value compute.Value, axesLayout compute.AttentionAxesLayout, options *compute.ScaledDotProductAttentionConfig) (output compute.Value, statesForVJP []compute.Value, err error)

FusedScaledDotProductAttention runs the cuDNN flash forward. query/key/value are [B,S,H,D] (BSHD), bf16. It returns the [B,S,H,D] bf16 output and the [B,H,S] f32 softmax statistics (log-sum-exp) the flash backward needs. The [B,H,S,S] scores never materialize. On non-cuda plugins or unsupported option combinations it returns ErrNotImplemented.

func (*Function) FusedScaledDotProductAttentionVJP

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

FusedScaledDotProductAttentionVJP runs the cuDNN flash backward. It threads the softmax stats (statesForVJP[0], from the forward) plus the forward output and the output gradient dOutput into the cuDNN backward custom-call, so the [B,H,S,S] scores never materialize in the backward either. Returns dQuery, dKey, dValue as [B,S,H,D] bf16.

func (*Function) FusedSoftmax

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

func (*Function) Gather

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

Gather is a powerful but cumbersome Gather operation. See details in the backend.

Notice GoMLX backend Gather operation doesn't support batching axes, which StableHLO does. For compatibility, we simply leave them empty.

func (*Function) GreaterOrEqual

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

GreaterOrEqual returns the element-wise operation. Standard broadcasting rules apply (see documentation).

func (*Function) GreaterOrEqualTotalOrder

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

GreaterOrEqualTotalOrder returns the element-wise operation. Standard broadcasting rules apply (see documentation).

The "TotalOrder" version of the operation enforces `-NaN < -Inf < -Finite < -0 < +0 < +Finite < +Inf < +NaN`.

func (*Function) GreaterThan

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

GreaterThan returns the element-wise operation. Standard broadcasting rules apply (see documentation).

func (*Function) GreaterThanTotalOrder

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

GreaterThanTotalOrder returns the element-wise operation. Standard broadcasting rules apply (see documentation).

The "TotalOrder" version of the operation enforces `-NaN < -Inf < -Finite < -0 < +0 < +Finite < +Inf < +NaN`.

func (*Function) Identity

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

Identity returns an Op whose output is the same as its input. It's a no-op that can serve as a place-holder.

func (*Function) If

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

If executes one of two branches based on a predicate.

func (*Function) Imag

func (f *Function) Imag(operand compute.Value) (compute.Value, error)

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

func (*Function) Iota

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

Iota implements compute.Function interface.

func (*Function) IsFinite

func (f *Function) IsFinite(operand compute.Value) (compute.Value, error)

IsFinite tests whether each element of operand is finite, i.e., if it is not positive nor negative infinity, and it is not NaN. It returns the same shape as the input, but with boolean values where each element is true if and only if the corresponding input element is finite.

func (*Function) IsNaN

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

IsNaN implements compute.Function interface.

func (*Function) LessOrEqual

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

LessOrEqual returns the element-wise operation. Standard broadcasting rules apply (see documentation).

func (*Function) LessOrEqualTotalOrder

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

LessOrEqualTotalOrder returns the element-wise operation. Standard broadcasting rules apply (see documentation).

The "TotalOrder" version of the operation enforces `-NaN < -Inf < -Finite < -0 < +0 < +Finite < +Inf < +NaN`.

func (*Function) LessThan

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

LessThan returns the element-wise operation. Standard broadcasting rules apply (see documentation).

func (*Function) LessThanTotalOrder

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

LessThanTotalOrder returns the element-wise operation. Standard broadcasting rules apply (see documentation).

The "TotalOrder" version of the operation enforces `-NaN < -Inf < -Finite < -0 < +0 < +Finite < +Inf < +NaN`.

func (*Function) Log

func (f *Function) Log(operand compute.Value) (compute.Value, error)

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

func (*Function) Log1p

func (f *Function) Log1p(operand compute.Value) (compute.Value, error)

Log1p returns the expression log(x+1).

func (*Function) LogicalAnd

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

LogicalAnd returns the element-wise logical AND operation.

func (*Function) LogicalNot

func (f *Function) LogicalNot(operand compute.Value) (compute.Value, error)

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

func (*Function) LogicalOr

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

LogicalOr returns the element-wise logical OR operation.

func (*Function) LogicalXor

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

LogicalXor returns the element-wise logical XOR operator.

func (*Function) Logistic

func (f *Function) Logistic(operand compute.Value) (compute.Value, error)

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

func (*Function) Max

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

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

func (*Function) Min

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

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

func (*Function) Mul

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

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

func (*Function) Name

func (f *Function) Name() string

Name returns the name of this function.

func (*Function) Neg

func (f *Function) Neg(operand compute.Value) (compute.Value, error)

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

func (*Function) NotEqual

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

NotEqual returns the element-wise operation. Standard broadcasting rules apply (see documentation).

func (*Function) NotEqualTotalOrder

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

NotEqualTotalOrder returns the element-wise operation. Standard broadcasting rules apply (see documentation).

The "TotalOrder" version of the operation enforces `-NaN < -Inf < -Finite < -0 < +0 < +Finite < +Inf < +NaN`.

func (*Function) OptimizationBarrier

func (f *Function) OptimizationBarrier(operands ...compute.Value) ([]compute.Value, error)

OptimizationBarrier returned values are identity to the operands, but they become only available in compilation time once all the inputs are calculated.

func (*Function) Pad

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

Pad injects padding on the start, end, or interior (in between each element) of the given operand. There must be at most `operand.Rank()` axesConfig values. Missing PadAxis are assumed to be zeros, that is, no padding for those axes.

func (*Function) Parameter

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

Parameter creates an input parameter for this function.

func (*Function) Parent

func (f *Function) Parent() compute.Function

Parent returns the parent function if this is a closure.

func (*Function) Pow

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

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

func (*Function) QuantizedEmbeddingLookup

func (f *Function) QuantizedEmbeddingLookup(data, indices compute.Value, dataQuantization *compute.Quantization) (compute.Value, error)

func (*Function) RNGBitGenerator

func (f *Function) RNGBitGenerator(state compute.Value, shape shapes.Shape) (newState compute.Value, values compute.Value, err error)

RNGBitGenerator generates the given shape filled with random bits.

It takes as input a state (usually [3]uint64) and returns the updated state and the generated values (with random bits).

Currently, the backend only supports the Philox algorithm. See https://dl.acm.org/doi/10.1145/2063384.2063405

func (*Function) Real

func (f *Function) Real(operand compute.Value) (compute.Value, error)

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

func (*Function) ReduceBitwiseAnd

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

ReduceBitwiseAnd implements the corresponding method of the compute.Function interface.

func (*Function) ReduceBitwiseOr

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

ReduceBitwiseOr implements the corresponding method of the compute.Function interface.

func (*Function) ReduceBitwiseXor

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

ReduceBitwiseXor implements the corresponding method of the compute.Function interface.

func (*Function) ReduceLogicalAnd

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

ReduceLogicalAnd implements the corresponding method of the compute.Function interface.

func (*Function) ReduceLogicalOr

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

ReduceLogicalOr implements the corresponding method of the compute.Function interface.

func (*Function) ReduceLogicalXor

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

ReduceLogicalXor implements the corresponding method of the compute.Function interface.

func (*Function) ReduceMax

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

ReduceMax implements the corresponding method of the compute.Function interface.

func (*Function) ReduceMin

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

ReduceMin implements the corresponding method of the compute.Function interface.

func (*Function) ReduceProduct

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

ReduceProduct implements the corresponding method of the compute.Function interface.

func (*Function) ReduceSum

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

ReduceSum implements the corresponding method of the compute.Function interface.

func (*Function) ReduceWindow

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

func (*Function) Rem

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

Rem returns the remainder operation, also known as modulo (or Mod for short). Notice despite the name XLA implements Mod not IEEE754 Remainder operation.

func (*Function) Reshape

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

Reshape implements compute.Function interface.

func (*Function) Return

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

Return marks the outputs of this function.

func (*Function) Reverse

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

Reverse implements the compute.Function interface.

func (*Function) Round

func (f *Function) Round(operand compute.Value) (compute.Value, error)

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

func (*Function) Rsqrt

func (f *Function) Rsqrt(operand compute.Value) (compute.Value, error)

Rsqrt returns the element-wise reciprocal of square root operation 1/sqrt(x).

func (*Function) ScatterMax

func (f *Function) ScatterMax(operand, scatterIndices, updates compute.Value, indexVectorAxis int,
	updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int, indicesAreSorted, uniqueIndices bool) (compute.Value, error)

ScatterMax scatter values from updates pointed by scatterIndices to operand, by taking the Max.

func (*Function) ScatterMin

func (f *Function) ScatterMin(operand, scatterIndices, updates compute.Value, indexVectorAxis int, updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int, indicesAreSorted, uniqueIndices bool) (compute.Value, error)

ScatterMin scatter values from updates pointed by scatterIndices to operand, by taking the Min.

func (*Function) ScatterSum

func (f *Function) ScatterSum(operand, scatterIndices, updates compute.Value, indexVectorAxis int, updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int, indicesAreSorted, uniqueIndices bool) (compute.Value, error)

ScatterSum values from updates pointed by scatterIndices to operand.

func (*Function) SchedulingBarrier

func (f *Function) SchedulingBarrier(operand compute.Value, dependencies ...compute.Value) (compute.Value, error)

SchedulingBarrier introduces a scheduling barrier. Returned value is identity to the operand, but it is guaranteed to depend on all the dependencies.

Since XLA/StableHLO don't support this operation, we "hack" it by means of a no-op: taking a scalar of each depdency, multiply by 0 and add them to the operand.

See: https://github.com/openxla/stablehlo/issues/2923.

func (*Function) SelectAndScatterMax

func (f *Function) SelectAndScatterMax(operand, source compute.Value, windowDimensions, windowStrides []int, paddings [][2]int) (compute.Value, error)

SelectAndScatterMax runs windows (similar to ReduceWindow) over the operand and selects the lowest values to update the output (like ScatterSum)

It selects the values in the window such that it works as reverse for a PoolMax operation.

Note: "Max" refers to the selection. After selected, the values are added into the output position.

See details in https://openxla.org/xla/operation_semantics#selectandscatter

func (*Function) SelectAndScatterMin

func (f *Function) SelectAndScatterMin(operand, source compute.Value, windowDimensions, windowStrides []int, paddings [][2]int) (compute.Value, error)

SelectAndScatterMin runs windows (similar to ReduceWindow) over the operand and selects the lowest values to update the output (like ScatterSum)

It selects the values in the window such that it works as reverse for a PoolMax operation.

Note: "Min" refers to the selection. After selected, values are added into the output position.

See details in https://openxla.org/xla/operation_semantics#selectandscatter

func (*Function) Shape

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

Shape returns the shape of a value in the function.

func (*Function) ShiftLeft

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

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

func (*Function) ShiftRightArithmetic

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

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

func (*Function) ShiftRightLogical

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

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

func (*Function) Sign

func (f *Function) Sign(operand compute.Value) (compute.Value, error)

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

func (*Function) Sin

func (f *Function) Sin(operand compute.Value) (compute.Value, error)

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

func (*Function) Slice

func (f *Function) Slice(x compute.Value, starts, limits, strides []int) (compute.Value, error)

Slice implements compute.Function interface.

func (*Function) Sort

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

Sort sorts one or more tensors along the specified axis using a comparator function.

func (*Function) Sqrt

func (f *Function) Sqrt(operand compute.Value) (compute.Value, error)

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

func (*Function) Sub

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

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

func (*Function) Tanh

func (f *Function) Tanh(operand compute.Value) (compute.Value, error)

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

func (*Function) Transpose

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

Transpose implements compute.Function interface. It transposes input tensor x according to the given permutation axes.

func (*Function) Where

func (f *Function) Where(condition, onTrue, onFalse compute.Value) (compute.Value, error)

Where implements compute.Function interface.

func (*Function) While

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

While executes bodyFn repeatedly while condFn returns true.

type Node

type Node struct {
	// contains filtered or unexported fields
}

Node represents the output of an operation and implements a "compute.Op" interface.

Directories

Path Synopsis
Package autoinstall automatically registers the default PJRT plugin installer into the XLA backend.
Package autoinstall automatically registers the default PJRT plugin installer into the XLA backend.
cpu
dynamic
Package dynamic links the XLA/PJRT CPU plugin dynamically (as in ".so" libraries) with your binary.
Package dynamic links the XLA/PJRT CPU plugin dynamically (as in ".so" libraries) with your binary.
static
Package static links the XLA/PJRT CPU plugin statically with your binary.
Package static links the XLA/PJRT CPU plugin statically with your binary.

Jump to

Keyboard shortcuts

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