simplego

package
v0.27.3 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2026 License: Apache-2.0 Imports: 30 Imported by: 0 modules, 0 packages

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

SimpleGo Backend

SimpleGo implements a simple, and not very fast, but very portable backend for GoMLX.

The priority is to make something that will work everywhere and is "ergonomic" (doesn't require installing any associated C/C++/Rust library, or special packages other than Go itself).

A second priority is having a very short dependency list: this aimed at being safe, very low dependency library.

See capabilities.go file to see operations that are implemented.

To Do's

This can be split into 2 parts: implement missing ops, and optimizations.

Missing Ops/Functionality

There are still many missing. See file capabilities.go. But feel free to create issues if there is an Op that you need and would like to see it prioritized.

Optimizations

The initial implementation was focused on portability and getting it to work.

But there are many relatively "low-hanging fruits" for optimization, a few obvious items:

  • Pre-calculate constant sub-expressions.
  • Fuse unary ops: it's much faster (for larger data blocks) to loop over the data only once and apply various functions than loop over the data many times, each time applying the unary function.
  • Fuse binary/unary ops: perform unary functions while traversing the data for binary functions. Again to save memory accesses.
  • Parallelization: in-operation, and across operations.
    • Only DotGeneral has been parallelized so far: it is usually the one that consumes most of the time.
  • Use intrinsics/SIMD on platforms that allow it. It was announced as experimental in Go 1.25.
  • Eliminate common sub-expressions.

Documentation

Overview

Package simplego implements a simple, and not very fast, but very portable backend for GoMLX.

It only implements the most popular dtypes and operations. But generally, it's easy to add new ops, if you need, just open an issue in GoMLX.

Index

Constants

View Source
const BackendName = "go"

BackendName to be used in GOMLX_BACKEND to specify this backend.

View Source
const MaxArgMinMaxReductionSize = 0x8000_0000
View Source
const MaxDTypes = 32

Variables

View Source
var (
	// DotGeneralTargetBlockSize is hardware-specific, it should be aligned with the L1 cache size
	// and maybe page-size.
	// It should be the number per thread, not necessarily the number per core.
	// It was empirically optimized in an AMD 9950x3d.
	// TODO: find out how to initialize this number in runtime.
	DotGeneralTargetBlockSize = 16 * 1024

	// DotGeneralTargetBlockLog2Dim is set per dtype, such that it is square and fits DotGeneralTargetBlockSize.
	// The block dim is 2^(DotGeneralTargetBlockLog2Dim[dtype]).
	DotGeneralTargetBlockLog2Dim [MaxDTypes]int

	// DotGeneralBlockedPathThreshold is the multiplier for determining when to use the blocked execution path.
	// When crossesSize (lhsCrossSize * rhsCrossSize) exceeds this multiplier times blockSize,
	// the blocked path is chosen over the normalized path.
	//
	// Empirically determined: below this threshold, the overhead of cache-tiled blocking
	// outweighs its benefits. Above this threshold, the blocked path's cache efficiency wins.
	DotGeneralBlockedPathThreshold = 16
)
View Source
var Capabilities = backends.Capabilities{

	Functions: true,

	Operations: map[backends.OpType]bool{

		backends.OpTypeParameter: true,
		backends.OpTypeConstant:  true,

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

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

		backends.OpTypeEqual:          true,
		backends.OpTypeNotEqual:       true,
		backends.OpTypeGreaterOrEqual: true,
		backends.OpTypeGreaterThan:    true,
		backends.OpTypeLessOrEqual:    true,
		backends.OpTypeLessThan:       true,

		backends.OpTypeArgMinMax:            true,
		backends.OpTypeBitcast:              true,
		backends.OpTypeBroadcast:            true,
		backends.OpTypeBroadcastInDim:       true,
		backends.OpTypeConcatenate:          true,
		backends.OpTypeConvertDType:         true,
		backends.OpTypeDot:                  true,
		backends.OpTypeDotGeneral:           true,
		backends.OpTypeGather:               true,
		backends.OpTypeIdentity:             true,
		backends.OpTypeIota:                 true,
		backends.OpTypePad:                  true,
		backends.OpTypeReduceBitwiseAnd:     true,
		backends.OpTypeReduceBitwiseOr:      true,
		backends.OpTypeReduceBitwiseXor:     true,
		backends.OpTypeReduceLogicalAnd:     true,
		backends.OpTypeReduceLogicalOr:      true,
		backends.OpTypeReduceLogicalXor:     true,
		backends.OpTypeReduceMax:            true,
		backends.OpTypeReduceMin:            true,
		backends.OpTypeReduceProduct:        true,
		backends.OpTypeReduceSum:            true,
		backends.OpTypeReduceWindow:         true,
		backends.OpTypeReshape:              true,
		backends.OpTypeReverse:              true,
		backends.OpTypeRNGBitGenerator:      true,
		backends.OpTypeScatterMax:           true,
		backends.OpTypeScatterMin:           true,
		backends.OpTypeScatterSum:           true,
		backends.OpTypeShiftLeft:            true,
		backends.OpTypeShiftRightArithmetic: true,
		backends.OpTypeShiftRightLogical:    true,
		backends.OpTypeSlice:                true,
		backends.OpTypeTranspose:            true,
		backends.OpTypeWhere:                true,
		backends.OpTypeConvGeneral:          true,

		backends.OpTypeCall:  true,
		backends.OpTypeIf:    true,
		backends.OpTypeWhile: true,
		backends.OpTypeSort:  true,

		backends.OpTypeFusedSoftmax:                   true,
		backends.OpTypeFusedLayerNorm:                 true,
		backends.OpTypeFusedGelu:                      true,
		backends.OpTypeFusedDense:                     true,
		backends.OpTypeFusedScaledDotProductAttention: true,
		backends.OpTypeFusedAttentionQKVProjection:    true,
		backends.OpTypeFusedQuantizedDense:            true,
		backends.OpTypeQuantizedEmbeddingLookup:       true,
	},

	DTypes: map[dtypes.DType]bool{
		dtypes.Bool:     true,
		dtypes.Int2:     true,
		dtypes.Uint2:    true,
		dtypes.Int4:     true,
		dtypes.Uint4:    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.Float16:  true,
		dtypes.Float32:  true,
		dtypes.Float64:  true,
		dtypes.BFloat16: true,
	},
}

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

View Source
var ErrBackendAlreadyFinalized = stderrors.New("backend already exists")

ErrBackendAlreadyFinalized is returned when attempting to register or initialize a backend that already exists.

View Source
var GetBackend = sync.OnceValue(func() backends.Backend {
	backend, err := New("")
	if err != nil {
		panic(err)
	}
	return backend
})

GetBackend returns a singleton backend for SimpleGo, created with the default configuration. The backend is only created at the first call of the function.

The singleton is never destroyed.

Functions

func New

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

New constructs a new SimpleGo Backend. There are no configurations, the string is simply ignored.

Types

type Backend

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

Backend implements the backends.Backend interface.

func (*Backend) BufferCopyToDevice added in v0.25.0

func (b *Backend) BufferCopyToDevice(_ backends.Buffer, _ backends.DeviceNum) (
	bufferOnDevice backends.Buffer, err error)

BufferCopyToDevice implements the backends.Backend interface.

func (*Backend) BufferData

func (b *Backend) BufferData(buffer backends.Buffer) (flat any, err error)

BufferData returns a slice pointing to the buffer storage memory directly.

This only works if HasSharedBuffer is true, that is, if the backend engine runs on CPU, or shares CPU memory.

The returned slice becomes invalid after the buffer is destroyed.

func (*Backend) BufferDeviceNum

func (b *Backend) BufferDeviceNum(buffer backends.Buffer) (backends.DeviceNum, error)

BufferDeviceNum returns the deviceNum for the buffer.

func (*Backend) BufferFinalize

func (b *Backend) BufferFinalize(backendBuffer backends.Buffer) error

BufferFinalize allows the client to inform the backend that the buffer is no longer needed and associated resources can be freed immediately.

A isFinalized buffer should never be used again. Preferably, the caller should set its references to it to nil.

func (*Backend) BufferFromFlatData

func (b *Backend) BufferFromFlatData(deviceNum backends.DeviceNum, flat any, shape shapes.Shape) (backends.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 backends.Buffer.

func (*Backend) BufferShape

func (b *Backend) BufferShape(buffer backends.Buffer) (shapes.Shape, error)

BufferShape returns the shape for the buffer.

func (*Backend) BufferToFlatData

func (b *Backend) BufferToFlatData(backendBuffer backends.Buffer, flat any) error

BufferToFlatData transfers the flat values of the buffer to the Go flat array. The slice flat must have the exact number of elements required to store the backends.Buffer shape.

See also FlatDataToBuffer, BufferShape, and shapes.Shape.Size.

func (*Backend) Builder

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

Builder creates a new builder used to construct a named computation.

func (*Backend) Capabilities

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

Capabilities method returns information about what is supported by this backend.

func (*Backend) Description

func (b *Backend) Description() string

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

func (*Backend) DeviceDescription added in v0.25.0

func (b *Backend) DeviceDescription(_ backends.DeviceNum) string

DeviceDescription returns a description of the device with the given deviceNum.

func (*Backend) Finalize

func (b *Backend) Finalize()

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

func (*Backend) HasSharedBuffers

func (b *Backend) HasSharedBuffers() bool

HasSharedBuffers returns whether the backend supports "shared buffers": these are buffers that can be used directly by the engine and has a local address that can be read or mutated directly by the client.

func (*Backend) IsFinalized added in v0.20.0

func (b *Backend) IsFinalized() bool

IsFinalized returns true if the backend has been isFinalized.

func (*Backend) Name

func (b *Backend) Name() string

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

func (*Backend) NewBuffer

func (b *Backend) NewBuffer(shape shapes.Shape) *Buffer

NewBuffer creates the buffer with a newly allocated flat space.

TODO: should we study the possibility to change the signature with an error?

func (*Backend) NewSharedBuffer

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

NewSharedBuffer returns a "shared buffer" that can be both used as input for execution of computations and directly read or mutated by the clients.

It panics if the backend doesn't support shared buffers -- see HasSharedBuffer.

The shared buffer should not be mutated while it is used by an execution. Also, the shared buffer cannot be "donated" during execution.

When done, to release the memory, call BufferFinalized on the returned buffer.

It returns a handle to the buffer and a slice of the corresponding data type pointing to the shared data.

func (*Backend) NumDevices

func (b *Backend) NumDevices() int

NumDevices return the number of devices available for this Backend.

func (*Backend) String added in v0.19.3

func (b *Backend) String() string

String implement backends.Backend.

type Buffer

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

Buffer for SimpleGo backend holds a shape and a reference to the flat data.

The flat data may be shared -- for temporary buffers from compiled graphs they are taken from larger blobs of bytes allocated in one Go -- or owned by the buffer.

func (*Buffer) EqualNodeData added in v0.27.0

func (b *Buffer) EqualNodeData(other nodeDataComparable) bool

EqualNodeData implements nodeDataComparable for Buffer. For Constants, this compares the shape and the actual data values.

func (*Buffer) Fill added in v0.19.3

func (b *Buffer) Fill(value any) error

Fill the buffer with the given value. It returns an error if the value type doesn't correspond to the buffer dtype.

As a special case, if value is nil, it will fill the buffer with zeroes for the corresponding DType.

func (*Buffer) Ones added in v0.19.3

func (b *Buffer) Ones() *Buffer

Ones fills the buffer with ones.

It returns a reference to the buffer to allow cascading calls.

func (*Buffer) Zeros added in v0.19.3

func (b *Buffer) Zeros() *Buffer

Zeros fills the buffer with zeros.

It returns a reference to the buffer to allow cascading calls.

type Builder

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

Builder keeps track of the computation graph being defined.

func (*Builder) Compile

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

Compile implements backends.Builder.

func (*Builder) Finalize

func (b *Builder) Finalize()

Finalize immediately releases the resources associated with the Builder.

func (*Builder) Main added in v0.27.0

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

Main returns the main function of this computation.

func (*Builder) Name

func (b *Builder) Name() string

Name implements backends.Builder.

func (*Builder) NewFunction added in v0.27.0

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

NewFunction creates a new named function within this builder. Named functions can be called with Call() and are independent of the main function.

func (*Builder) OpShape

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

OpShape returns the shape of a computation Op.

type ClosureInputs added in v0.27.0

type ClosureInputs struct {
	// Buffers are the captured input buffers for the closure.
	Buffers []*Buffer
	// Owned indicates which captured inputs can be donated to the closure.
	// If Owned[i] is true, the closure takes ownership of Buffers[i].
	Owned []bool
}

ClosureInputs holds the captured inputs and their ownership for a single closure. This is used to pass captured values to closure-calling operations (If, While, Sort).

type DTypeDispatcher deprecated

type DTypeDispatcher struct {
	Name string

	Priority [MaxDTypes]registerPriority
	// contains filtered or unexported fields
}

DTypeDispatcher manages dispatching functions to handle specific DTypes. Often, these functions will be instances of a generic function.

Deprecated: use DTypeMap instead.

func NewDTypeDispatcher deprecated

func NewDTypeDispatcher(name string) *DTypeDispatcher

NewDTypeDispatcher creates a new dispatcher for a class of functions.

Deprecated: use DTypeMap instead.

func (*DTypeDispatcher) Dispatch

func (d *DTypeDispatcher) Dispatch(dtype dtypes.DType, params ...any) any

Dispatch call the function that matches the dtype.

func (*DTypeDispatcher) Register

func (d *DTypeDispatcher) Register(dtype dtypes.DType, priority registerPriority, fn FuncForDispatcher)

Register a function to handle a specific dtype with the specified priority. If the priority is lower than the current priority for the dtype, the function is ignored.

type DTypeMap

type DTypeMap struct {
	Name     string
	Map      [MaxDTypes]any
	Priority [MaxDTypes]registerPriority
}

DTypeMap manages registering of an arbitrary value per dtype.

func NewDTypeMap

func NewDTypeMap(name string) *DTypeMap

NewDTypeMap creates a new DTypeMap.

func (*DTypeMap) Get

func (d *DTypeMap) Get(dtype dtypes.DType) (any, error)

Get retrieves the value for the given dtype, or return an error if none was registered.

func (*DTypeMap) Register

func (d *DTypeMap) Register(dtype dtypes.DType, priority registerPriority, value any)

Register a value for a dtype with the specified priority. If the priority is lower than the current priority for the dtype, the value is ignored.

type DTypePairMap

type DTypePairMap struct {
	Name     string
	Map      [MaxDTypes][MaxDTypes]any
	Priority [MaxDTypes][MaxDTypes]registerPriority
}

DTypePairMap manages registering of an arbitrary value per dtype pair.

func NewDTypePairMap

func NewDTypePairMap(name string) *DTypePairMap

NewDTypePairMap creates a new DTypePairMap.

func (*DTypePairMap) Get

func (d *DTypePairMap) Get(dtype1, dtype2 dtypes.DType) (any, error)

Get retrieves the value for the given dtype pair, or return an error if none was registered.

func (*DTypePairMap) Register

func (d *DTypePairMap) Register(dtype1, dtype2 dtypes.DType, priority registerPriority, value any)

Register a value for a dtype pair with the specified priority. If the priority is lower than the current priority for the dtype pair, the value is ignored.

type Executable

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

Executable holds a frozen Builder. It assumes the graph in Builder is valid and has been properly checked that all the shapes and data types are valid.

If any inconsistencies are found, please fix in the Builder, so Executable can be written without the need of any duplicate checks.

func (*Executable) Execute

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

Execute the executable on the default device (0). The number and shapes of the inputs must match those returned by Inputs.

The inputs marked in `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.

func (*Executable) Finalize

func (e *Executable) Finalize()

Finalize immediately frees resources associated with the executable.

TODO: Race-condition where calling Finalize will make execution crash, if finalized while executing.

Make Finalize wait for all the current executions to exit, before finalizing.
And add a latch indicating Finalize has been called, to tell the executions to exit immediately
without finishing. Finally, remove the `e.builder == nil` checks, that won't be necessary anymore,
since e.builder will never be set to nil while there is an execution alive.

func (*Executable) Inputs

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

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

func (*Executable) Outputs

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

Outputs returns the output shapes of the computation, in order given to the Builder.Compile call.

type FuncForDispatcher

type FuncForDispatcher func(params ...any) any

FuncForDispatcher is type of functions that the DTypeDispatcher can handle.

type Function added in v0.27.0

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

Function implements backends.Function for SimpleGo.

func (*Function) Abs added in v0.27.0

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

Abs implements the backends.Builder interface.

func (*Function) Add added in v0.27.0

func (f *Function) Add(lhsOp, rhsOp backends.Value) (backends.Value, error)

Add implements the backends.Builder interface.

func (*Function) AllReduce added in v0.27.0

func (f *Function) AllReduce(_ []backends.Value, _ backends.ReduceOpType, _ [][]int) ([]backends.Value, error)

AllReduce implements the backends.CollectiveOps interface.

func (*Function) ArgMinMax added in v0.27.0

func (f *Function) ArgMinMax(
	operandOp backends.Value,
	axis int,
	outputDType dtypes.DType,
	isMin bool,
) (backends.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 added in v0.27.0

func (f *Function) Atan2(lhsOp, rhsOp backends.Value) (backends.Value, error)

Atan2 implements the backends.Builder interface.

func (*Function) BitCount added in v0.27.0

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

BitCount implements the backends.Builder interface.

func (*Function) Bitcast added in v0.27.0

func (f *Function) Bitcast(operandOp backends.Value, targetDType dtypes.DType) (backends.Value, error)

Bitcast reinterprets the bits of operandOp as targetDType. It implements the backends.Builder interface.

If the element sizes 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 divisible by (dstBits / srcBits) and is divided by this ratio, but not "squeezed", the rank is always preserved in this case.

func (*Function) BitwiseAnd added in v0.27.0

func (f *Function) BitwiseAnd(lhsOp, rhsOp backends.Value) (backends.Value, error)

BitwiseAnd implements the backends.Builder interface.

func (*Function) BitwiseNot added in v0.27.0

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

BitwiseNot implements the backends.Builder interface.

func (*Function) BitwiseOr added in v0.27.0

func (f *Function) BitwiseOr(lhsOp, rhsOp backends.Value) (backends.Value, error)

BitwiseOr implements the backends.Builder interface.

func (*Function) BitwiseXor added in v0.27.0

func (f *Function) BitwiseXor(lhsOp, rhsOp backends.Value) (backends.Value, error)

BitwiseXor implements the backends.Builder interface.

func (*Function) Broadcast added in v0.27.0

func (f *Function) Broadcast(operandOp backends.Value, prefixDims ...int) (backends.Value, error)

Broadcast prefixes dimensions to an array by duplicating the data in the array. See BroadcastInDim for a broadcast in between the axes. The new dimensions dims are inserted on the left, i.e., if prefixDims has values `{a0, ..., aN}` and the operand shape has dimensions {b0, ..., bM}, then the shape of the output has dimensions {a0, ..., aN, b0, ..., bM}. The new dimensions id into copies of the operand, i.e.

output[i0, ..., iN, j0, ..., jM] = operand[j0, ..., jM]

func (*Function) BroadcastInDim added in v0.27.0

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

BroadcastInDim broadcasts x to an output with the given shape.

  • outputShape will be the new shape after x is broadcast.
  • broadcastAxes maps x-axes to the corresponding outputShape 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) Call added in v0.27.0

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

Call creates nodes representing a call to the target function with the given inputs. The target function must be a named function from the same builder that has been compiled.

func (*Function) CapturedParentNodes added in v0.27.0

func (f *Function) CapturedParentNodes() []*Node

CapturedParentNodes returns the list of parent nodes that this closure captures. Each entry corresponds to a node from a parent function that this closure uses. Returns nil for non-closures or closures that don't capture any values.

func (*Function) Ceil added in v0.27.0

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

Ceil implements the backends.Builder interface.

func (*Function) CheckValid added in v0.27.0

func (f *Function) CheckValid() error

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

func (*Function) Clamp added in v0.27.0

func (f *Function) Clamp(minV, x, maxV backends.Value) (backends.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 added in v0.27.0

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

Closure creates a new closure function within this function. Closures can access values from their parent function's scope.

func (*Function) Clz added in v0.27.0

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

Clz implements the backends.Builder interface.

func (*Function) Compiled added in v0.27.0

func (f *Function) Compiled() *FunctionExecutable

Compiled returns the pre-compiled function executable, or nil if not yet compiled.

func (*Function) Concatenate added in v0.27.0

func (f *Function) Concatenate(axis int, operandOps ...backends.Value) (backends.Value, error)

Concatenate joins a sequence of tensors along the given axis (it must exist already). All input tensors must have the same shape, except potentially in the concatenation dimension. They must also have the same data type (DType). It returns an error if inputs are invalid (e.g., no inputs, mismatched graphs, shapes, dtypes, or invalid dimension).

func (*Function) Constant added in v0.27.0

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

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

func (*Function) ConvGeneral added in v0.27.0

func (f *Function) ConvGeneral(inputOp, kernelOp backends.Value, axes backends.ConvolveAxesConfig,
	strides []int, paddings [][2]int,
	inputDilations, kernelDilations []int,
	channelGroupCount, batchGroupCount int) (backends.Value, error)

ConvGeneral is a generic Convolution operation with support for:

- Arbitrary number of spatial axes. - Arbitrary transposition of axes. - Strides and padding. - Dilations of the input. - Dilations of the kernel, aka. atrous convolution. - Feature grouping (on the input channels). - Batch grouping.

Some details in https://www.tensorflow.org/xla/operation_semantics#convwithgeneralpadding_convolution. There operand and filter are called lhs and rhs. (XLA documentation is unfortunately poor, much is guess-work). Also useful, https://arxiv.org/pdf/1603.07285v1.pdf.

Note: input is aka. operand; kernel is aka. "filters". The input and output "channels" are also known as "features dimensions".

func (*Function) ConvGeneralDilated deprecated added in v0.27.0

func (f *Function) ConvGeneralDilated(inputOp, kernelOp backends.Value, axes backends.ConvolveAxesConfig,
	strides []int, paddings [][2]int,
	inputDilations, kernelDilations []int,
	channelGroupCount, batchGroupCount int) (backends.Value, error)

ConvGeneralDilated is a deprecated an alias to ConvGeneral.

Deprecated: use ConvGeneral instead.

func (*Function) ConvertDType added in v0.27.0

func (f *Function) ConvertDType(operandOp backends.Value, dtype dtypes.DType) (backends.Value, error)

ConvertDType converts operandOp to the given dtype. It implements the backends.Builder interface.

func (*Function) Cos added in v0.27.0

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

Cos implements the backends.Builder interface.

func (*Function) Div added in v0.27.0

func (f *Function) Div(lhsOp, rhsOp backends.Value) (backends.Value, error)

Div implements the backends.Builder interface.

func (*Function) DotGeneral added in v0.27.0

func (f *Function) DotGeneral(
	lhsOp backends.Value, lhsContractingAxes, lhsBatchAxes []int,
	rhsOp backends.Value, rhsContractingAxes, rhsBatchAxes []int,
	config backends.DotGeneralConfig) (backends.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.

It follows that the resulting dimension number starts with the batch dimension, then the 'lhs' non-contracting/non-batch dimension and finally the 'rhs' non-contracting/non-batch dimension. It provides the basic means of implementing Einsum.

This function implements backends.Builder interface.

This is the graph building part of DotGeneral. It first transposes the operands to a normalized shape with rank=3 ([batchSize, crossSize, contractingSize]), and then it issues the DotGeneral node with normalized inputs. Finally, it reshapes back to the final result.

See execDotGeneral for the implementation.

func (*Function) Equal added in v0.27.0

func (f *Function) Equal(lhsOp, rhsOp backends.Value) (backends.Value, error)

Equal implements the backends.Builder interface.

func (*Function) Erf added in v0.27.0

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

Erf implements the backends.Builder interface.

func (*Function) Exp added in v0.27.0

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

Exp implements the backends.Builder interface.

func (*Function) Expm1 added in v0.27.0

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

Expm1 implements the backends.Builder interface. It returns e(x)-1.

func (*Function) Floor added in v0.27.0

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

Floor implements the backends.Builder interface.

func (*Function) FusedAttentionQKVProjection added in v0.27.0

func (f *Function) FusedAttentionQKVProjection(x, wQKV, biasQ, biasK, biasV backends.Value, queryDim, keyValueDim int) (queryOut, keyOut, valueOut backends.Value, err error)

FusedAttentionQKVProjection performs fused Query-Key-Value projection.

The matmul (x @ wQKV) is delegated to DotGeneral, which selects the optimal execution path (blocked, packgemm, highway, etc.) at build time. The fused executor then splits the result into Q/K/V and adds biases.

func (*Function) FusedDense added in v0.27.0

func (f *Function) FusedDense(x, weight, bias backends.Value, activation backends.ActivationType) (backends.Value, error)

FusedDense performs fused matmul + optional bias + optional activation:

y = activation(x @ W + bias)

The matmul is delegated to DotGeneral (which selects the optimal execution path at build time). FusedDense then adds bias and applies activation on top of the DotGeneral result.

func (*Function) FusedGelu added in v0.27.0

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

FusedGelu computes Gaussian Error Linear Unit activation. If exact is true, uses the exact GELU (erf); otherwise uses the tanh approximation.

func (*Function) FusedLayerNorm added in v0.27.0

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

FusedLayerNorm applies layer normalization.

func (*Function) FusedQuantizedDense added in v0.27.0

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

FusedQuantizedDense performs fused dequantization + matmul + optional bias + optional activation.

Unlike FusedDense, this does not create a DotGeneral sub-node — the quantized matmul is fundamentally different (mixed-dtype with per-group scales). The inputs to the executor are [x, weights, scales, zeroPoints?, bias?] directly.

Weights should have their dtype set to reflect the actual storage type (e.g. Int4, Int8). For sub-byte types, the caller should Bitcast packed byte data to the correct dtype.

func (*Function) FusedScaledDotProductAttention added in v0.27.0

func (f *Function) FusedScaledDotProductAttention(query, key, value, mask backends.Value, numHeads, numKVHeads int, axesLayout backends.AxesLayout, scale float64, causal bool, options *backends.ScaledDotProductAttentionConfig) (backends.Value, error)

FusedScaledDotProductAttention computes multi-head scaled dot-product attention. Both AxesLayoutBHSD and AxesLayoutBSHD are supported; the executor transposes BSHD inputs to BHSD internally.

func (*Function) FusedSoftmax added in v0.27.0

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

FusedSoftmax computes softmax along the specified axis. The axis must be non-negative (the caller normalizes negative indices).

func (*Function) Gather added in v0.27.0

func (f *Function) Gather(
	operandOp, startIndicesOp backends.Value,
	indexVectorAxis int,
	offsetOutputAxes, collapsedSliceAxes, startIndexMap, sliceSizes []int,
	indicesAreSorted bool,
) (backends.Value, error)

Gather implements the backends.Builder. It's a complex operation, fully described in the backends.Builder.Gather documentation.

func (*Function) GreaterOrEqual added in v0.27.0

func (f *Function) GreaterOrEqual(lhsOp, rhsOp backends.Value) (backends.Value, error)

GreaterOrEqual implements the backends.Builder interface.

func (*Function) GreaterThan added in v0.27.0

func (f *Function) GreaterThan(lhsOp, rhsOp backends.Value) (backends.Value, error)

GreaterThan implements the backends.Builder interface.

func (*Function) Identity added in v0.27.0

func (f *Function) Identity(operandOp backends.Value) (backends.Value, error)

Identity implements the backends.Identity interface. This operation is not de-duplicated: if you issue it twice, it will not reuse the previous instance.

func (*Function) If added in v0.27.0

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

If executes one of two branches based on a boolean predicate.

The predicate must be a scalar boolean. The true and false branches are closures that take no parameters and return the same number of outputs with matching shapes.

func (*Function) Iota added in v0.27.0

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

Iota creates a constant of the given shape with increasing numbers (starting from 0) on the given axis. So Iota([2,2], 1) returns [[0 1][0 1]], while Iota([2,2], 0) returns [[0 0][1 1]].

func (*Function) IsAncestorOf added in v0.27.0

func (f *Function) IsAncestorOf(leafFunc *Function) bool

IsAncestorOf checks whether f is an ancestor of leafFunc. It returns true if f == leafFunc.

Typically, leafFunc will be a closure.

func (*Function) IsFinite added in v0.27.0

func (f *Function) IsFinite(operandOp backends.Value) (backends.Value, error)

IsFinite implements the backends.Builder interface.

func (*Function) IsNaN added in v0.27.0

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

IsNaN implements backends.Builder interface.

func (*Function) LessOrEqual added in v0.27.0

func (f *Function) LessOrEqual(lhsOp, rhsOp backends.Value) (backends.Value, error)

LessOrEqual implements the backends.Builder interface.

func (*Function) LessThan added in v0.27.0

func (f *Function) LessThan(lhsOp, rhsOp backends.Value) (backends.Value, error)

LessThan implements the backends.Builder interface.

func (*Function) Log added in v0.27.0

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

Log implements the backends.Builder interface.

func (*Function) Log1p added in v0.27.0

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

Log1p implements the backends.Builder interface.

func (*Function) LogicalAnd added in v0.27.0

func (f *Function) LogicalAnd(lhsOp, rhsOp backends.Value) (backends.Value, error)

LogicalAnd implements the backends.Builder interface.

func (*Function) LogicalNot added in v0.27.0

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

LogicalNot implements the backends.Builder interface.

func (*Function) LogicalOr added in v0.27.0

func (f *Function) LogicalOr(lhsOp, rhsOp backends.Value) (backends.Value, error)

LogicalOr implements the backends.Builder interface.

func (*Function) LogicalXor added in v0.27.0

func (f *Function) LogicalXor(lhsOp, rhsOp backends.Value) (backends.Value, error)

LogicalXor implements the backends.Builder interface.

func (*Function) Logistic added in v0.27.0

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

Logistic implements the backends.Builder interface. Aka as sigmoid. It returns 1/(1+exp(-x)).

func (*Function) Max added in v0.27.0

func (f *Function) Max(lhsOp, rhsOp backends.Value) (backends.Value, error)

Max implements the backends.Builder interface.

func (*Function) Min added in v0.27.0

func (f *Function) Min(lhsOp, rhsOp backends.Value) (backends.Value, error)

Min implements the backends.Builder interface.

func (*Function) Mul added in v0.27.0

func (f *Function) Mul(lhsOp, rhsOp backends.Value) (backends.Value, error)

Mul implements the backends.Builder interface.

func (*Function) Name added in v0.27.0

func (f *Function) Name() string

Name returns the name of this function. For closures, this returns "".

func (*Function) Neg added in v0.27.0

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

Neg implements the backends.Builder interface.

func (*Function) NotEqual added in v0.27.0

func (f *Function) NotEqual(lhsOp, rhsOp backends.Value) (backends.Value, error)

NotEqual implements the backends.Builder interface.

func (*Function) Pad added in v0.27.1

func (f *Function) Pad(operandOp, fillValueOp backends.Value, axesConfig ...backends.PadAxis) (backends.Value, error)

Pad implements the backends.Builder interface.

func (*Function) Parameter added in v0.27.0

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

Parameter creates an input parameter for this function.

func (*Function) Parent added in v0.27.0

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

Parent returns the parent function if this is a closure. Returns nil for top-level functions (including main).

func (*Function) Pow added in v0.27.0

func (f *Function) Pow(lhsOp, rhsOp backends.Value) (backends.Value, error)

Pow implements the backends.Builder interface.

func (*Function) QuantizedEmbeddingLookup added in v0.27.3

func (f *Function) QuantizedEmbeddingLookup(data, indices backends.Value,
	wq *backends.Quantization) (backends.Value, error)

QuantizedEmbeddingLookup performs a quantized embedding lookup (row gather) with on-the-fly dequantization. data: [vocabSize, bytesPerRow] Uint8 with native GGML block layout. indices: integer tensor with last dim = 1 (same as Gather convention). Output: [batch..., K] Float32 where K is derived from the block format.

func (*Function) RNGBitGenerator added in v0.27.0

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

RNGBitGenerator generates the given shape filled with random bits. It takes as input the current random number generator (RNG) state, see RNGState or RNGStateFromSeed. The algorithm is hard-coded to use Philox algorithm for now.

It returns the new state of the RNG and the generated values (with random bits) with the given shape.

func (*Function) ReduceBitwiseAnd added in v0.27.0

func (f *Function) ReduceBitwiseAnd(operandOp backends.Value, axis ...int) (backends.Value, error)

ReduceBitwiseAnd implements the backends.Builder interface.

func (*Function) ReduceBitwiseOr added in v0.27.0

func (f *Function) ReduceBitwiseOr(operandOp backends.Value, axis ...int) (backends.Value, error)

ReduceBitwiseOr implements the backends.Builder interface.

func (*Function) ReduceBitwiseXor added in v0.27.0

func (f *Function) ReduceBitwiseXor(operandOp backends.Value, axis ...int) (backends.Value, error)

ReduceBitwiseXor implements the backends.Builder interface.

func (*Function) ReduceLogicalAnd added in v0.27.0

func (f *Function) ReduceLogicalAnd(operandOp backends.Value, axis ...int) (backends.Value, error)

ReduceLogicalAnd implements the backends.Builder interface.

func (*Function) ReduceLogicalOr added in v0.27.0

func (f *Function) ReduceLogicalOr(operandOp backends.Value, axis ...int) (backends.Value, error)

ReduceLogicalOr implements the backends.Builder interface.

func (*Function) ReduceLogicalXor added in v0.27.0

func (f *Function) ReduceLogicalXor(operandOp backends.Value, axis ...int) (backends.Value, error)

ReduceLogicalXor implements the backends.Builder interface.

func (*Function) ReduceMax added in v0.27.0

func (f *Function) ReduceMax(operandOp backends.Value, axis ...int) (backends.Value, error)

ReduceMax implements the backends.Builder interface.

func (*Function) ReduceMin added in v0.27.0

func (f *Function) ReduceMin(operandOp backends.Value, axis ...int) (backends.Value, error)

ReduceMin implements the backends.Builder interface.

func (*Function) ReduceProduct added in v0.27.0

func (f *Function) ReduceProduct(operandOp backends.Value, axis ...int) (backends.Value, error)

ReduceProduct implements the backends.Builder interface.

func (*Function) ReduceSum added in v0.27.0

func (f *Function) ReduceSum(operandOp backends.Value, axis ...int) (backends.Value, error)

ReduceSum implements the backends.Builder interface.

func (*Function) ReduceWindow added in v0.27.0

func (f *Function) ReduceWindow(
	operandOp backends.Value,
	reductionType backends.ReduceOpType,
	windowDimensions, strides, baseDilations, windowDilations []int,
	paddings [][2]int,
) (backends.Value, error)

ReduceWindow runs a reduction function of reduceType (backends.ReduceOpMax, backends.ReduceOpSum or backends.ReduceOpProduct).

The parameter windowDimensions must be set and have a value for each axis. If strides is nil, it's assumed to be the same as windowDimensions -- that is, the strides jump a window at a time. If baseDilations, windowDilations are nil, they are assumed to be 1 (no dilation). If paddings is nil, they are assumed to be 0.

func (*Function) Rem added in v0.27.0

func (f *Function) Rem(lhsOp, rhsOp backends.Value) (backends.Value, error)

Rem implements the backends.Builder interface.

func (*Function) Reshape added in v0.27.0

func (f *Function) Reshape(operandOp backends.Value, dims ...int) (backends.Value, error)

Reshape implements the backends.Builder interface.

Notice the backends.Reshape doesn't support auto-scaling dimensions (set to -1), as graph.Reshape does.

func (*Function) Return added in v0.27.0

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

Return marks the outputs of this function.

func (*Function) Reverse added in v0.27.0

func (f *Function) Reverse(operandOp backends.Value, axes ...int) (backends.Value, error)

Reverse returns x with the values for the given dimensions reversed, that is, the value indexed at `i` will be swapped with the value at indexed `(dimension_size - 1 - i)`. The shape remains the same.

func (*Function) Round added in v0.27.0

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

Round implements the backends.Builder interface.

func (*Function) Rsqrt added in v0.27.0

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

Rsqrt implements the backends.Builder interface.

func (*Function) ScatterMax added in v0.27.0

func (f *Function) ScatterMax(
	operandOp, scatterIndicesOp, updatesOp backends.Value,
	indexVectorAxis int,
	updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int,
	indicesAreSorted, uniqueIndices bool,
) (backends.Value, error)

ScatterMax implements the backends.Builder interface.

func (*Function) ScatterMin added in v0.27.0

func (f *Function) ScatterMin(
	operandOp, scatterIndicesOp, updatesOp backends.Value,
	indexVectorAxis int,
	updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int,
	indicesAreSorted, uniqueIndices bool,
) (backends.Value, error)

ScatterMin implements the backends.Builder interface.

func (*Function) ScatterSum added in v0.27.0

func (f *Function) ScatterSum(
	operandOp, scatterIndicesOp, updatesOp backends.Value,
	indexVectorAxis int,
	updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int,
	indicesAreSorted, uniqueIndices bool,
) (backends.Value, error)

ScatterSum implements the backends.Builder interface.

func (*Function) ShiftLeft added in v0.27.3

func (f *Function) ShiftLeft(lhsOp, rhsOp backends.Value) (backends.Value, error)

ShiftLeft implements the backends.Builder interface.

func (*Function) ShiftRightArithmetic added in v0.27.3

func (f *Function) ShiftRightArithmetic(lhsOp, rhsOp backends.Value) (backends.Value, error)

ShiftRightArithmetic implements the backends.Builder interface.

func (*Function) ShiftRightLogical added in v0.27.3

func (f *Function) ShiftRightLogical(lhsOp, rhsOp backends.Value) (backends.Value, error)

ShiftRightLogical implements the backends.Builder interface.

func (*Function) Sign added in v0.27.0

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

Sign implements the backends.Builder interface.

func (*Function) Sin added in v0.27.0

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

Sin implements the backends.Builder interface.

func (*Function) Slice added in v0.27.0

func (f *Function) Slice(operandOp backends.Value, starts, limits, strides []int) (backends.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. 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}

func (*Function) Sort added in v0.27.0

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

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

The comparator closure takes 2*N scalar parameters (lhs_0, rhs_0, lhs_1, rhs_1, ...) where N is the number of input tensors, and returns a scalar boolean indicating whether lhs should come before rhs.

func (*Function) Sqrt added in v0.27.0

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

Sqrt implements the backends.Builder interface.

func (*Function) Sub added in v0.27.0

func (f *Function) Sub(lhsOp, rhsOp backends.Value) (backends.Value, error)

Sub implements the backends.Builder interface.

func (*Function) Tanh added in v0.27.0

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

Tanh implements the backends.Builder interface.

func (*Function) Transpose added in v0.27.0

func (f *Function) Transpose(operandOp backends.Value, permutations ...int) (backends.Value, error)

Transpose axes of x. There must be one value in permutations for each axis in the operand. The output will have: output.Shape.Dimension[ii] = operand.Shape.Dimension[permutations[i]].

func (*Function) Where added in v0.27.0

func (f *Function) Where(conditionOp, onTrueOp, onFalseOp backends.Value) (backends.Value, error)

Where implements the backends.Builder interface.

func (*Function) While added in v0.27.0

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

While executes a loop while a condition is true.

The condition closure takes the current state values and returns a scalar boolean. The body closure takes the current state values and returns new state values. Both must have the same number of parameters matching the initialState count.

type FunctionExecutable added in v0.27.0

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

FunctionExecutable contains pre-compiled execution information for any function. This is used for both the main function and closures, unifying their execution model.

func (*FunctionExecutable) Execute added in v0.27.0

func (fe *FunctionExecutable) Execute(backend *Backend, inputs []*Buffer, donate []bool, capturedInputs []*Buffer,
	donateCaptures []bool) ([]*Buffer, error)

Execute runs the compiled function with the given inputs. The inputs must match the function's parameters in count and shape. capturedInputs are the values captured from parent scopes (for closures). donateCaptures indicates which captured inputs can be donated to the closure. If donateCaptures is nil, no captured inputs will be donated.

type Node

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

Node in the SimpleGo computation graph.

func (*Node) AddNodeCapturedInputs added in v0.27.0

func (n *Node) AddNodeCapturedInputs(closure *Function)

AddNodeCapturedInputs adds captured inputs from a closure to this node. This should be called when building ops like If, While, Sort that use closures. For ops with multiple closures, call this once for each closure. Each closure's captured values are stored as a separate slice in node.capturedInputs, preserving the per-closure grouping for execution.

For nested closures, if the closure captures values from a grandparent, those values are propagated to the parent closure's required captures.

func (*Node) IsMultiOutputs added in v0.19.1

func (n *Node) IsMultiOutputs() bool

IsMultiOutputs returns whether this node yields multiple outputs.

func (*Node) MultiOutputValues added in v0.27.0

func (node *Node) MultiOutputValues() []backends.Value

MultiOutputValues converts a multi-output node's outputs to []backends.Value.

type PODBooleanConstraints

type PODBooleanConstraints interface {
	bool
}

PODBooleanConstraints is a simple placeholder for the gen_exec_binary.go generated code.

type PODFloatConstraints

type PODFloatConstraints interface {
	float32 | float64
}

PODFloatConstraints are used for generics for the Golang pod (plain-old-data) types. BFloat16 and Float16 are not included because they are specialized types, not natively supported by Go.

type PODIntegerConstraints

type PODIntegerConstraints interface {
	int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
}

PODIntegerConstraints are used for generics for the Golang pod (plain-old-data) types.

type PODNumericConstraints

type PODNumericConstraints interface {
	int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | float32 | float64
}

PODNumericConstraints are used for generics for the Golang pod (plain-old-data) types. BFloat16 is not included because it is a specialized type, not natively supported by Go.

type PODSignedNumericConstraints

type PODSignedNumericConstraints interface {
	int8 | int16 | int32 | int64 | float32 | float64
}

PODSignedNumericConstraints are used for generics for the Golang pod (plain-old-data) types. BFloat16 and Float16 are not included because they are specialized types, not natively supported by Go.

type PODUnsignedConstraints

type PODUnsignedConstraints interface {
	uint8 | uint16 | uint32 | uint64
}

PODUnsignedConstraints are used for generics for the Golang pod (plain-old-data) types.

type SupportedTypesConstraints

type SupportedTypesConstraints interface {
	bool | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | float32 | float64 |
		bfloat16.BFloat16 | float16.Float16
}

SupportedTypesConstraints enumerates the types supported by SimpleGo.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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