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
- Variables
- func New(config string) (backends.Backend, error)
- type Backend
- func (b *Backend) BufferCopyToDevice(_ backends.Buffer, _ backends.DeviceNum) (bufferOnDevice backends.Buffer, err error)
- func (b *Backend) BufferData(buffer backends.Buffer) (flat any, err error)
- func (b *Backend) BufferDeviceNum(buffer backends.Buffer) (backends.DeviceNum, error)
- func (b *Backend) BufferFinalize(backendBuffer backends.Buffer) error
- func (b *Backend) BufferFromFlatData(deviceNum backends.DeviceNum, flat any, shape shapes.Shape) (backends.Buffer, error)
- func (b *Backend) BufferShape(buffer backends.Buffer) (shapes.Shape, error)
- func (b *Backend) BufferToFlatData(backendBuffer backends.Buffer, flat any) error
- func (b *Backend) Builder(name string) backends.Builder
- func (b *Backend) Capabilities() backends.Capabilities
- func (b *Backend) Description() string
- func (b *Backend) DeviceDescription(_ backends.DeviceNum) string
- func (b *Backend) Finalize()
- func (b *Backend) HasSharedBuffers() bool
- func (b *Backend) IsFinalized() bool
- func (b *Backend) Name() string
- func (b *Backend) NewBuffer(shape shapes.Shape) *Buffer
- func (b *Backend) NewSharedBuffer(deviceNum backends.DeviceNum, shape shapes.Shape) (buffer backends.Buffer, flat any, err error)
- func (b *Backend) NumDevices() int
- func (b *Backend) String() string
- type Buffer
- type Builder
- type ClosureInputs
- type DTypeDispatcher
- type DTypeMap
- type DTypePairMap
- type Executable
- type FuncForDispatcher
- type Function
- func (f *Function) Abs(operand backends.Value) (backends.Value, error)
- func (f *Function) Add(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) AllReduce(_ []backends.Value, _ backends.ReduceOpType, _ [][]int) ([]backends.Value, error)
- func (f *Function) ArgMinMax(operandOp backends.Value, axis int, outputDType dtypes.DType, isMin bool) (backends.Value, error)
- func (f *Function) Atan2(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) BitCount(operand backends.Value) (backends.Value, error)
- func (f *Function) Bitcast(operandOp backends.Value, targetDType dtypes.DType) (backends.Value, error)
- func (f *Function) BitwiseAnd(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) BitwiseNot(operand backends.Value) (backends.Value, error)
- func (f *Function) BitwiseOr(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) BitwiseXor(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) Broadcast(operandOp backends.Value, prefixDims ...int) (backends.Value, error)
- func (f *Function) BroadcastInDim(operandOp backends.Value, outputShape shapes.Shape, broadcastAxes []int) (backends.Value, error)
- func (f *Function) Call(target backends.Function, inputs ...backends.Value) ([]backends.Value, error)
- func (f *Function) CapturedParentNodes() []*Node
- func (f *Function) Ceil(operand backends.Value) (backends.Value, error)
- func (f *Function) CheckValid() error
- func (f *Function) Clamp(minV, x, maxV backends.Value) (backends.Value, error)
- func (f *Function) Closure() (backends.Function, error)
- func (f *Function) Clz(operand backends.Value) (backends.Value, error)
- func (f *Function) Compiled() *FunctionExecutable
- func (f *Function) Concatenate(axis int, operandOps ...backends.Value) (backends.Value, error)
- func (f *Function) Constant(flat any, dims ...int) (backends.Value, error)
- func (f *Function) ConvGeneral(inputOp, kernelOp backends.Value, axes backends.ConvolveAxesConfig, ...) (backends.Value, error)
- func (f *Function) ConvGeneralDilated(inputOp, kernelOp backends.Value, axes backends.ConvolveAxesConfig, ...) (backends.Value, error)deprecated
- func (f *Function) ConvertDType(operandOp backends.Value, dtype dtypes.DType) (backends.Value, error)
- func (f *Function) Cos(operand backends.Value) (backends.Value, error)
- func (f *Function) Div(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) DotGeneral(lhsOp backends.Value, lhsContractingAxes, lhsBatchAxes []int, ...) (backends.Value, error)
- func (f *Function) Equal(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) Erf(operand backends.Value) (backends.Value, error)
- func (f *Function) Exp(operand backends.Value) (backends.Value, error)
- func (f *Function) Expm1(operand backends.Value) (backends.Value, error)
- func (f *Function) Floor(operand backends.Value) (backends.Value, error)
- func (f *Function) FusedAttentionQKVProjection(x, wQKV, biasQ, biasK, biasV backends.Value, queryDim, keyValueDim int) (queryOut, keyOut, valueOut backends.Value, err error)
- func (f *Function) FusedDense(x, weight, bias backends.Value, activation backends.ActivationType) (backends.Value, error)
- func (f *Function) FusedGelu(x backends.Value, exact bool) (backends.Value, error)
- func (f *Function) FusedLayerNorm(x backends.Value, axes []int, epsilon float64, gamma, beta backends.Value) (backends.Value, error)
- func (f *Function) FusedQuantizedDense(x, weights, bias backends.Value, weightsQuantization *backends.Quantization, ...) (backends.Value, error)
- func (f *Function) FusedScaledDotProductAttention(query, key, value, mask backends.Value, numHeads, numKVHeads int, ...) (backends.Value, error)
- func (f *Function) FusedSoftmax(x backends.Value, axis int) (backends.Value, error)
- func (f *Function) Gather(operandOp, startIndicesOp backends.Value, indexVectorAxis int, ...) (backends.Value, error)
- func (f *Function) GreaterOrEqual(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) GreaterThan(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) Identity(operandOp backends.Value) (backends.Value, error)
- func (f *Function) If(pred backends.Value, trueBranch, falseBranch backends.Function) ([]backends.Value, error)
- func (f *Function) Iota(shape shapes.Shape, iotaAxis int) (backends.Value, error)
- func (f *Function) IsAncestorOf(leafFunc *Function) bool
- func (f *Function) IsFinite(operandOp backends.Value) (backends.Value, error)
- func (f *Function) IsNaN(x backends.Value) (backends.Value, error)
- func (f *Function) LessOrEqual(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) LessThan(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) Log(operand backends.Value) (backends.Value, error)
- func (f *Function) Log1p(operand backends.Value) (backends.Value, error)
- func (f *Function) LogicalAnd(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) LogicalNot(operand backends.Value) (backends.Value, error)
- func (f *Function) LogicalOr(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) LogicalXor(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) Logistic(operand backends.Value) (backends.Value, error)
- func (f *Function) Max(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) Min(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) Mul(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) Name() string
- func (f *Function) Neg(operand backends.Value) (backends.Value, error)
- func (f *Function) NotEqual(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) Pad(operandOp, fillValueOp backends.Value, axesConfig ...backends.PadAxis) (backends.Value, error)
- func (f *Function) Parameter(name string, shape shapes.Shape, sharding *backends.ShardingSpec) (backends.Value, error)
- func (f *Function) Parent() backends.Function
- func (f *Function) Pow(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) RNGBitGenerator(stateOp backends.Value, shape shapes.Shape) (newState, values backends.Value, err error)
- func (f *Function) ReduceBitwiseAnd(operandOp backends.Value, axis ...int) (backends.Value, error)
- func (f *Function) ReduceBitwiseOr(operandOp backends.Value, axis ...int) (backends.Value, error)
- func (f *Function) ReduceBitwiseXor(operandOp backends.Value, axis ...int) (backends.Value, error)
- func (f *Function) ReduceLogicalAnd(operandOp backends.Value, axis ...int) (backends.Value, error)
- func (f *Function) ReduceLogicalOr(operandOp backends.Value, axis ...int) (backends.Value, error)
- func (f *Function) ReduceLogicalXor(operandOp backends.Value, axis ...int) (backends.Value, error)
- func (f *Function) ReduceMax(operandOp backends.Value, axis ...int) (backends.Value, error)
- func (f *Function) ReduceMin(operandOp backends.Value, axis ...int) (backends.Value, error)
- func (f *Function) ReduceProduct(operandOp backends.Value, axis ...int) (backends.Value, error)
- func (f *Function) ReduceSum(operandOp backends.Value, axis ...int) (backends.Value, error)
- func (f *Function) ReduceWindow(operandOp backends.Value, reductionType backends.ReduceOpType, ...) (backends.Value, error)
- func (f *Function) Rem(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) Reshape(operandOp backends.Value, dims ...int) (backends.Value, error)
- func (f *Function) Return(outputs []backends.Value, shardings []*backends.ShardingSpec) error
- func (f *Function) Reverse(operandOp backends.Value, axes ...int) (backends.Value, error)
- func (f *Function) Round(operand backends.Value) (backends.Value, error)
- func (f *Function) Rsqrt(operand backends.Value) (backends.Value, error)
- func (f *Function) ScatterMax(operandOp, scatterIndicesOp, updatesOp backends.Value, indexVectorAxis int, ...) (backends.Value, error)
- func (f *Function) ScatterMin(operandOp, scatterIndicesOp, updatesOp backends.Value, indexVectorAxis int, ...) (backends.Value, error)
- func (f *Function) ScatterSum(operandOp, scatterIndicesOp, updatesOp backends.Value, indexVectorAxis int, ...) (backends.Value, error)
- func (f *Function) Sign(operand backends.Value) (backends.Value, error)
- func (f *Function) Sin(operand backends.Value) (backends.Value, error)
- func (f *Function) Slice(operandOp backends.Value, starts, limits, strides []int) (backends.Value, error)
- func (f *Function) Sort(comparator backends.Function, axis int, isStable bool, ...) ([]backends.Value, error)
- func (f *Function) Sqrt(operand backends.Value) (backends.Value, error)
- func (f *Function) Sub(lhsOp, rhsOp backends.Value) (backends.Value, error)
- func (f *Function) Tanh(operand backends.Value) (backends.Value, error)
- func (f *Function) Transpose(operandOp backends.Value, permutations ...int) (backends.Value, error)
- func (f *Function) Where(conditionOp, onTrueOp, onFalseOp backends.Value) (backends.Value, error)
- func (f *Function) While(cond, body backends.Function, initialState ...backends.Value) ([]backends.Value, error)
- type FunctionExecutable
- type Node
- type PODBooleanConstraints
- type PODFloatConstraints
- type PODIntegerConstraints
- type PODNumericConstraints
- type PODSignedNumericConstraints
- type PODUnsignedConstraints
- type SupportedTypesConstraints
Constants ¶
const BackendName = "go"
BackendName to be used in GOMLX_BACKEND to specify this backend.
const MaxArgMinMaxReductionSize = 0x8000_0000
const MaxDTypes = 32
Variables ¶
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 )
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.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, }, 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.
var ErrBackendAlreadyFinalized = stderrors.New("backend already exists")
ErrBackendAlreadyFinalized is returned when attempting to register or initialize a backend that already exists.
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 ¶
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 ¶
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 ¶
BufferDeviceNum returns the deviceNum for the buffer.
func (*Backend) BufferFinalize ¶
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 ¶
BufferShape returns the shape for the buffer.
func (*Backend) BufferToFlatData ¶
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) Capabilities ¶
func (b *Backend) Capabilities() backends.Capabilities
Capabilities method returns information about what is supported by this backend.
func (*Backend) Description ¶
Description is a longer description of the Backend that can be used to pretty-print.
func (*Backend) DeviceDescription ¶ added in v0.25.0
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 ¶
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
IsFinalized returns true if the backend has been isFinalized.
func (*Backend) Name ¶
Name returns the short name of the backend. E.g.: "xla" for the Xla/PJRT plugin.
func (*Backend) NewBuffer ¶
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 ¶
NumDevices return the number of devices available for this 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
EqualNodeData implements nodeDataComparable for Buffer. For Constants, this compares the shape and the actual data values.
func (*Buffer) Fill ¶ added in v0.19.3
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.
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) NewFunction ¶ added in v0.27.0
NewFunction creates a new named function within this builder. Named functions can be called with Call() and are independent of the main function.
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 ¶
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.
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, 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 ¶
DTypeMap manages registering of an arbitrary value per dtype.
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.
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 ¶
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) 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) 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
BitwiseAnd implements the backends.Builder interface.
func (*Function) BitwiseNot ¶ added in v0.27.0
BitwiseNot implements the backends.Builder interface.
func (*Function) BitwiseXor ¶ added in v0.27.0
BitwiseXor implements the backends.Builder interface.
func (*Function) Broadcast ¶ added in v0.27.0
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
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) CheckValid ¶ added in v0.27.0
CheckValid returns an error if the builder or the function are not ok.
func (*Function) Clamp ¶ added in v0.27.0
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
Closure creates a new closure function within this function. Closures can access values from their parent function's scope.
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
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
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) 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) Expm1 ¶ added in v0.27.0
Expm1 implements the backends.Builder interface. It returns e(x)-1.
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
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
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
GreaterOrEqual implements the backends.Builder interface.
func (*Function) GreaterThan ¶ added in v0.27.0
GreaterThan implements the backends.Builder interface.
func (*Function) Identity ¶ added in v0.27.0
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
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
IsAncestorOf checks whether f is an ancestor of leafFunc. It returns true if f == leafFunc.
Typically, leafFunc will be a closure.
func (*Function) LessOrEqual ¶ added in v0.27.0
LessOrEqual implements the backends.Builder interface.
func (*Function) LogicalAnd ¶ added in v0.27.0
LogicalAnd implements the backends.Builder interface.
func (*Function) LogicalNot ¶ added in v0.27.0
LogicalNot implements the backends.Builder interface.
func (*Function) LogicalXor ¶ added in v0.27.0
LogicalXor implements the backends.Builder interface.
func (*Function) Logistic ¶ added in v0.27.0
Logistic implements the backends.Builder interface. Aka as sigmoid. It returns 1/(1+exp(-x)).
func (*Function) Name ¶ added in v0.27.0
Name returns the name of this function. For closures, this returns "".
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
Parent returns the parent function if this is a closure. Returns nil for top-level functions (including main).
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
ReduceBitwiseAnd implements the backends.Builder interface.
func (*Function) ReduceBitwiseOr ¶ added in v0.27.0
ReduceBitwiseOr implements the backends.Builder interface.
func (*Function) ReduceBitwiseXor ¶ added in v0.27.0
ReduceBitwiseXor implements the backends.Builder interface.
func (*Function) ReduceLogicalAnd ¶ added in v0.27.0
ReduceLogicalAnd implements the backends.Builder interface.
func (*Function) ReduceLogicalOr ¶ added in v0.27.0
ReduceLogicalOr implements the backends.Builder interface.
func (*Function) ReduceLogicalXor ¶ added in v0.27.0
ReduceLogicalXor implements the backends.Builder interface.
func (*Function) ReduceProduct ¶ added in v0.27.0
ReduceProduct 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) Reshape ¶ added in v0.27.0
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) Reverse ¶ added in v0.27.0
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) 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) 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) Transpose ¶ added in v0.27.0
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) 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
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
IsMultiOutputs returns whether this node yields multiple outputs.
func (*Node) MultiOutputValues ¶ added in v0.27.0
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 ¶
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 ¶
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 ¶
PODUnsignedConstraints are used for generics for the Golang pod (plain-old-data) types.
Source Files
¶
- buffers.go
- builder.go
- capabilities.go
- convgeneral.go
- convgeneral_exec.go
- dotgeneral.go
- dotgeneral_blocked.go
- dotgeneral_blocked_alt_base.go
- dotgeneral_normalized.go
- dotgeneral_normalized_alt_base.go
- dotgeneral_small_matmul.go
- dotgeneral_small_matmul_alt_base.go
- dtypes_generics.go
- exec.go
- exec_binary.go
- exec_binary_float16.go
- exec_bitcast.go
- exec_control_flow.go
- exec_convert_dtype.go
- exec_fused_ops.go
- exec_special_ops.go
- exec_special_ops_float16.go
- exec_unary.go
- exec_unary_float16.go
- function.go
- function_control_flow.go
- function_dedup.go
- function_exec.go
- fused_ops.go
- gen_convgeneral_exec_bf16.go
- gen_convgeneral_exec_full.go
- gen_convgeneral_exec_full_bf16.go
- gen_dotgeneral_blocked_alt_bf16.go
- gen_dotgeneral_blocked_alt_f16.go
- gen_dotgeneral_execution_path_enumer.go
- gen_dotgeneral_normalized_alt_bf16.go
- gen_dotgeneral_normalized_alt_f16.go
- gen_dotgeneral_small_matmul_alt_bf16.go
- gen_dotgeneral_small_matmul_alt_f16.go
- gen_exec_binary.go
- gen_register_dtypes.go
- simplego.go