simplego

package
v0.22.1 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2025 License: Apache-2.0 Imports: 28 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:

  • Eliminate common sub-expressions.
  • 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.

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
)
View Source
var Capabilities = backends.Capabilities{
	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.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.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.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.OpTypeRngBitGenerator:  true,
		backends.OpTypeScatterMax:       true,
		backends.OpTypeScatterMin:       true,
		backends.OpTypeScatterSum:       true,
		backends.OpTypeSlice:            true,
		backends.OpTypeTranspose:        true,
		backends.OpTypeWhere:            true,
		backends.OpTypeConvGeneral:      true,
	},

	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,
	},
}

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

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) 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 backend that 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 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) 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.

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() backends.DeviceNum

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

func (b *Builder) Abs(operand backends.Op) (backends.Op, error)

Abs implements the backends.Builder interface.

func (*Builder) Add

func (b *Builder) Add(lhsOp, rhsOp backends.Op) (backends.Op, error)

Add implements the backends.Builder interface.

func (*Builder) ArgMinMax added in v0.19.3

func (b *Builder) ArgMinMax(operandOp backends.Op, axis int, outputDType dtypes.DType, isMin bool) (backends.Op, 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 (*Builder) BitCount

func (b *Builder) BitCount(operand backends.Op) (backends.Op, error)

BitCount implements the backends.Builder interface.

func (*Builder) BitwiseAnd

func (b *Builder) BitwiseAnd(lhsOp, rhsOp backends.Op) (backends.Op, error)

BitwiseAnd implements the backends.Builder interface.

func (*Builder) BitwiseNot

func (b *Builder) BitwiseNot(operand backends.Op) (backends.Op, error)

BitwiseNot implements the backends.Builder interface.

func (*Builder) BitwiseOr

func (b *Builder) BitwiseOr(lhsOp, rhsOp backends.Op) (backends.Op, error)

BitwiseOr implements the backends.Builder interface.

func (*Builder) BitwiseXor

func (b *Builder) BitwiseXor(lhsOp, rhsOp backends.Op) (backends.Op, error)

BitwiseXor implements the backends.Builder interface.

func (*Builder) Broadcast

func (b *Builder) Broadcast(operandOp backends.Op, prefixDims ...int) (backends.Op, 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 (*Builder) BroadcastInDim

func (b *Builder) BroadcastInDim(operandOp backends.Op, outputShape shapes.Shape, broadcastAxes []int) (backends.Op, 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 (*Builder) Ceil

func (b *Builder) Ceil(operand backends.Op) (backends.Op, error)

Ceil implements the backends.Builder interface.

func (*Builder) Clz

func (b *Builder) Clz(operand backends.Op) (backends.Op, error)

Clz implements the backends.Builder interface.

func (*Builder) Compile

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

Compile implements backends.Builder.

func (*Builder) Concatenate

func (b *Builder) Concatenate(axis int, operandOps ...backends.Op) (backends.Op, 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 (*Builder) Constant

func (b *Builder) Constant(flat any, dims ...int) (backends.Op, error)

Constant creates a constant in the graph with the given flat values, and the shape defined by the parameter dims.

flat must be a slice of a basic type supported -- that can be converted to a DType.

The value is copied into the graph. It's recommended that for very large tensors, even if constants, that they are passed as side inputNodes (or variables, see context package) instead.

func (*Builder) ConvGeneral added in v0.22.0

func (b *Builder) ConvGeneral(inputOp, kernelOp backends.Op, axes backends.ConvolveAxesConfig,
	strides []int, paddings [][2]int,
	inputDilations, kernelDilations []int,
	channelGroupCount, batchGroupCount int) (backends.Op, 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 (*Builder) ConvGeneralDilated deprecated added in v0.22.0

func (b *Builder) ConvGeneralDilated(inputOp, kernelOp backends.Op, axes backends.ConvolveAxesConfig,
	strides []int, paddings [][2]int,
	inputDilations, kernelDilations []int,
	channelGroupCount, batchGroupCount int) (backends.Op, error)

ConvGeneralDilated is a deprecated an alias to ConvGeneral.

Deprecated: use ConvGeneral instead.

func (*Builder) ConvertDType

func (b *Builder) ConvertDType(operandOp backends.Op, dtype dtypes.DType) (backends.Op, error)

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

func (*Builder) Cos

func (b *Builder) Cos(operand backends.Op) (backends.Op, error)

Cos implements the backends.Builder interface.

func (*Builder) Div

func (b *Builder) Div(lhsOp, rhsOp backends.Op) (backends.Op, error)

Div implements the backends.Builder interface.

func (*Builder) Dot

func (b *Builder) Dot(lhsOp, rhsOp backends.Op) (backends.Op, error)

Dot ------------------------------------------------------------------------------------------------------ Dot implements backends.Builder interface.

It is implemented using DotGeneral and Reshape.

Dot returns the "dot product" operation. The exact semantics of this operation depend on the ranks of the operands: | Input | Output | Semantics | | vector [n] dot vector [n] | scalar | vector dot product | | matrix [m x k] dot vector [k] | vector [m] matrix-vector multiplication | | matrix [m x k] dot matrix [k x n] | matrix [m x n] | matrix-matrix multiplication | The operation performs sum of products over the second dimension of x0 (or the first if it has rank 1) and the first dimension of x1. These are the "contracted" dimensions. The contracted dimensions of x0 and x1 must be of the same size. In practice, it can be used to perform dot products between vectors, vector/matrix multiplications or matrix/matrix multiplications. The op is created on the same XlaBuilder as used for x0 and x1.

func (*Builder) DotGeneral

func (b *Builder) DotGeneral(lhsOp backends.Op, lhsContractingAxes, lhsBatchAxes []int, rhsOp backends.Op, rhsContractingAxes, rhsBatchAxes []int) (backends.Op, 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 (*Builder) Equal

func (b *Builder) Equal(lhsOp, rhsOp backends.Op) (backends.Op, error)

Equal implements the backends.Builder interface.

func (*Builder) Erf added in v0.19.2

func (b *Builder) Erf(operand backends.Op) (backends.Op, error)

Erf implements the backends.Builder interface.

func (*Builder) Exp

func (b *Builder) Exp(operand backends.Op) (backends.Op, error)

Exp implements the backends.Builder interface.

func (*Builder) Expm1

func (b *Builder) Expm1(operand backends.Op) (backends.Op, error)

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

func (*Builder) Finalize

func (b *Builder) Finalize()

Finalize immediately release the resources associated with the Builder.

func (*Builder) Floor

func (b *Builder) Floor(operand backends.Op) (backends.Op, error)

Floor implements the backends.Builder interface.

func (*Builder) Gather

func (b *Builder) Gather(operandOp, startIndicesOp backends.Op, indexVectorAxis int, offsetOutputAxes, collapsedSliceAxes, startIndexMap, sliceSizes []int, indicesAreSorted bool) (backends.Op, error)

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

func (*Builder) GreaterOrEqual

func (b *Builder) GreaterOrEqual(lhsOp, rhsOp backends.Op) (backends.Op, error)

GreaterOrEqual implements the backends.Builder interface.

func (*Builder) GreaterThan

func (b *Builder) GreaterThan(lhsOp, rhsOp backends.Op) (backends.Op, error)

GreaterThan implements the backends.Builder interface.

func (*Builder) Identity

func (b *Builder) Identity(operandOp backends.Op) (backends.Op, error)

Identity implements the backends.Identity interface.

func (*Builder) Iota

func (b *Builder) Iota(shape shapes.Shape, iotaAxis int) (backends.Op, 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 (*Builder) IsFinite

func (b *Builder) IsFinite(operandOp backends.Op) (backends.Op, error)

IsFinite implements the backends.Builder interface.

func (*Builder) LessOrEqual

func (b *Builder) LessOrEqual(lhsOp, rhsOp backends.Op) (backends.Op, error)

LessOrEqual implements the backends.Builder interface.

func (*Builder) LessThan

func (b *Builder) LessThan(lhsOp, rhsOp backends.Op) (backends.Op, error)

LessThan implements the backends.Builder interface.

func (*Builder) Log

func (b *Builder) Log(operand backends.Op) (backends.Op, error)

Log implements the backends.Builder interface.

func (*Builder) Log1p

func (b *Builder) Log1p(operand backends.Op) (backends.Op, error)

Log1p implements the backends.Builder interface.

func (*Builder) LogicalAnd

func (b *Builder) LogicalAnd(lhsOp, rhsOp backends.Op) (backends.Op, error)

LogicalAnd implements the backends.Builder interface.

func (*Builder) LogicalNot

func (b *Builder) LogicalNot(operand backends.Op) (backends.Op, error)

LogicalNot implements the backends.Builder interface.

func (*Builder) LogicalOr

func (b *Builder) LogicalOr(lhsOp, rhsOp backends.Op) (backends.Op, error)

LogicalOr implements the backends.Builder interface.

func (*Builder) LogicalXor

func (b *Builder) LogicalXor(lhsOp, rhsOp backends.Op) (backends.Op, error)

LogicalXor implements the backends.Builder interface.

func (*Builder) Logistic

func (b *Builder) Logistic(operand backends.Op) (backends.Op, error)

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

func (*Builder) Max

func (b *Builder) Max(lhsOp, rhsOp backends.Op) (backends.Op, error)

Max implements the backends.Builder interface.

func (*Builder) Min

func (b *Builder) Min(lhsOp, rhsOp backends.Op) (backends.Op, error)

Min implements the backends.Builder interface.

func (*Builder) Mul

func (b *Builder) Mul(lhsOp, rhsOp backends.Op) (backends.Op, error)

Mul implements the backends.Builder interface.

func (*Builder) Name

func (b *Builder) Name() string

Name implements backends.Builder.

func (*Builder) Neg

func (b *Builder) Neg(operand backends.Op) (backends.Op, error)

Neg implements the backends.Builder interface.

func (*Builder) NotEqual added in v0.19.3

func (b *Builder) NotEqual(lhsOp, rhsOp backends.Op) (backends.Op, error)

NotEqual implements the backends.Builder interface.

func (*Builder) OpShape

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

OpShape returns the shape of a computation Op.

func (*Builder) Parameter

func (b *Builder) Parameter(name string, shape shapes.Shape) (backends.Op, error)

Parameter creates an input parameter for the computation. During execution of the computation, this value will need to be fed in the same order it is created.

func (*Builder) Pow

func (b *Builder) Pow(lhsOp, rhsOp backends.Op) (backends.Op, error)

Pow implements the backends.Builder interface.

func (*Builder) ReduceBitwiseAnd added in v0.19.3

func (b *Builder) ReduceBitwiseAnd(operandOp backends.Op, axis ...int) (backends.Op, error)

ReduceBitwiseAnd implements the backends.Builder interface.

func (*Builder) ReduceBitwiseOr added in v0.19.3

func (b *Builder) ReduceBitwiseOr(operandOp backends.Op, axis ...int) (backends.Op, error)

ReduceBitwiseOr implements the backends.Builder interface.

func (*Builder) ReduceBitwiseXor added in v0.19.3

func (b *Builder) ReduceBitwiseXor(operandOp backends.Op, axis ...int) (backends.Op, error)

ReduceBitwiseXor implements the backends.Builder interface.

func (*Builder) ReduceLogicalAnd added in v0.19.3

func (b *Builder) ReduceLogicalAnd(operandOp backends.Op, axis ...int) (backends.Op, error)

ReduceLogicalAnd implements the backends.Builder interface.

func (*Builder) ReduceLogicalOr added in v0.19.3

func (b *Builder) ReduceLogicalOr(operandOp backends.Op, axis ...int) (backends.Op, error)

ReduceLogicalOr implements the backends.Builder interface.

func (*Builder) ReduceLogicalXor added in v0.19.3

func (b *Builder) ReduceLogicalXor(operandOp backends.Op, axis ...int) (backends.Op, error)

ReduceLogicalXor implements the backends.Builder interface.

func (*Builder) ReduceMax

func (b *Builder) ReduceMax(operandOp backends.Op, axis ...int) (backends.Op, error)

ReduceMax implements the backends.Builder interface.

func (*Builder) ReduceMin

func (b *Builder) ReduceMin(operandOp backends.Op, axis ...int) (backends.Op, error)

ReduceMin implements the backends.Builder interface.

func (*Builder) ReduceProduct

func (b *Builder) ReduceProduct(operandOp backends.Op, axis ...int) (backends.Op, error)

ReduceProduct implements the backends.Builder interface.

func (*Builder) ReduceSum

func (b *Builder) ReduceSum(operandOp backends.Op, axis ...int) (backends.Op, error)

ReduceSum implements the backends.Builder interface.

func (*Builder) ReduceWindow added in v0.19.3

func (b *Builder) ReduceWindow(operandOp backends.Op, reductionType backends.ReduceOpType, windowDimensions, strides, baseDilations, windowDilations []int, paddings [][2]int) (backends.Op, 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 (*Builder) Rem

func (b *Builder) Rem(lhsOp, rhsOp backends.Op) (backends.Op, error)

Rem implements the backends.Builder interface.

func (*Builder) Reshape

func (b *Builder) Reshape(operandOp backends.Op, dims ...int) (backends.Op, 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 (*Builder) RngBitGenerator added in v0.19.1

func (b *Builder) RngBitGenerator(stateOp backends.Op, shape shapes.Shape) (newState, values backends.Op, 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 (*Builder) Round

func (b *Builder) Round(operand backends.Op) (backends.Op, error)

Round implements the backends.Builder interface.

func (*Builder) Rsqrt

func (b *Builder) Rsqrt(operand backends.Op) (backends.Op, error)

Rsqrt implements the backends.Builder interface.

func (*Builder) ScatterMax

func (b *Builder) ScatterMax(operandOp, scatterIndicesOp, updatesOp backends.Op, indexVectorAxis int, updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int, indicesAreSorted, uniqueIndices bool) (backends.Op, error)

ScatterMax implements the backends.Builder interface.

func (*Builder) ScatterMin

func (b *Builder) ScatterMin(operandOp, scatterIndicesOp, updatesOp backends.Op, indexVectorAxis int, updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int, indicesAreSorted, uniqueIndices bool) (backends.Op, error)

ScatterMin implements the backends.Builder interface.

func (*Builder) ScatterSum

func (b *Builder) ScatterSum(operandOp, scatterIndicesOp, updatesOp backends.Op, indexVectorAxis int, updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int, indicesAreSorted, uniqueIndices bool) (backends.Op, error)

ScatterSum implements the backends.Builder interface.

func (*Builder) Sign

func (b *Builder) Sign(operand backends.Op) (backends.Op, error)

Sign implements the backends.Builder interface.

func (*Builder) Sin

func (b *Builder) Sin(operand backends.Op) (backends.Op, error)

Sin implements the backends.Builder interface.

func (*Builder) Slice added in v0.19.1

func (b *Builder) Slice(operandOp backends.Op, starts, limits, strides []int) (backends.Op, 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 (*Builder) Sqrt

func (b *Builder) Sqrt(operand backends.Op) (backends.Op, error)

Sqrt implements the backends.Builder interface.

func (*Builder) Sub

func (b *Builder) Sub(lhsOp, rhsOp backends.Op) (backends.Op, error)

Sub implements the backends.Builder interface.

func (*Builder) Tanh

func (b *Builder) Tanh(operand backends.Op) (backends.Op, error)

Tanh implements the backends.Builder interface.

func (*Builder) Transpose

func (b *Builder) Transpose(operandOp backends.Op, permutations ...int) (backends.Op, 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 (*Builder) Where

func (b *Builder) Where(conditionOp, onTrueOp, onFalseOp backends.Op) (backends.Op, error)

Where implements the backends.Builder interface.

type DTypeDispatcher

type DTypeDispatcher struct {
	Name string
	// contains filtered or unexported fields
}

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

func NewDTypeDispatcher

func NewDTypeDispatcher(name string) *DTypeDispatcher

NewDTypeDispatcher creates a new dispatcher for a class of functions.

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, fn FuncForDispatcher)

Register a function to handle a specific dtype. This overwrites any previous setting for the same dtype.

func (*DTypeDispatcher) RegisterIfNotSet

func (d *DTypeDispatcher) RegisterIfNotSet(dtype dtypes.DType, fn FuncForDispatcher)

RegisterIfNotSet a function to handle a specific dtype.

type DTypeMap

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

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

Get retrieves the value for the given dtype, or throw an exception if none was registered.

func (*DTypeMap) Register

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

Register a value for a dtype. This overwrites any previous setting for the same dtype.

func (*DTypeMap) RegisterIfNotSet

func (d *DTypeMap) RegisterIfNotSet(dtype dtypes.DType, value any)

RegisterIfNotSet a value for a dtype.

type DTypePairMap

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

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

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

func (*DTypePairMap) Register

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

Register a value for a dtype pair. This overwrites any previous setting for the same dtype.

func (*DTypePairMap) RegisterIfNotSet

func (d *DTypePairMap) RegisterIfNotSet(dtype1, dtype2 dtypes.DType, value any)

RegisterIfNotSet a value for a dtype pair.

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 need of any duplicate checks.

func (*Executable) Execute

func (e *Executable) Execute(inputs []backends.Buffer, donate []bool) ([]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 to the executable.

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 Node

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

Node in the SimpleGo computation graph.

func (*Node) IsMultiOutputs added in v0.19.1

func (n *Node) IsMultiOutputs() bool

IsMultiOutputs returns whether this node yields multiple outputs.

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 is not included because it is a specialized type, 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 is not included because it is a specialized type, 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
}

SupportedTypesConstraints enumerates the types supported by SimpleGo.

Jump to

Keyboard shortcuts

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