gobackend

package
v0.1.24 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 26 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

Go Backend

The "go" backend 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.
  • In-operation parallelization: DotGeneral and FusedScaledDotProductAttention are parallelized across worker pools using dynamic lock-free work-stealing.
  • Use intrinsics/SIMD on platforms that allow it: AVX2 and AVX-512 SIMD kernels are implemented for DotGeneral (GEMM), FusedScaledDotProductAttention, Where, FusedLayerNorm, and activations (Gelu).
  • Eliminate common sub-expressions.

SIMD Thresholding

While SIMD vectorization dramatically accelerates large tensor computations, it introduces fixed overheads:

  • Setting up vector registers, broadcast constants, and partial load/store masks.
  • Horizontal reduction across vector lanes (e.g. shuffles, unpack chains, or intermediate stack buffer stores).
  • Memory alignment and post-loop scalar tails.

For small reduction axes (particularly in ReduceTrailing where the inner axis $B$ is reduced across many rows $A$, or in ReduceLeading where $B \le 4$), simple scalar loops in CPU registers outperform SIMD.

Architecture & Caching Mechanism
  1. Clean Fallback: When a SIMD executor determines that an input axis or total tensor size is below the architecture-specific threshold, it immediately returns (nil, gobackend.ErrFallback) before allocating any output buffer or consuming inputs. The dispatch loop in executable.go falls through to the next registered executor (Generic / Scalar).

  2. Node-Level Executor Caching: Each *Node contains a thread-safe cachedExecutorIdx atomic.Int32 (storing the 1-based index idx + 1 of the winning executor in nodeExecutors[node.OpType]).

    • On the first execution, the fallback chain runs to discover the winning executor (SIMD or Scalar).
    • Once an executor succeeds without ErrFallback, its 1-based index is stored in node.cachedExecutorIdx.
    • Subsequent executions read nodeExecutors[node.OpType][cachedIdx-1] directly with zero heap allocations, zero struct wrappers, and 0 ns dispatch overhead.
    • For dynamic shapes, GoMLX uses ShapeSpecialization (cached per concrete dimension tuple). Each specialization has its own concrete resolvedNodes []*Node, so the optimal executor is cached automatically per specialized shape configuration.
Finding & Updating Thresholds

The thresholds are discovered empirically using a dedicated benchmark suite that measures the median execution duration across iterations using testutil.DurationSampler (16K reservoir sampling):

GOEXPERIMENT=simd go test -v -run TestFindReduceThresholds ./internal/gobackend/ops

This prints a Markdown comparison table showing Scalar Median, SIMD Median, and the Ratio (SIMD/Scalar) across data types and dimensions for:

  • ReduceTrailing: shape $[A, B] \rightarrow [A]$ (reducing inner dimension $B$).
  • ReduceLeading: shape $[A, B] \rightarrow [B]$ (reducing outer dimension $A$, vectorized across $B$).
  • ReduceAll: shape $[N] \rightarrow [1]$ (reducing entire tensor).
Re-running on AVX-512 Hardware

To calibrate thresholds for AVX-512:

  1. Run the benchmark on an AVX-512 machine:
    GOEXPERIMENT=simd go test -v -run TestFindReduceThresholds ./internal/gobackend/ops
    
  2. Inspect the crossover points (where Ratio > 1.05 indicates Scalar is faster).
  3. Update avx512ReduceThresholds in compute/internal/gobackend/ops/reduce_thresholds_amd64.go.

Assembly Guidelines: Avoiding AVX-SSE Transition Penalties

When writing AMD64 assembly routines for AVX2 or AVX-512, never mix non-VEX (legacy SSE) instructions with VEX/EVEX instructions.

The Problem: AVX $\leftrightarrow$ SSE State Transitions

On x86_64 processors (especially Intel architectures like Skylake through Alder Lake / Raptor Lake), the CPU pipeline manages upper register bits (e.g. bits 128–255 of YMM registers) differently depending on whether VEX-encoded or legacy SSE-encoded instructions are executing.

When a legacy SSE instruction (such as MOVSS, ADDSS, DIVSS, SQRTSS, or CVTSL2SS) executes while the upper bits of any YMM register are active or not cleanly zeroed:

  1. The CPU hardware must save the upper 128 bits of all YMM registers to an internal buffer and transition the register state.
  2. Executing a subsequent AVX/VEX instruction requires another transition to restore state.
  3. Each transition stalls the execution pipeline for ~70 to 140 CPU cycles.

In tight loops or row-by-row reductions (such as LayerNorm, RMSNorm, or Softmax), having even 2–4 transitions per row creates a massive fixed latency penalty. For example, in a 100-row LayerNorm operation, this introduced an artificial ~18 µs floor regardless of tensor size, completely negating SIMD benefits on small-to-medium batches. Eliminating these transitions yielded a 34× speedup (from 18.8 µs down to 550 ns for batch size 16) and improved full model training throughput by 20%.

Rules for Assembly Implementations
  1. Always Use VEX/EVEX Instructions (V...): In any kernel using YMM (Y0–Y15) or ZMM (Z0–Z31) registers, all scalar floating-point instructions must also use their VEX-prefixed counterparts.

  2. Go Assembly Opcode Names for Scalar VEX Operations: Go's internal assembler has specific naming conventions for 3-operand VEX scalar and conversion instructions:

    Operation Legacy SSE (Avoid in AVX code) VEX Equivalent (Use this)
    Float32 Move MOVSS src, dst VMOVSS src, dst
    Float64 Move MOVSD src, dst VMOVSD src, dst
    Float32 Add/Sub/Mul ADDSS / SUBSS / MULSS src, dst VADDSS / VSUBSS / VMULSS src2, src1, dst
    Float64 Add/Sub/Mul ADDSD / SUBSD / MULSD src, dst VADDSD / VSUBSD / VMULSD src2, src1, dst
    Float32 Division DIVSS src, dst VDIVSS divisor, dividend, dst
    Float64 Division DIVSD src, dst VDIVSD divisor, dividend, dst
    Square Root SQRTSS src, dst VSQRTSS src, src, dst
    Int32 $\to$ Float32 CVTSL2SS reg, xmm VCVTSI2SSL reg, xmm, dst
    Int64 $\to$ Float64 CVTSQ2SD reg, xmm VCVTSI2SDQ reg, xmm, dst
    Zeroing Registers XORPS xmm, xmm VXORPS ymm, ymm, ymm

    [!NOTE] For VDIVSS and VDIVSD, the operand order in Go assembly is VDIVSS divisor, dividend, dst (e.g. VDIVSS X0, X1, X1 computes X1 = X1 / X0). For VCVTSI2SSL, the trailing L indicates a 32-bit integer register (R11 / R11D), while VCVTSI2SDQ with trailing Q indicates a 64-bit integer register.

  3. Always Call VZEROUPPER Before Returning (RET): Standard Go compiler code generation uses legacy SSE instructions for scalar float math. If an assembly routine leaves the upper halves of YMM/ZMM registers in a "dirty" state upon returning, the very next Go-compiled SSE instruction will trigger an AVX $\to$ SSE penalty. Always emit VZEROUPPER immediately before every RET instruction in functions using 256-bit or 512-bit registers.

Fused Operations & Intra-Op Parallelization Architecture

When implementing compute-intensive fused operations (such as FusedScaledDotProductAttention), the Go backend employs several core design principles to maximize hardware efficiency on modern multi-core x86_64 processors:

1. Dynamic Work-Stealing with Atomic Counters

Rather than using Go channels or statically partitioning work across goroutines:

  • Avoid Go Channels in Inner Loops: Distributing work units through Go channels introduces channel mutex lock contention, channel buffer overhead, and goroutine parking/unparking latency.
  • Avoid Static Chunking: Dividing tasks evenly across $W$ workers upfront leads to thread imbalance when individual tasks have variable workloads (e.g. varying sequence lengths due to padding) or when the number of tasks does not divide evenly by worker count.
  • Atomic Work-Stealing:
    1. Workers are spawned up to $\min(N_{\text{tasks}}, \text{backend.Workers})$.
    2. Workers dynamically steal the next available task index using an atomic counter:
      for {
          taskIdx := int(taskCounter.Add(1) - 1)
          if taskIdx >= numTasks {
              break
          }
          // Process taskIdx
      }
      
    3. This provides zero-allocation, lock-free dynamic load balancing where faster cores naturally process more tasks.
2. Cache-Aware Task Decomposition (KV-Head Grouping in GQA/MQA)

In Grouped Query Attention (GQA) and Multi-Query Attention (MQA), multiple query heads share a single key/value (KV) head ($N_{\text{query}} \ge N_{\text{kv}}$):

  • If tasks are decomposed per individual query head, multiple worker goroutines concurrently compete for memory bandwidth fetching identical $K$ and $V$ tensors from L3 cache or DRAM.
  • By defining each parallel task as a $(batch, kv_head)$ chunk, a single worker iterates over all $G = N_{\text{query}} / N_{\text{kv}}$ query heads sequentially.
  • This guarantees that the key and value sequences ($S_{\text{kv}} \times D$) are loaded once and remain resident in the core's private L1/L2 cache while computing all $G$ query heads.
3. Zero-Transpose Direct Strided Memory Access

Deep learning models frequently switch between layout conventions (e.g. LayoutBSHD $[B, S, H, D]$ and LayoutBHSD $[B, H, S, D]$):

  • Decomposing attention into explicit 4D tensor permutations (Transpose) incurs severe memory copying penalties (accounting for ~20% of CPU time and dominating runtime.memmove).
  • In row-major tensors, the inner head dimension $D$ is contiguous (stride 1) in both layouts.
  • By parametrizing inner loops with sequence strides (qSeqStride, kvSeqStride) and query group strides (qGroupStride), compute kernels can read operands and write outputs directly in their native layouts with zero tensor copying.
4. In-Cache Softmax & Register-Accumulated Values
  • Avoid Materializing $S \times S$ Matrices in Memory: Writing intermediate attention logits or probabilities to DRAM creates severe bandwidth bottlenecks.
  • Per-Worker Scratch Buffers: Each worker allocates a small temporary slice ($S_{\text{kv}}$ floats) reused across tokens.
  • In-Register Fused Math: Scale factors, causal masks, additive masks, and attention biases are folded directly into vector registers during dot-product accumulation. Softmax exponentiation uses fast vectorized polynomial approximations (exp512 / exp256), and weighted values ($P \cdot V$) accumulate directly into vector registers before writing directly to the final destination buffer.
5. Head Dimension Specialization ($D \in {32, 64, 128}$)

When the inner loop over dimension $D$ has a dynamic upper bound, the compiler cannot unroll vector loops and must emit loop counter branches. Specializing kernels for standard head dimensions allows completely unrolling into a fixed set of vector registers (e.g. 2 Float32x16 registers for $D=32$ on AVX-512, 4 for $D=64$, 8 for $D=128$), sustaining near-peak FMA throughput.

Documentation

Overview

Package gobackend implements a compute.Backend using Go only.

Its main goal is portability, and not be a state-of-the art ML backend.

It also serves as a reference implementation for the compute.Backend interface.

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 (
	// ThresholdNone indicates that SIMD is always as fast or faster (or ties), so no fallback threshold is needed.
	ThresholdNone = 0

	// ThresholdAlwaysFallBack indicates that scalar is always faster (or SIMD unsupported), so always fall back to scalar.
	ThresholdAlwaysFallBack = -1
)
View Source
const (
	// Bold enables the bold text style
	Bold = "\x1b[1m"
	// Reset clears all text formatting and colors back to default
	Reset = "\x1b[0m"
	// Blue enables the blue text style
	Blue = "\x1b[34m"
	// Green enables the green text style
	Green = "\x1b[32m"
	// Red enables the red text style
	Red = "\x1b[31m"
	// Underline enables the underline text style
	Underline = "\x1b[4m"
)
View Source
const BackendName = "go"

BackendName to be used in GOMLX_BACKEND to specify this backend.

View Source
const DefaultNumExecutors = 8

DefaultNumExecutors is the default number of concurrent worker executors used in executeParallel to execute ready graph nodes.

View Source
const MaxDTypes = 32

Variables

View Source
var (

	// MultiOutputsNodeExecutors should be populated during initialization for the multi-output ops
	// implemented. E.g.: RNGBitGenerator.
	MultiOutputsNodeExecutors [compute.OpTypeLast]nodeMultiOutputExecutor

	// NodeClosureExecutors should be populated during initialization for ops that call closures.
	// E.g.: If, While, Sort.
	// These executors receive captured inputs separately with explicit ownership tracking.
	NodeClosureExecutors [compute.OpTypeLast]nodeClosureExecutor
)
View Source
var (
	RegisterAbs = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Abs",
	}
	RegisterAdd = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Add",
	}
	RegisterArgMinMax = OpHandlerRegistration[func(f *Function, x compute.Value, axis int, outputDType dtypes.DType, isMin bool) (compute.Value, error)]{
		Method: "ArgMinMax",
	}
	RegisterAtan2 = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Atan2",
	}
	RegisterBatchNormForInference = OpHandlerRegistration[func(f *Function, operand compute.Value, scale compute.Value, offset compute.Value, mean compute.Value, variance compute.Value, epsilon float32, featureAxis int) (compute.Value, error)]{
		Method: "BatchNormForInference",
	}
	RegisterBatchNormForTraining = OpHandlerRegistration[func(f *Function, operand compute.Value, scale compute.Value, offset compute.Value, epsilon float32, featureAxis int) (normalized compute.Value, batchMean compute.Value, batchVariance compute.Value, err error)]{
		Method: "BatchNormForTraining",
	}
	RegisterBatchNormGradient = OpHandlerRegistration[func(f *Function, operand compute.Value, scale compute.Value, mean compute.Value, variance compute.Value, gradOutput compute.Value, epsilon float32, featureAxis int) (gradOperand compute.Value, gradScale compute.Value, gradOffset compute.Value, err error)]{
		Method: "BatchNormGradient",
	}
	RegisterBitcast = OpHandlerRegistration[func(f *Function, operand compute.Value, targetDType dtypes.DType) (compute.Value, error)]{
		Method: "Bitcast",
	}
	RegisterBitCount = OpHandlerRegistration[func(f *Function, operand compute.Value) (compute.Value, error)]{
		Method: "BitCount",
	}
	RegisterBitwiseAnd = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "BitwiseAnd",
	}
	RegisterBitwiseNot = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "BitwiseNot",
	}
	RegisterBitwiseOr = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "BitwiseOr",
	}
	RegisterBitwiseXor = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "BitwiseXor",
	}
	RegisterBroadcastInDim = OpHandlerRegistration[func(f *Function, operand compute.Value, outputShape shapes.Shape, broadcastAxes []int) (compute.Value, error)]{
		Method: "BroadcastInDim",
	}
	RegisterCall = OpHandlerRegistration[func(f *Function, fn compute.Function, inputs ...compute.Value) ([]compute.Value, error)]{
		Method: "Call",
	}
	RegisterCeil = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Ceil",
	}
	RegisterClamp = OpHandlerRegistration[func(f *Function, min compute.Value, x compute.Value, max compute.Value) (compute.Value, error)]{
		Method: "Clamp",
	}
	RegisterClz = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Clz",
	}
	RegisterComplex = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Complex",
	}
	RegisterConcatenate = OpHandlerRegistration[func(f *Function, axis int, operands ...compute.Value) (compute.Value, error)]{
		Method: "Concatenate",
	}
	RegisterConj = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Conj",
	}
	RegisterConvertDType = OpHandlerRegistration[func(f *Function, x compute.Value, dtype dtypes.DType) (compute.Value, error)]{
		Method: "ConvertDType",
	}
	RegisterConvGeneral = OpHandlerRegistration[func(f *Function, input compute.Value, kernel compute.Value, axes compute.ConvolveAxesConfig, strides []int, paddings [][2]int, inputDilations []int, kernelDilations []int, channelGroupCount int, batchGroupCount int) (compute.Value, error)]{
		Method: "ConvGeneral",
	}
	RegisterCos = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Cos",
	}
	RegisterCumMax = OpHandlerRegistration[func(f *Function, operand compute.Value, axis int, options compute.CumSumOptions) (compute.Value, error)]{
		Method: "CumMax",
	}
	RegisterCumSum = OpHandlerRegistration[func(f *Function, operand compute.Value, axis int, options compute.CumSumOptions) (compute.Value, error)]{
		Method: "CumSum",
	}
	RegisterDiv = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Div",
	}
	RegisterDotGeneral = OpHandlerRegistration[func(f *Function, lhs compute.Value, lhsContractingAxes []int, lhsBatchAxes []int, rhs compute.Value, rhsContractingAxes []int, rhsBatchAxes []int, config compute.DotGeneralConfig) (compute.Value, error)]{
		Method: "DotGeneral",
	}
	RegisterDynamicBroadcastInDim = OpHandlerRegistration[func(f *Function, operand compute.Value, broadcastAxes []int, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)]{
		Method: "DynamicBroadcastInDim",
	}
	RegisterDynamicDimensionSize = OpHandlerRegistration[func(f *Function, operand compute.Value, axis int) (compute.Value, error)]{
		Method: "DynamicDimensionSize",
	}
	RegisterDynamicIota = OpHandlerRegistration[func(f *Function, dtype dtypes.DType, iotaAxis int, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)]{
		Method: "DynamicIota",
	}
	RegisterDynamicPad = OpHandlerRegistration[func(f *Function, x compute.Value, fillValue compute.Value, axesConfig ...compute.DynamicPadAxis) (compute.Value, error)]{
		Method: "DynamicPad",
	}
	RegisterDynamicReshape = OpHandlerRegistration[func(f *Function, operand compute.Value, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)]{
		Method: "DynamicReshape",
	}
	RegisterDynamicShape = OpHandlerRegistration[func(f *Function, operand compute.Value) (compute.Value, error)]{
		Method: "DynamicShape",
	}
	RegisterDynamicSlice = OpHandlerRegistration[func(f *Function, operand compute.Value, startIndices []compute.Value, sliceDims []int) (compute.Value, error)]{
		Method: "DynamicSlice",
	}
	RegisterDynamicUpdateSlice = OpHandlerRegistration[func(f *Function, operand compute.Value, update compute.Value, startIndices []compute.Value) (compute.Value, error)]{
		Method: "DynamicUpdateSlice",
	}
	RegisterEqual = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Equal",
	}
	RegisterEqualTotalOrder = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "EqualTotalOrder",
	}
	RegisterErf = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Erf",
	}
	RegisterExp = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Exp",
	}
	RegisterExpm1 = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Expm1",
	}
	RegisterFFT = OpHandlerRegistration[func(f *Function, operand compute.Value, fftType compute.FFTType, fftLength []int) (compute.Value, error)]{
		Method: "FFT",
	}
	RegisterFloor = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Floor",
	}
	RegisterFusedActivation = OpHandlerRegistration[func(f *Function, x compute.Value, cfg compute.ActivationConfig) (compute.Value, error)]{
		Method: "FusedActivation",
	}
	RegisterFusedActivationVJP = OpHandlerRegistration[func(f *Function, y compute.Value, x compute.Value, dOutput compute.Value, cfg compute.ActivationConfig) (compute.Value, error)]{
		Method: "FusedActivationVJP",
	}
	RegisterFusedAttentionQKVProjection = OpHandlerRegistration[func(f *Function, x compute.Value, wQKV compute.Value, biasQ compute.Value, biasK compute.Value, biasV compute.Value, queryDim int, keyValueDim int) (query compute.Value, key compute.Value, value compute.Value, err error)]{
		Method: "FusedAttentionQKVProjection",
	}
	RegisterFusedDense = OpHandlerRegistration[func(f *Function, x compute.Value, weight compute.Value, bias compute.Value, options compute.DenseConfig) (compute.Value, error)]{
		Method: "FusedDense",
	}
	RegisterFusedDenseVJP = OpHandlerRegistration[func(f *Function, x compute.Value, weight compute.Value, bias compute.Value, y compute.Value, dOutput compute.Value, options compute.DenseConfig) (dx compute.Value, dWeight compute.Value, dBias compute.Value, err error)]{
		Method: "FusedDenseVJP",
	}
	RegisterFusedLayerNorm = OpHandlerRegistration[func(f *Function, x compute.Value, axes []int, epsilon float64, gamma compute.Value, beta compute.Value) (compute.Value, error)]{
		Method: "FusedLayerNorm",
	}
	RegisterFusedQuantizedDense = OpHandlerRegistration[func(f *Function, x compute.Value, weights compute.Value, bias compute.Value, weightsQuantization *compute.Quantization, activation compute.ActivationType) (compute.Value, error)]{
		Method: "FusedQuantizedDense",
	}
	RegisterFusedScaledDotProductAttention = OpHandlerRegistration[func(f *Function, query compute.Value, key compute.Value, value compute.Value, axesLayout compute.AttentionAxesLayout, options *compute.ScaledDotProductAttentionConfig) (output compute.Value, statesForVJP []compute.Value, err error)]{
		Method: "FusedScaledDotProductAttention",
	}
	RegisterFusedScaledDotProductAttentionVJP = OpHandlerRegistration[func(f *Function, query compute.Value, key compute.Value, value compute.Value, axesLayout compute.AttentionAxesLayout, options *compute.ScaledDotProductAttentionConfig, output compute.Value, statesForVJP []compute.Value, dOutput compute.Value) (dQuery compute.Value, dKey compute.Value, dValue compute.Value, err error)]{
		Method: "FusedScaledDotProductAttentionVJP",
	}
	RegisterFusedSoftmax = OpHandlerRegistration[func(f *Function, x compute.Value, axis int) (compute.Value, error)]{
		Method: "FusedSoftmax",
	}
	RegisterGather = OpHandlerRegistration[func(f *Function, operand compute.Value, startIndices compute.Value, indexVectorAxis int, offsetOutputAxes []int, collapsedSliceAxes []int, startIndexMap []int, sliceSizes []int, indicesAreSorted bool) (compute.Value, error)]{
		Method: "Gather",
	}
	RegisterGreaterOrEqual = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "GreaterOrEqual",
	}
	RegisterGreaterOrEqualTotalOrder = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "GreaterOrEqualTotalOrder",
	}
	RegisterGreaterThan = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "GreaterThan",
	}
	RegisterGreaterThanTotalOrder = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "GreaterThanTotalOrder",
	}
	RegisterIdentity = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Identity",
	}
	RegisterIf = OpHandlerRegistration[func(f *Function, pred compute.Value, trueBranch compute.Function, falseBranch compute.Function) ([]compute.Value, error)]{
		Method: "If",
	}
	RegisterImag = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Imag",
	}
	RegisterIota = OpHandlerRegistration[func(f *Function, shape shapes.Shape, iotaAxis int) (compute.Value, error)]{
		Method: "Iota",
	}
	RegisterIsFinite = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "IsFinite",
	}
	RegisterIsNaN = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "IsNaN",
	}
	RegisterLessOrEqual = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "LessOrEqual",
	}
	RegisterLessOrEqualTotalOrder = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "LessOrEqualTotalOrder",
	}
	RegisterLessThan = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "LessThan",
	}
	RegisterLessThanTotalOrder = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "LessThanTotalOrder",
	}
	RegisterLog = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Log",
	}
	RegisterLog1p = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Log1p",
	}
	RegisterLogicalAnd = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "LogicalAnd",
	}
	RegisterLogicalNot = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "LogicalNot",
	}
	RegisterLogicalOr = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "LogicalOr",
	}
	RegisterLogicalXor = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "LogicalXor",
	}
	RegisterLogistic = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Logistic",
	}
	RegisterMax = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Max",
	}
	RegisterMin = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Min",
	}
	RegisterMul = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Mul",
	}
	RegisterNeg = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Neg",
	}
	RegisterNotEqual = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "NotEqual",
	}
	RegisterNotEqualTotalOrder = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "NotEqualTotalOrder",
	}
	RegisterOptimizationBarrier = OpHandlerRegistration[func(f *Function, operands ...compute.Value) ([]compute.Value, error)]{
		Method: "OptimizationBarrier",
	}
	RegisterPad = OpHandlerRegistration[func(f *Function, x compute.Value, fillValue compute.Value, axesConfig ...compute.PadAxis) (compute.Value, error)]{
		Method: "Pad",
	}
	RegisterPow = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Pow",
	}
	RegisterQuantizedEmbeddingLookup = OpHandlerRegistration[func(f *Function, data compute.Value, indices compute.Value, dataQuantization *compute.Quantization) (compute.Value, error)]{
		Method: "QuantizedEmbeddingLookup",
	}
	RegisterReal = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Real",
	}
	RegisterReduceBitwiseAnd = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceBitwiseAnd",
	}
	RegisterReduceBitwiseOr = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceBitwiseOr",
	}
	RegisterReduceBitwiseXor = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceBitwiseXor",
	}
	RegisterReduceLogicalAnd = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceLogicalAnd",
	}
	RegisterReduceLogicalOr = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceLogicalOr",
	}
	RegisterReduceLogicalXor = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceLogicalXor",
	}
	RegisterReduceMax = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceMax",
	}
	RegisterReduceMin = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceMin",
	}
	RegisterReduceProduct = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceProduct",
	}
	RegisterReduceSum = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "ReduceSum",
	}
	RegisterReduceWindow = OpHandlerRegistration[func(f *Function, input compute.Value, reductionType compute.ReduceOpType, windowDimensions []int, strides []int, inputDilations []int, windowDilations []int, paddings [][2]int) (compute.Value, error)]{
		Method: "ReduceWindow",
	}
	RegisterRem = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Rem",
	}
	RegisterReshape = OpHandlerRegistration[func(f *Function, x compute.Value, dimensions ...int) (compute.Value, error)]{
		Method: "Reshape",
	}
	RegisterReverse = OpHandlerRegistration[func(f *Function, x compute.Value, axes ...int) (compute.Value, error)]{
		Method: "Reverse",
	}
	RegisterRNGBitGenerator = OpHandlerRegistration[func(f *Function, state compute.Value, shape shapes.Shape) (newState compute.Value, values compute.Value, err error)]{
		Method: "RNGBitGenerator",
	}
	RegisterRound = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Round",
	}
	RegisterRsqrt = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Rsqrt",
	}
	RegisterScatterMax = OpHandlerRegistration[func(f *Function, operand compute.Value, scatterIndices compute.Value, updates compute.Value, indexVectorAxis int, updateWindowAxes []int, insertedWindowAxes []int, scatterAxesToOperandAxes []int, indicesAreSorted bool, uniqueIndices bool) (compute.Value, error)]{
		Method: "ScatterMax",
	}
	RegisterScatterMin = OpHandlerRegistration[func(f *Function, operand compute.Value, scatterIndices compute.Value, updates compute.Value, indexVectorAxis int, updateWindowAxes []int, insertedWindowAxes []int, scatterAxesToOperandAxes []int, indicesAreSorted bool, uniqueIndices bool) (compute.Value, error)]{
		Method: "ScatterMin",
	}
	RegisterScatterSum = OpHandlerRegistration[func(f *Function, operand compute.Value, scatterIndices compute.Value, updates compute.Value, indexVectorAxis int, updateWindowAxes []int, insertedWindowAxes []int, scatterAxesToOperandAxes []int, indicesAreSorted bool, uniqueIndices bool) (compute.Value, error)]{
		Method: "ScatterSum",
	}
	RegisterSchedulingBarrier = OpHandlerRegistration[func(f *Function, operand compute.Value, dependencies ...compute.Value) (compute.Value, error)]{
		Method: "SchedulingBarrier",
	}
	RegisterSelectAndScatterMax = OpHandlerRegistration[func(f *Function, operand compute.Value, source compute.Value, windowDimensions []int, windowStrides []int, paddings [][2]int) (compute.Value, error)]{
		Method: "SelectAndScatterMax",
	}
	RegisterSelectAndScatterMin = OpHandlerRegistration[func(f *Function, operand compute.Value, source compute.Value, windowDimensions []int, windowStrides []int, paddings [][2]int) (compute.Value, error)]{
		Method: "SelectAndScatterMin",
	}
	RegisterShiftLeft = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "ShiftLeft",
	}
	RegisterShiftRightArithmetic = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "ShiftRightArithmetic",
	}
	RegisterShiftRightLogical = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "ShiftRightLogical",
	}
	RegisterSign = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Sign",
	}
	RegisterSin = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Sin",
	}
	RegisterSlice = OpHandlerRegistration[func(f *Function, x compute.Value, starts []int, limits []int, strides []int) (compute.Value, error)]{
		Method: "Slice",
	}
	RegisterSort = OpHandlerRegistration[func(f *Function, comparator compute.Function, axis int, isStable bool, inputs ...compute.Value) ([]compute.Value, error)]{
		Method: "Sort",
	}
	RegisterSqrt = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Sqrt",
	}
	RegisterSub = OpHandlerRegistration[func(f *Function, lhs compute.Value, rhs compute.Value) (compute.Value, error)]{
		Method: "Sub",
	}
	RegisterTanh = OpHandlerRegistration[func(f *Function, x compute.Value) (compute.Value, error)]{
		Method: "Tanh",
	}
	RegisterTranspose = OpHandlerRegistration[func(f *Function, x compute.Value, permutation ...int) (compute.Value, error)]{
		Method: "Transpose",
	}
	RegisterWhere = OpHandlerRegistration[func(f *Function, condition compute.Value, onTrue compute.Value, onFalse compute.Value) (compute.Value, error)]{
		Method: "Where",
	}
	RegisterWhile = OpHandlerRegistration[func(f *Function, cond compute.Function, body compute.Function, initialState ...compute.Value) ([]compute.Value, error)]{
		Method: "While",
	}
)

Registration variables for the op handlers.

View Source
var (
	// IsAVX512Allowed returns false on non-amd64 architectures or when SIMD is disabled.
	IsAVX512Allowed = false

	// IsAVX2Allowed returns false on non-amd64 architectures or when SIMD is disabled.
	IsAVX2Allowed = false

	// ARM64 SIMD flags return false on non-arm64 architectures or when SIMD is disabled.
	IsNEONAllowed         = false
	IsARM64FP16Allowed    = false
	IsARM64BF16Allowed    = false
	IsARM64DotProdAllowed = false
	IsARM64I8MMAllowed    = false
	IsSVEAllowed          = false
	IsSMEAllowed          = false
)
View Source
var Capabilities = compute.Capabilities{
	Functions:                   true,
	DynamicAxes:                 true,
	DynamicShapes:               compute.DynamicShapesNative,
	DynamicDimDType:             dtypes.Int64,
	PreferConstantsForVariables: true,
	SharedConstants:             true,

	Operations: map[compute.OpType]bool{

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

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

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

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

		compute.OpTypeArgMinMax:             true,
		compute.OpTypeBitcast:               true,
		compute.OpTypeBroadcastInDim:        true,
		compute.OpTypeDynamicBroadcastInDim: true,
		compute.OpTypeConcatenate:           true,
		compute.OpTypeConvertDType:          true,
		compute.OpTypeCumMax:                true,
		compute.OpTypeCumSum:                true,
		compute.OpTypeDot:                   true,
		compute.OpTypeDotGeneral:            true,
		compute.OpTypeGather:                true,
		compute.OpTypeIdentity:              true,
		compute.OpTypeIota:                  true,
		compute.OpTypeDynamicIota:           true,
		compute.OpTypePad:                   true,
		compute.OpTypeDynamicPad:            true,
		compute.OpTypeDynamicDimensionSize:  true,
		compute.OpTypeDynamicShape:          true,
		compute.OpTypeReduceBitwiseAnd:      true,
		compute.OpTypeReduceBitwiseOr:       true,
		compute.OpTypeReduceBitwiseXor:      true,
		compute.OpTypeReduceLogicalAnd:      true,
		compute.OpTypeReduceLogicalOr:       true,
		compute.OpTypeReduceLogicalXor:      true,
		compute.OpTypeReduceMax:             true,
		compute.OpTypeReduceMin:             true,
		compute.OpTypeReduceProduct:         true,
		compute.OpTypeReduceSum:             true,
		compute.OpTypeReduceWindow:          true,
		compute.OpTypeReshape:               true,
		compute.OpTypeDynamicReshape:        true,
		compute.OpTypeReverse:               true,
		compute.OpTypeRNGBitGenerator:       true,
		compute.OpTypeScatterMax:            true,
		compute.OpTypeScatterMin:            true,
		compute.OpTypeScatterSum:            true,
		compute.OpTypeShiftLeft:             true,
		compute.OpTypeShiftRightArithmetic:  true,
		compute.OpTypeShiftRightLogical:     true,
		compute.OpTypeSlice:                 true,
		compute.OpTypeTranspose:             true,
		compute.OpTypeWhere:                 true,
		compute.OpTypeConvGeneral:           true,
		compute.OpTypeOptimizationBarrier:   true,
		compute.OpTypeSchedulingBarrier:     true,

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

		compute.OpTypeFusedSoftmax:                   true,
		compute.OpTypeFusedLayerNorm:                 true,
		compute.OpTypeFusedActivation:                true,
		compute.OpTypeFusedActivationVJP:             true,
		compute.OpTypeFusedDense:                     true,
		compute.OpTypeFusedDenseVJP:                  true,
		compute.OpTypeFusedScaledDotProductAttention: true,
		compute.OpTypeFusedAttentionQKVProjection:    true,
		compute.OpTypeFusedQuantizedDense:            true,
		compute.OpTypeQuantizedEmbeddingLookup:       true,

		compute.OpTypeSelectAndScatterMax: true,
		compute.OpTypeSelectAndScatterMin: true,
		compute.OpTypeDynamicUpdateSlice:  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 Go backend: 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 ErrFallback = errors.New("node executor not implemented for input combination")

ErrFallback is returned by a NodeExecutor when it does not support (or is too slow for) the given input combination (e.g. data type or broadcast pattern), signaling the execution engine to fall back to the next registered executor.

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

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

The singleton is never destroyed.

View Source
var KnownOptionsSetters = make(map[string]func(b *Backend, key string) error)

KnownOptionsSetters registers handlers for backend configuration options. These allow any sub-package to register option setters.

The key is the name of the option: it can't take any values yet.

NumericDTypes is the list of numeric data types supported by the Go backend. This excludes Bool and is used for operations like DotGeneral that only work on numeric types.

Functions

func CheckClosureParams

func CheckClosureParams(opName, closureName string, fn *Function, expected []*Node) error

CheckClosureParams verifies that a closure's parameters match expected shapes.

func CopyFlat

func CopyFlat(flatDst, flatSrc any)

CopyFlat assumes both flat slices are of the same underlying type. Fast paths for common dtypes avoid reflection overhead.

func DataEqual

func DataEqual(a, b any) bool

DataEqual compares node data for equality.

If the node data field implements NodeDataComparable interface, it uses the EqualNodeData method for comparison.

Otherwise it has fallback for the primitive types int, []int strucs (using shallow equal "==") and pointers to structs.

func GetOrSetCachedForm added in v0.1.20

func GetOrSetCachedForm[T any](cd *ConstantData, computeFn func() T) T

GetOrSetCachedForm returns the cached representation cast to T if already present (via a lock-free atomic load). Otherwise, it locks cd.mu, re-checks that cachedForm is still nil, calls computeFn() to build the cached representation, stores it in cachedForm, releases rawBuffer (if !isRawBufferPinned), and unlocks cd.mu.

func IsConstantNode added in v0.1.13

func IsConstantNode(node *Node) bool

IsConstantNode is a helper function to check whether a node is constant.

func MutableBytesGeneric

func MutableBytesGeneric[T SupportedTypesConstraints](b *Buffer) ([]byte, error)

MutableBytesGeneric is the generic implementation of mutableBytes.

func New

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

New constructs a new Go backend. There are no configurations, the string is simply ignored.

func RegisterTransformation

func RegisterTransformation(priority int, transformation GraphTransformation)

RegisterTransformation registers a graph transformation to be executed during compilation.

This should be called in init() functions only, it must not be called after the program starts.

func ScheduleStrategyStrings

func ScheduleStrategyStrings() []string

ScheduleStrategyStrings returns a slice of all String values of the enum

func SetBinaryTrailingArchDispatcher added in v0.1.10

func SetBinaryTrailingArchDispatcher(priority RegisterPriority, fn BinaryTrailingArchFn)

SetBinaryTrailingArchDispatcher registers an architecture-specific binary trailing broadcast dispatcher with a priority. Dispatchers are tried in descending order of priority; if a higher-priority dispatcher returns false, the next one is tried.

func SetLayerNormTrailingArchDispatcher added in v0.1.10

func SetLayerNormTrailingArchDispatcher(priority RegisterPriority, fn LayerNormTrailingArchFn)

SetLayerNormTrailingArchDispatcher registers an architecture-specific LayerNorm dispatcher. Dispatchers are tried in descending order of priority; if a higher-priority dispatcher returns false, the next one is tried.

func SetNodeExecutor

func SetNodeExecutor(opType compute.OpType, priority RegisterPriority, executor NodeExecutor)

SetNodeExecutor sets the node executor for the given operation type with the specified priority. Executors are stored in descending order of priority so higher-priority implementations are tried first.

func SetReduceLeadingSumArchDispatcher added in v0.1.10

func SetReduceLeadingSumArchDispatcher(priority RegisterPriority, fn ReduceLeadingSumArchFn)

SetReduceLeadingSumArchDispatcher registers an architecture-specific leading sum dispatcher with a priority. Dispatchers are tried in descending order of priority; if a higher-priority dispatcher returns false, the next one is tried.

func SetReduceTrailingSumArchDispatcher added in v0.1.10

func SetReduceTrailingSumArchDispatcher(priority RegisterPriority, fn ReduceTrailingSumArchFn)

SetReduceTrailingSumArchDispatcher registers an architecture-specific trailing sum dispatcher with a priority. Dispatchers are tried in descending order of priority; if a higher-priority dispatcher returns false, the next one is tried.

func SetSDPAArchDispatcher added in v0.1.11

func SetSDPAArchDispatcher(priority RegisterPriority, fn SDPAFloat32ArchFn)

SetSDPAArchDispatcher registers an architecture-specific SDPA dispatcher with a priority. Dispatchers are tried in descending order of priority; if a higher-priority dispatcher returns false, the next one is tried.

Types

type Backend

type Backend struct {
	Scheduler *scheduler.Scheduler

	NumLiveExecutions atomic.Int32

	// OpsExecutionType defines how to execute the ops of a computation.
	OpsExecutionType OpsExecutionType

	// SchedulingStrategy
	SchedulingStrategy ScheduleStrategy

	// NoOps disables the actual calculation in operations when true.
	NoOps bool

	// NumExecutors is the number of concurrent executor goroutines to launch in executeParallel.
	NumExecutors int
	// contains filtered or unexported fields
}

Backend implements the compute.Backend interface.

func NewBackend added in v0.1.10

func NewBackend() (*Backend, error)

NewBackend returns a "go" backend (*compute/internal/gobackend.Backend) for test. It returns an error if the backend is not a "go" backend.

func (*Backend) BufferFromFlatData

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

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

func (*Backend) Builder

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

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

func (*Backend) Capabilities

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

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

func (*Backend) CloneBuffer

func (b *Backend) CloneBuffer(buffer *Buffer) (*Buffer, error)

CloneBuffer using the pool to allocate a new one.

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

func (b *Backend) DeviceDescription(_ compute.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) GetBuffer

func (b *Backend) GetBuffer(shape shapes.Shape) (*Buffer, error)

GetBuffer with the corresponding shape from the backend pool of buffers if possible, or it allocates a new one.

It returns ErrBackendAlreadyFinalized if the backend is already finalized.

Important: it's not necessarily initialized with zero, since it can reuse old buffers.

See also Buffer.Zeros to initialize it with zeros, if needed.

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

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

func (b *Backend) NewSharedBuffer(deviceNum compute.DeviceNum, shape shapes.Shape) (buffer compute.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) PutBuffer

func (b *Backend) PutBuffer(buffer *Buffer)

PutBuffer back into the backend pool of buffers. After this any references to buffer should be dropped.

func (*Backend) String

func (b *Backend) String() string

String implement compute.Backend.

type BinaryTrailingArchFn added in v0.1.10

type BinaryTrailingArchFn func(op compute.OpType, isLHS bool, lhs, rhs, output *Buffer, A, B int, dtype dtypes.DType) bool

BinaryTrailingArchFn is a function hook to execute binary trailing broadcast (RHS or LHS) using architecture-specific kernels.

When isLHS is false (BroadcastTrailingRHS):

lhs is [A, B]
rhs is [A, 1] (flat slice length A)
output is [A, B]
output[a*B + b] = lhs[a*B + b] op rhs[a]

When isLHS is true (BroadcastTrailingLHS):

lhs is [A, 1] (flat slice length A)
rhs is [A, B]
output is [A, B]
output[a*B + b] = lhs[a] op rhs[a*B + b]

func GetBinaryTrailingArchDispatcher added in v0.1.10

func GetBinaryTrailingArchDispatcher() BinaryTrailingArchFn

GetBinaryTrailingArchDispatcher returns the registered architecture-specific binary trailing broadcast dispatcher, if any.

type BroadcastConfig added in v0.1.9

type BroadcastConfig struct {
	Pattern BroadcastPattern
	A, B, C int
	ZipIter *ZipIterator
}

BroadcastConfig contains pre-computed broadcast pattern metadata.

func DetermineBroadcastConfig added in v0.1.9

func DetermineBroadcastConfig(lhsShape, rhsShape, tgtShape shapes.Shape) BroadcastConfig

DetermineBroadcastConfig classifies the broadcast pattern between lhsShape and rhsShape to produce tgtShape.

func (*BroadcastConfig) EqualNodeData added in v0.1.9

func (c *BroadcastConfig) EqualNodeData(other NodeDataComparable) bool

EqualNodeData implements NodeDataComparable.

func (*BroadcastConfig) Recompute added in v0.1.9

func (c *BroadcastConfig) Recompute(backend *Backend, resolvedNodes []*Node, originalNode *Node) (any, error)

Recompute implements RecomputableNodeData.

type BroadcastIterator

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

BroadcastIterator allows iteration over the flat indices of the target shape of a broadcast (where some axis dimensions grow)

It is used by implicit broadcasting in binary ops and by the BroadcastInDim.

func NewBroadcastIterator

func NewBroadcastIterator(srcShape, tgtShape shapes.Shape) *BroadcastIterator

NewBroadcastIterator returns an iterator contructor over the flat indices of the target shape of a broadcast (where some axis dimensions grow).

Pre-requisite: srcShape.Rank() == tgtShape.Rank().

It is used by implicit broadcasting in binary ops and by the BroadcastInDim.

func (*BroadcastIterator) IterFlatIndices

func (bi *BroadcastIterator) IterFlatIndices() iter.Seq2[int, int]

IterFlatIndices iterate over the source and target flat indices for broadcast. Notice since we are broadcasting, the target index will always be incremented by 1, while the source index may repeat (when it is being broadcast).

type BroadcastPattern added in v0.1.9

type BroadcastPattern int8

BroadcastPattern represents the classified pattern of broadcasting between two operands.

const (
	// BroadcastNone indicates both operands have identical shapes (no broadcasting).
	BroadcastNone BroadcastPattern = iota

	// BroadcastScalarRHS indicates RHS has size 1 (scalar broadcast).
	BroadcastScalarRHS

	// BroadcastScalarLHS indicates LHS has size 1 (scalar broadcast).
	BroadcastScalarLHS

	// BroadcastLeadingRHS indicates RHS has leading 1s collapsed into [1, B] and LHS is [A, B].
	BroadcastLeadingRHS

	// BroadcastLeadingLHS indicates LHS has leading 1s collapsed into [1, B] and RHS is [A, B].
	BroadcastLeadingLHS

	// BroadcastTrailingRHS indicates RHS has trailing 1s collapsed into [A, 1] and LHS is [A, B].
	BroadcastTrailingRHS

	// BroadcastTrailingLHS indicates LHS has trailing 1s collapsed into [A, 1] and RHS is [A, B].
	BroadcastTrailingLHS

	// BroadcastRowCol indicates LHS is collapsed into [A, 1] and RHS into [1, B], producing [A, B].
	BroadcastRowCol

	// BroadcastColRow indicates LHS is collapsed into [1, B] and RHS into [A, 1], producing [A, B].
	BroadcastColRow

	// BroadcastMidRHS indicates LHS is collapsed into [A, B, C] and RHS into [A, 1, C], producing [A, B, C].
	BroadcastMidRHS

	// BroadcastMidLHS indicates LHS is collapsed into [A, 1, C] and RHS into [A, B, C], producing [A, B, C].
	BroadcastMidLHS

	// BroadcastOuterInnerRHS indicates LHS is collapsed into [A, B, C] and RHS into [1, B, 1], producing [A, B, C].
	BroadcastOuterInnerRHS

	// BroadcastOuterInnerLHS indicates LHS is collapsed into [1, B, 1] and RHS into [A, B, C], producing [A, B, C].
	BroadcastOuterInnerLHS

	// BroadcastGeneral indicates arbitrary multi-axis broadcasting.
	BroadcastGeneral
)

type Buffer

type Buffer struct {
	// RawBackend may be nil, for Buffers owning its own memory and not participating of the buffer pool.
	RawBackend *Backend

	// RawShape holds the concrete runtime shape of the buffer.
	// It is named RawShape because Buffer implements the compute.Buffer method Shape().
	// Internal Go backend kernels read RawShape directly (avoiding the Clone() and error return of Shape()),
	// and in-place operations (e.g., Reshape, Bitcast) update RawShape directly when reusing an owned input buffer.
	// When a buffer is finalized or returned to the pool, RawShape is reset to shapes.Invalid().
	RawShape shapes.Shape

	// ShapeDimensionsBuffer provides inline storage for dimensions up to rank 8,
	// avoiding heap allocation on shape cloning during buffer acquisition.
	ShapeDimensionsBuffer [8]int

	// InUse is set to false when the buffer is finalized and moved back to the pool.
	InUse bool

	// RawBytes is the underlying storage for the buffer.
	// Its length is always >= requested size in bytes.
	RawBytes []byte

	// Flat is always a slice of the underlying data type (shape.DType).
	// It is a re-casting of RawBytes.
	Flat any
	// contains filtered or unexported fields
}

Buffer for the Go 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 NewBuffer added in v0.1.20

func NewBuffer(shape shapes.Shape) *Buffer

NewBuffer creates a buffer with an exact-sized newly allocated flat space, not owned by the buffer pool.

func (*Buffer) Backend

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

Backend returns the backend that owns this buffer.

func (*Buffer) Check

func (buffer *Buffer) Check() error

Check does a sanity-check on the buffer. Returns a corresponding error if something is wrong.

Used only for debugging.

func (*Buffer) CopyToDevice

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

BufferCopyToDevice implements the compute.Backend interface. CopyToDevice implements the compute.Buffer interface.

func (*Buffer) Data

func (buffer *Buffer) Data() (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. Data returns a slice pointing to the buffer storage memory directly.

func (*Buffer) DeviceNum

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

BufferDeviceNum returns the deviceNum for the buffer. DeviceNum returns the deviceNum for the buffer.

func (*Buffer) EqualNodeData

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

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

func (buffer *Buffer) Finalize() error

Finalize 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. Finalize allows the client to inform the backend that the buffer is no longer needed and associated resources can be freed immediately.

func (*Buffer) MutableBytes

func (b *Buffer) MutableBytes() ([]byte, error)

MutableBytes returns the slice of the bytes used by the flat given -- it works with any of the supported data types for buffers.

func (*Buffer) Ones

func (b *Buffer) Ones() *Buffer

Ones fills the buffer with ones.

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

func (*Buffer) Shape

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

BufferShape returns the shape for the buffer. Shape returns the shape for the buffer.

func (*Buffer) ToFlatData

func (buffer *Buffer) ToFlatData(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 compute.Buffer shape.

See also FlatDataToBuffer, BufferShape, and shapes.Shape.Size. ToFlatData transfers the flat values of the buffer to the Go flat array.

func (*Buffer) UnsafePointer added in v0.1.10

func (b *Buffer) UnsafePointer() unsafe.Pointer

UnsafePointer returns an unsafe.Pointer to the underlying data of this buffer.

func (*Buffer) Zeros

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

	Backend    *Backend
	IsCompiled bool

	// MainFn is the main function of the computation.
	// Each function (including MainFn and closures) has its own nodes slice.
	MainFn *Function

	// Functions are all functions created within this builder, in order of creation.
	// It includes the main function.
	Functions []*Function
	// contains filtered or unexported fields
}

Builder keeps track of the computation graph being defined.

func (*Builder) Compile

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

Compile implements compute.Builder.

func (*Builder) DAGSort

func (b *Builder) DAGSort() error

DAGSort stably sorts the nodes in all functions topologically. It preserves the original creation order as much as possible.

func (*Builder) Finalize

func (b *Builder) Finalize()

Finalize immediately releases the resources associated with the Builder.

func (*Builder) Main

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

Main returns the main function of this computation.

func (*Builder) Name

func (b *Builder) Name() string

Name implements compute.Builder.

func (*Builder) NewFunction

func (b *Builder) NewFunction(name string) (compute.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 compute.Value) (shapes.Shape, error)

OpShape returns the shape of a computation Op.

func (*Builder) Optimize

func (b *Builder) Optimize() error

func (*Builder) String

func (b *Builder) String() string

String returns a multi-line string with the output of each function.

type ClosureInputs

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 ConstantCacheNodeData added in v0.1.20

type ConstantCacheNodeData interface {
	// CacheSignature returns a non-empty canonical string describing how inputIdx is transformed/cached,
	// or "" if inputIdx is not cached by this node.
	CacheSignature(inputIdx int) string

	// BindConstantData binds the shared ConstantData to inputIdx so the op reads/writes its cachedForm.
	BindConstantData(inputIdx int, cd *ConstantData)

	// IsInputCached reports whether inputIdx uses a cached form that has already been populated.
	IsInputCached(inputIdx int) bool
}

ConstantCacheNodeData is implemented by op Node.Data types in sub-packages (for example, DotGeneral and FusedDense caching pre-packed weight panels) that transform constant inputs into ConstantData.cachedForm on first execution and never read the raw constant input buffer again once cached.

type ConstantData added in v0.1.20

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

ConstantData holds the underlying buffer and any derived cached form for an OpTypeConstant node. A ConstantData instance can be shared across multiple Functions and Builders on the same Backend when Capabilities.SharedConstants is true.

Separating ConstantData from Buffer keeps Buffer a pure storage container without any knowledge of constant semantics or graph-level optimizations.

func NewAnonymousConstantData added in v0.1.20

func NewAnonymousConstantData() *ConstantData

NewAnonymousConstantData creates a ConstantData container without a single backing rawBuffer (isRawBufferPinned = true), used by ops like DotGeneral when an input is a composite constant expression.

func NewConstantData added in v0.1.20

func NewConstantData(backend *Backend, shape shapes.Shape, flat any) (*ConstantData, error)

NewConstantData creates a new ConstantData with an exact-sized, non-pooled buffer copied from flat.

func (*ConstantData) Backend added in v0.1.20

func (cd *ConstantData) Backend() *Backend

Backend returns the Backend that owns this ConstantData.

func (*ConstantData) Buffer added in v0.1.20

func (cd *ConstantData) Buffer() *Buffer

Buffer returns the raw Buffer, or nil if it has been released after caching a derived form.

func (*ConstantData) CachedForm added in v0.1.20

func (cd *ConstantData) CachedForm() any

CachedForm returns the shared derived cached representation, or nil if none has been set. It performs a lock-free atomic load.

func (*ConstantData) EqualNodeData added in v0.1.20

func (cd *ConstantData) EqualNodeData(other NodeDataComparable) bool

EqualNodeData implements NodeDataComparable for ConstantData.

func (*ConstantData) ForceCache added in v0.1.20

func (cd *ConstantData) ForceCache() bool

ForceCache reports whether populating cachedForm is forced on the first execution.

func (*ConstantData) Shape added in v0.1.20

func (cd *ConstantData) Shape() shapes.Shape

Shape returns the shape of this constant.

type DTypeMap

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

DTypeMap manages registering of an arbitrary value per dtype. See NewDTypeMap for more information, including how to auto-generation registration for various classes of dtypes (ints, uints, floats, half).

func NewDTypeMap

func NewDTypeMap(name string) *DTypeMap

NewDTypeMap creates a new DTypeMap.

To automatically create code to register Go-generic functions to handle those dtypes, you can use the generator in internal/cmd/gobackend_dtypemap and add annotations (comments) before the DTypeMap variable declaration, like the example:

//gobackend:dtypemap MyGeneric ints,uints,floats,half
var myDTypeMap = gobackend.NewDTypeMap("myDTypeMap")

This will automatically trigger the generation of registration calls in `gen_dtypemaps_registration.go` with content like:

myDTypeMap.Register(dtypes.Int8, gobackend.PriorityGeneric, MyGeneric[int8])
myDTypeMap.Register(dtypes.Int16, gobackend.PriorityGeneric, MyGeneric[int16])
myDTypeMap.Register(dtypes.Int32, gobackend.PriorityGeneric, MyGeneric[int32])
myDTypeMap.Register(dtypes.Int64, gobackend.PriorityGeneric, MyGeneric[int64])
myDTypeMap.Register(dtypes.Uint8, gobackend.PriorityGeneric, MyGeneric[uint8])
myDTypeMap.Register(dtypes.Uint16, gobackend.PriorityGeneric, MyGeneric[uint16])
myDTypeMap.Register(dtypes.Uint32, gobackend.PriorityGeneric, MyGeneric[uint32])
myDTypeMap.Register(dtypes.Uint64, gobackend.PriorityGeneric, MyGeneric[uint64])
myDTypeMap.Register(dtypes.Float32, gobackend.PriorityGeneric, MyGeneric[float32])
myDTypeMap.Register(dtypes.Float64, gobackend.PriorityGeneric, MyGeneric[float64])
myDTypeMap.Register(dtypes.BFloat16, gobackend.PriorityGeneric, MyGeneric[bfloat16.BFloat16])
myDTypeMap.Register(dtypes.Float16, gobackend.PriorityGeneric, MyGeneric[float16.Float16])

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.

Similar to NewDTypeMap, you can add annotations to generate code to register generic functions. Example:

//gobackend:dtypemap_pair callImplementationGeneric ints same
//gobackend:dtypemap_pair callImplementationGeneric ints int32,int64
//gobackend:dtypemap_pair callImplementationGeneric uints same
//gobackend:dtypemap_pair callImplementationGeneric uints uint32,uint64
//gobackend:dtypemap_pair callImplementationGeneric floats floats
//gobackend:dtypemap_pair callImplementationGeneric half float32
callImplementationDTypePairMap = gobackend.NewDTypePairMap("callImplementationGeneric")

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) EstimatedTemporaryMemory added in v0.1.13

func (e *Executable) EstimatedTemporaryMemory() int64

EstimatedTemporaryMemory estimates the memory used for the executable if executed sequentially. Returns int64(shapes.DynamicDim) (-1) if the computation has dynamic shapes.

func (*Executable) Execute

func (e *Executable) Execute(inputs []compute.Buffer, donate []bool, _ compute.DeviceNum) ([]compute.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 Function

type Function struct {
	notimplemented.Function

	RawBuilder *Builder

	// RawParent is the parent function if this is a closure.
	// For top-level functions (including main), this is nil.
	RawParent *Function

	// IsReturned indicates Return() was called.
	IsReturned bool

	// Nodes are all Nodes created within this function, in DAG order.
	// Each node's idx field is its index in this slice.
	Nodes []*Node

	// Outputs stores the return values set by Return().
	Outputs []*Node

	// Parameters stores the parameter nodes for this function.
	Parameters []*Node

	// CapturedParentNodes stores nodes from parent scopes that are captured by this closure.
	// The order matches capturedLocalNodes - CapturedParentNodes[i] is the parent node for capturedLocalNodes[i].
	CapturedParentNodes []*Node

	// CapturedLocalNodes stores the proxy nodes in this closure for captured values.
	// These are OpTypeCapturedValue nodes that receive their values at execution time.
	CapturedLocalNodes []*Node

	// compiled holds pre-compiled execution info.
	// This is set during Return() to allow efficient execution.
	Compiled *FunctionExecutable
	// contains filtered or unexported fields
}

Function implements compute.Function for the Go backend.

func (*Function) Abs

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

Stub methods that converts compute.Value to *Node and dispatches to the corresponding op handler.

func (*Function) Add

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

func (*Function) AllReduce

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

AllReduce implements the compute.CollectiveOps interface.

func (*Function) ArgMinMax

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

func (*Function) Atan2

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

func (*Function) BatchNormForInference

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

func (*Function) BatchNormForTraining

func (f *Function) BatchNormForTraining(operand compute.Value, scale compute.Value, offset compute.Value, epsilon float32, featureAxis int) (normalized compute.Value, batchMean compute.Value, batchVariance compute.Value, err error)

func (*Function) BatchNormGradient

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

func (*Function) BitCount

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

func (*Function) Bitcast

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

func (*Function) BitwiseAnd

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

func (*Function) BitwiseNot

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

func (*Function) BitwiseOr

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

func (*Function) BitwiseXor

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

func (*Function) BroadcastInDim

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

func (*Function) Builder

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

Builder returns the builder for this function.

func (*Function) Call

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

func (*Function) Ceil

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

func (*Function) CheckValid

func (f *Function) CheckValid() error

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

func (*Function) Clamp

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

func (*Function) Closure

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

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

func (*Function) Clz

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

func (*Function) Complex

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

func (*Function) Concatenate

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

func (*Function) Conj

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

func (*Function) Constant

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

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

func (*Function) ConvGeneral

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

func (*Function) ConvertDType

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

func (*Function) Cos

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

func (*Function) CumMax added in v0.1.19

func (f *Function) CumMax(operand compute.Value, axis int, options compute.CumSumOptions) (compute.Value, error)

func (*Function) CumSum added in v0.1.5

func (f *Function) CumSum(operand compute.Value, axis int, options compute.CumSumOptions) (compute.Value, error)

func (*Function) DAGSort

func (f *Function) DAGSort() error

DAGSort stably sorts the nodes in the function topologically.

func (*Function) Div

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

func (*Function) DotGeneral

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

func (*Function) DynamicBroadcastInDim added in v0.1.5

func (f *Function) DynamicBroadcastInDim(operand compute.Value, broadcastAxes []int, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)

func (*Function) DynamicDimensionSize

func (f *Function) DynamicDimensionSize(operand compute.Value, axis int) (compute.Value, error)

func (*Function) DynamicIota added in v0.1.5

func (f *Function) DynamicIota(dtype dtypes.DType, iotaAxis int, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)

func (*Function) DynamicPad added in v0.1.5

func (f *Function) DynamicPad(x compute.Value, fillValue compute.Value, axesConfig ...compute.DynamicPadAxis) (compute.Value, error)

func (*Function) DynamicReshape added in v0.1.1

func (f *Function) DynamicReshape(operand compute.Value, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)

func (*Function) DynamicShape

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

func (*Function) DynamicSlice

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

func (*Function) DynamicUpdateSlice

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

func (*Function) Equal

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

func (*Function) EqualTotalOrder

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

func (*Function) Erf

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

func (*Function) Exp

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

func (*Function) Expm1

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

func (*Function) FFT

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

func (*Function) Floor

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

func (*Function) FusedActivation added in v0.1.9

func (f *Function) FusedActivation(x compute.Value, cfg compute.ActivationConfig) (compute.Value, error)

func (*Function) FusedActivationVJP added in v0.1.9

func (f *Function) FusedActivationVJP(y compute.Value, x compute.Value, dOutput compute.Value, cfg compute.ActivationConfig) (compute.Value, error)

func (*Function) FusedAttentionQKVProjection

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

func (*Function) FusedDense

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

func (*Function) FusedDenseVJP added in v0.1.9

func (f *Function) FusedDenseVJP(x compute.Value, weight compute.Value, bias compute.Value, y compute.Value, dOutput compute.Value, options compute.DenseConfig) (dx compute.Value, dWeight compute.Value, dBias compute.Value, err error)

func (*Function) FusedLayerNorm

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

func (*Function) FusedQuantizedDense

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

func (*Function) FusedScaledDotProductAttention

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

func (*Function) FusedScaledDotProductAttentionVJP

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

func (*Function) FusedSoftmax

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

func (*Function) Gather

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

func (*Function) GetOrCreateCaptureNode

func (f *Function) GetOrCreateCaptureNode(parentNode *Node) *Node

GetOrCreateCaptureNode returns a capture node for the given parent node. If the parent node has already been captured, returns the existing capture node. Otherwise, creates a new capture node and adds it to the captured values list.

For nested closures (grandparent captures), this recursively propagates the capture through intermediate closures. For example, if closure C (child of B, child of A) wants to capture a value from A, this will: 1. Have B capture the value from A 2. Have C capture B's capture node

This ensures that when If/While/Sort ops are built, they can properly set up their capturedInputs by looking at the closure's capturedParentNodes.

func (*Function) GetOrCreateNode

func (f *Function) GetOrCreateNode(
	opType compute.OpType, shape shapes.Shape, inputs []*Node, data any) (
	n *Node, found bool)

GetOrCreateNode attempts to find a node with the content (opType, shape, inputs, data). If found, it returns the node. If not, it creates a new node with the filled fields, and returns found=false.

It also validates that all input nodes belong to this function or one of its ancestors. Using nodes from an ancestor function (closure capture) is not yet supported.

func (*Function) GreaterOrEqual

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

func (*Function) GreaterOrEqualTotalOrder

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

func (*Function) GreaterThan

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

func (*Function) GreaterThanTotalOrder

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

func (*Function) Identity

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

func (*Function) If

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

func (*Function) Imag

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

func (*Function) Iota

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

func (*Function) IsAncestorOf

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

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

func (*Function) IsNaN

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

func (*Function) KnownDynamicAxisNames

func (f *Function) KnownDynamicAxisNames() sets.Set[string]

KnownDynamicAxisNames returns the set of dynamically defined axis names known by the function.

func (*Function) LessOrEqual

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

func (*Function) LessOrEqualTotalOrder

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

func (*Function) LessThan

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

func (*Function) LessThanTotalOrder

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

func (*Function) Log

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

func (*Function) Log1p

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

func (*Function) LogicalAnd

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

func (*Function) LogicalNot

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

func (*Function) LogicalOr

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

func (*Function) LogicalXor

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

func (*Function) Logistic

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

func (*Function) Max

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

func (*Function) Min

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

func (*Function) Mul

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

func (*Function) Name

func (f *Function) Name() string

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

func (*Function) Neg

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

func (*Function) NewMultiOutputsNode

func (f *Function) NewMultiOutputsNode(
	opType compute.OpType,
	outputShapes []shapes.Shape,
	inputs ...*Node,
) (node *Node)

NewMultiOutputsNode creates the multi-outputs node, and its "select nodes", one per output. The node.multiOutputsNodes will be set with the individual outputs and can be used by the Builder to return to the user. Nodes are added to the function's nodes slice.

Note: no de-duplication of multi-output nodes.

func (*Function) NewNode

func (f *Function) NewNode(opType compute.OpType, shape shapes.Shape, inputs ...*Node) *Node

NewNode adds a new node of the given opType and shape to the function's graph. It's used by the other ops when creating new nodes. Nodes are added to the function's nodes slice.

Use getOrCreateNode instead for most operations.

func (*Function) NotEqual

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

func (*Function) NotEqualTotalOrder

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

func (*Function) OptimizationBarrier

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

func (*Function) Pad

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

func (*Function) Parameter

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

Parameter creates an input parameter for this function.

func (*Function) Parent

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

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

func (*Function) Pow

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

func (*Function) QuantizedEmbeddingLookup

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

func (*Function) RNGBitGenerator

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

func (*Function) Real

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

func (*Function) ReduceBitwiseAnd

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

func (*Function) ReduceBitwiseOr

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

func (*Function) ReduceBitwiseXor

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

func (*Function) ReduceLogicalAnd

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

func (*Function) ReduceLogicalOr

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

func (*Function) ReduceLogicalXor

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

func (*Function) ReduceMax

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

func (*Function) ReduceMin

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

func (*Function) ReduceProduct

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

func (*Function) ReduceSum

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

func (*Function) ReduceWindow

func (f *Function) ReduceWindow(input compute.Value, reductionType compute.ReduceOpType, windowDimensions []int, strides []int, inputDilations []int, windowDilations []int, paddings [][2]int) (compute.Value, error)

func (*Function) Rem

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

func (*Function) Reshape

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

func (*Function) Return

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

Return marks the outputs of this function.

func (*Function) Reverse

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

func (*Function) Round

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

func (*Function) Rsqrt

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

func (*Function) ScatterMax

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

func (*Function) ScatterMin

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

func (*Function) ScatterSum

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

func (*Function) SchedulingBarrier

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

func (*Function) SelectAndScatterMax

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

func (*Function) SelectAndScatterMin

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

func (*Function) Shape

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

Shape returns the shape of a value in the function.

func (*Function) ShiftLeft

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

func (*Function) ShiftRightArithmetic

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

func (*Function) ShiftRightLogical

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

func (*Function) Sign

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

func (*Function) Sin

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

func (*Function) Slice

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

func (*Function) Sort

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

func (*Function) Sqrt

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

func (*Function) String

func (f *Function) String() string

String returns a multi-line string with one line per node.

func (*Function) Sub

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

func (*Function) Tanh

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

func (*Function) Transpose

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

func (*Function) ValidateClosure

func (f *Function) ValidateClosure(opName, closureName string, closure compute.Function) (*Function, error)

ValidateClosure validates that a compute.Function is a compiled closure of the current function.

func (*Function) VerifyAndCastValues

func (f *Function) VerifyAndCastValues(name string, values ...compute.Value) ([]*Node, error)

VerifyAndCastValues sanity checks that the values (compute.Op) are valid and created with this builder. If a node belongs to a parent function, it creates a capture node to access the value. It returns the underlying *Node of the values (with capture nodes substituted for parent values).

func (*Function) Where

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

func (*Function) While

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

type FunctionExecutable

type FunctionExecutable struct {
	Backend *Backend
	Builder *Builder

	// Function is the source Function this was compiled from.
	Function *Function

	// NumNodesToProcess is the max(outputs.idx)+1.
	// Arrays are sized to this to allow direct idx indexing.
	NumNodesToProcess int

	// Schedule represents the order in which nodes should be executed.
	// This should be optimized to minimize the latency/temporary memory.
	Schedule []int

	// NumUses tracks how many times each node's result is used (indexed by idx).
	NumUses []int

	// Dependents maps each node (by idx) to the list of dependent node idxs.
	Dependents [][]int

	// OutputNodes are the nodes that produce the function's outputs.
	OutputNodes []*Node

	// MaxInputs is the maximum number of inputs any node has.
	MaxInputs int

	// ExecutionBuffersPool allows reuse of execution buffers.
	ExecutionBuffersPool sync.Pool
	// 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) CreationOrderSchedule

func (fe *FunctionExecutable) CreationOrderSchedule()

CreationOrderSchedule schedule nodes in creation order: a trivial sequentially increasing order.

func (*FunctionExecutable) DependencyOrderSchedule

func (fe *FunctionExecutable) DependencyOrderSchedule()

DependencyOrderSchedule schedules nodes in topological order, based on dependencies.

It schedules those with the longest path to an output first. If there are multiple nodes with the same longest path to an output, it will schedule them in creation order.

func (*FunctionExecutable) EstimatedTemporaryMemory

func (fe *FunctionExecutable) EstimatedTemporaryMemory() int64

EstimatedTemporaryMemory estimates the memory used for the function if executed sequentially. Returns int64(shapes.DynamicDim) (-1) if any parameter or node in the function has dynamic dimensions, since dynamic models cannot have their memory statically estimated at compile time.

It assumes temporary memory is used for every node output (using Shape.ByteSize()), and released everytime one node output is no longer needed (its output has been used fe.NumUses[nodeIdx] times). It does not actually execute the nodes, just simulates the execution to report back the maximum temporary memory live at any time.

func (*FunctionExecutable) Execute

func (fe *FunctionExecutable) Execute(backend *Backend, inputs []*Buffer, donate []bool, capturedInputs []*Buffer,
	donateCaptures []bool, spec *ShapeSpecialization) ([]*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. spec is the shape specialization for the current execution, or nil for static graphs.

func (*FunctionExecutable) InitSchedule

func (fe *FunctionExecutable) InitSchedule()

InitSchedule initializes the execution schedule.

type GraphTransformation

type GraphTransformation interface {
	// Apply takes the current graph state and returns an optimized version.
	//
	// It should return dagModified=true, if new nodes were create out-of-order (at the end) and hence the DAG
	// order would have been broken, requiring a re-sort after the pass.
	Apply(builder *Builder) (dagModified bool, err error)
	Name() string
}

GraphTransformation is an optimizer of the graph, to be executed during compilation.

type LayerNormTrailingArchFn added in v0.1.10

type LayerNormTrailingArchFn func(
	inPtr, outPtr, gammaPtr, betaPtr unsafe.Pointer,
	outerSize, normSize int,
	epsilon float64,
	dtype dtypes.DType,
) bool

LayerNormTrailingArchFn is a function hook to execute LayerNorm on trailing contiguous axes using architecture-specific kernels (e.g., AVX2, AVX-512, NEON).

Parameters:

  • inPtr, outPtr: unsafe.Pointer to flat input/output data
  • gammaPtr, betaPtr: optional unsafe.Pointer to 1D scale/bias parameter buffers (may be nil)
  • outerSize: number of outer rows to normalize
  • normSize: number of elements along normalization axis per row
  • epsilon: numerical stability epsilon
  • dtype: element data type (e.g. Float32, Float64)

func GetLayerNormTrailingArchDispatcher added in v0.1.10

func GetLayerNormTrailingArchDispatcher() LayerNormTrailingArchFn

GetLayerNormTrailingArchDispatcher returns the registered architecture-specific LayerNorm dispatcher, if any.

type Node

type Node struct {
	// Index is the index of this node in its function's nodes slice.
	Index  int
	Inputs []*Node

	// CapturedInputs holds nodes from parent scopes that are used by closures
	// called by this node (for ops like If, While, Sort that use closures).
	// Each inner slice corresponds to one closure's captured values.
	// These are treated as additional inputs for dependency tracking and lifetime management.
	CapturedInputs [][]*Node

	// shape of the output.
	OpType  compute.OpType
	Shape   shapes.Shape
	Builder *Builder

	// Function is the Function in which this node was created.
	// This is used to detect cross-Function node usage.
	Function *Function

	// MultiOutputsShapes are set for a few specialized nodes.
	// For most nodes this is set to nil.
	MultiOutputsShapes []shapes.Shape
	MultiOutputsNodes  []*Node
	IsNodeSelectOutput bool
	SelectOutputIdx    int

	// Data for the specific node type.
	Data any
	// contains filtered or unexported fields
}

Node in the Go backend computation graph.

func (*Node) AddNodeCapturedInputs

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) ClearCachedExecutor added in v0.1.10

func (node *Node) ClearCachedExecutor()

ClearCachedExecutor clears any cached executor on the node, forcing rediscovery on next run.

func (*Node) Finalize added in v0.1.20

func (node *Node) Finalize()

Finalize releases the resources associated with the Node, including its Data if it implements WithFinalize.

func (*Node) IsConstant added in v0.1.13

func (node *Node) IsConstant() bool

IsConstant returns true if this node and all of its ancestors are constants (i.e. not dependent on input parameters or any non-deterministic / random operator).

func (*Node) IsExecutorCached added in v0.1.10

func (node *Node) IsExecutorCached() bool

IsExecutorCached returns true if an executor was already selected and cached for this node.

func (*Node) IsMultiOutputs

func (n *Node) IsMultiOutputs() bool

IsMultiOutputs returns whether this node yields multiple outputs.

func (*Node) MultiOutputValues

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

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

type NodeDataComparable

type NodeDataComparable interface {
	// EqualNodeData returns true if this data is semantically equivalent to other.
	// The other parameter is guaranteed to be the same concrete type.
	EqualNodeData(other NodeDataComparable) bool
}

NodeDataComparable is implemented by node data types that support de-duplication. Implementing this interface allows the Builder to automatically de-duplicate nodes with matching inputs and equivalent data.

type NodeDedupKey

type NodeDedupKey struct {
	OpType     compute.OpType
	InputCount int
	FirstInput *Node // nil if there are no inputs.
}

NodeDedupKey is used to index into the de-duplication map. It provides fast lookup for candidate nodes with the same operation type and input structure.

func MakeNodeDedupKey

func MakeNodeDedupKey(opType compute.OpType, inputs []*Node) NodeDedupKey

MakeNodeDedupKey creates a de-duplication key for a node with the given opType and inputs.

type NodeExecutor

type NodeExecutor func(backend *Backend, node *Node, inputs []*Buffer, inputsOwned []bool) (*Buffer, error)

NodeExecutor defines the signature of a node execution function.

node is the node being executed. inputs are the input buffers to the node. If the node owns the input buffer (inputsOwned[i] is true), the executor may donate/reuse the buffer for the output, and MUST set inputs[i] to nil to signal ownership transfer.

If the executor does not implement the operation for the given input combination (e.g. unsupported DType or broadcast pattern), it should return ErrNotImplemented without modifying inputs or inputsOwned, allowing the backend to fall back to the next registered executor.

type NodeParameter

type NodeParameter struct {
	Name     string
	InputIdx int
}

NodeParameter data.

func (*NodeParameter) EqualNodeData

func (n *NodeParameter) EqualNodeData(other NodeDataComparable) bool

EqualNodeData implements nodeDataComparable for nodeParameter.

type OpHandlerRegistration

type OpHandlerRegistration[FN any] struct {
	Method   string
	Priority RegisterPriority
	Fn       FN
}

OpHandlerRegistration is a generic registration handler type for Function methods.

FN represents the function type, which should take as first parameter always the Function. Example for the op "Max(lhs, rhs Value) (Value, error)", FN would take the form "func(f *Function, lhs, rhs *Node) (*Node, error)".

func (*OpHandlerRegistration[FN]) Register

func (handler *OpHandlerRegistration[FN]) Register(fn FN, priority RegisterPriority)

Register registers a handler with the given priority. It will only override the op if the given priority is higher than the current one.

type OpsExecutionType

type OpsExecutionType int
const (
	OpsExecutionDynamic OpsExecutionType = iota
	OpsExecutionParallel
	OpsExecutionSequential
)

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 RecomputableNodeData

type RecomputableNodeData interface {
	// Recompute shape-dependent metadata from the resolved input shapes.
	// Returns a new Data object (or the same one if it's mutable and updated in-place).
	Recompute(backend *Backend, resolvedNodes []*Node, originalNode *Node) (any, error)
}

RecomputableNodeData is an interface that can be implemented by the Data field of a Node to allow recomputing shape-dependent metadata when specializing a dynamic graph.

type ReduceLeadingSumArchFn added in v0.1.10

type ReduceLeadingSumArchFn func(operand, output *Buffer, A, B int, dtype dtypes.DType) bool

ReduceLeadingSumArchFn is a function hook to execute leading sum reduction using architecture-specific kernels.

func GetReduceLeadingSumArchDispatcher added in v0.1.10

func GetReduceLeadingSumArchDispatcher() ReduceLeadingSumArchFn

GetReduceLeadingSumArchDispatcher returns the registered architecture-specific leading sum dispatcher, if any.

type ReduceTrailingSumArchFn added in v0.1.10

type ReduceTrailingSumArchFn func(operand, output *Buffer, A, B int, dtype dtypes.DType) bool

ReduceTrailingSumArchFn is a function hook to execute trailing sum reduction using architecture-specific kernels.

func GetReduceTrailingSumArchDispatcher added in v0.1.10

func GetReduceTrailingSumArchDispatcher() ReduceTrailingSumArchFn

GetReduceTrailingSumArchDispatcher returns the registered architecture-specific trailing sum dispatcher, if any.

type RegisterPriority

type RegisterPriority int

RegisterPriority defines the priority of a node executor. Highest priority takes precedence. Anything with priority < 0 is ignored.

const (
	PriorityGeneric RegisterPriority = 0
	PriorityTyped   RegisterPriority = 1                // Specialized typed implementation.
	PrioritySIMD    RegisterPriority = 6                // Portable Go simd/archsimd package implementation.
	PriorityArch    RegisterPriority = 10               // Specialized baseline architecture implementation.
	PriorityNEON    RegisterPriority = PriorityArch     // ARM64 AdvSIMD / NEON (128-bit, 32 registers).
	PriorityAVX2    RegisterPriority = PriorityArch     // AMD64 AVX2 (256-bit, 16 registers).
	PriorityAVX512  RegisterPriority = PriorityArch + 1 // AMD64 AVX-512 (512-bit, 32 registers).
	PrioritySVE     RegisterPriority = PriorityArch + 1 // ARM64 SVE / SVE2.
	PrioritySME     RegisterPriority = PriorityArch + 2 // ARM64 SME / SME2.
	PriorityUser    RegisterPriority = 100              // Custom user overrides.
)

type SDPAFloat32ArchFn added in v0.1.11

type SDPAFloat32ArchFn func(
	q, k, v, output []float32,
	qOff, kvOff, qSeqStride, kvSeqStride, qGroupStride int,
	additiveMask []float32,
	booleanMask []bool,
	maskGroupStride int,
	additiveBias []float32,
	biasGroupStride int,
	scoresScratch []float32,
	groupSize, qStart, qEnd, kvLen, headDim int,
	scale float32, causal bool,
	qLimit, kvLimit int,
) bool

SDPAFloat32ArchFn is a function hook to execute Scaled Dot-Product Attention for float32 using architecture-specific kernels (e.g. AVX2, AVX-512, NEON). It processes one KV-head group (with groupSize query heads) over query range [qStart, qEnd) with zero transpositions.

func GetSDPAArchDispatcher added in v0.1.11

func GetSDPAArchDispatcher() SDPAFloat32ArchFn

GetSDPAArchDispatcher returns the registered architecture-specific SDPA dispatcher, if any.

type ScheduleStrategy

type ScheduleStrategy int

ScheduleStrategy defines the scheduling strategy to execute functions.

const (
	DependencyOrderSchedule ScheduleStrategy = iota
	CreationOrderSchedule
)

func ScheduleStrategyString

func ScheduleStrategyString(s string) (ScheduleStrategy, error)

ScheduleStrategyString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func ScheduleStrategyValues

func ScheduleStrategyValues() []ScheduleStrategy

ScheduleStrategyValues returns all values of the enum

func (ScheduleStrategy) IsAScheduleStrategy

func (i ScheduleStrategy) IsAScheduleStrategy() bool

IsAScheduleStrategy returns "true" if the value is listed in the enum definition. "false" otherwise

func (ScheduleStrategy) String

func (i ScheduleStrategy) String() string

type ShapeSpecialization

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

ShapeSpecialization holds a resolved-shape copy of the graph nodes for a specific set of axis bindings. Each specialization is created lazily on first execution with a given binding and cached for reuse.

The resolvedNodes are shallow copies of the original Function.nodes. Only the shape field (and multiOutputsShapes for multi-output nodes) is resolved; all other fields (inputs, capturedInputs, opType, etc.) are shared with the originals. This allows executor functions to read node.Shape and get concrete values without any signature changes.

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 the Go backend.

type WithFinalize added in v0.1.20

type WithFinalize interface {
	Finalize()
}

WithFinalize is implemented by Node.Data types that hold resources requiring cleanup when the Node is finalized.

type ZipIterator

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

ZipIterator allows iteration over the flat indices of the target shape of a broadcast (where some axis dimensions grow) for two input shapes (LHS and RHS).

It implements the implicit broadcasting for binary ops like Add, Sub, Mul, Div, etc.

func NewZippedBroadcastIterator

func NewZippedBroadcastIterator(lhsShape, rhsShape, tgtShape shapes.Shape) *ZipIterator

NewZippedBroadcastIterator returns an iterator constructor over the flat indices of the target shape of a broadcast (where some axis dimensions grow) for two input shapes (LHS and RHS).

Pre-requisite: lhsShape.Rank() == tgtShape.Rank() && rhsShape.Rank() == tgtShape.Rank().

It implements the implicit broadcasting for binary ops like Add, Sub, Mul, Div, etc.

func (*ZipIterator) EqualNodeData

func (z *ZipIterator) EqualNodeData(other NodeDataComparable) bool

EqualNodeData implements NodeDataComparable, so this can be used as NodeData -- the comparison is used for deduping repeated nodes during model building.

func (*ZipIterator) IterFlatIndices

func (zi *ZipIterator) IterFlatIndices() iter.Seq[ZippedIndices]

IterFlatIndices iterate over the lhs, rhs and target flat indices for broadcast. Notice since we are broadcasting, the target index will always be incremented by 1, while the source indices may repeat (when it is being broadcast).

type ZippedIndices

type ZippedIndices struct {
	LHSFlatIdx, RHSFlatIdx int
	TgtFlatIdx             int
}

ZippedIndices of two BroadcastIterators.

Directories

Path Synopsis
avx2
Package avx2 provides AVX2 SIMD implementations for activations.
Package avx2 provides AVX2 SIMD implementations for activations.
avx512
Package avx512 provides AVX-512 SIMD implementations for activations.
Package avx512 provides AVX-512 SIMD implementations for activations.
Package defaultpkgs imports all the sub-packages that implement the gobackend.
Package defaultpkgs imports all the sub-packages that implement the gobackend.
dot
Package dot implements a general-purpose "dot product" ("Einsum") computation.
Package dot implements a general-purpose "dot product" ("Einsum") computation.
matmul
package matmul provides the base implementations of matrx multiply for DotGeneral.
package matmul provides the base implementations of matrx multiply for DotGeneral.
matmul/avx2
Package avx2 provides AVX2 accelerated matrix multiplication kernels.
Package avx2 provides AVX2 accelerated matrix multiplication kernels.
matmul/avx512
Package avx512 provides AVX-512 accelerated matrix multiplication kernels.
Package avx512 provides AVX-512 accelerated matrix multiplication kernels.
matmul/matmultest
Package matmultest provides test helpers for verifying matrix multiplication packing and output routines.
Package matmultest provides test helpers for verifying matrix multiplication packing and output routines.
matmul/neon
Package neon implements ARM64 NEON accelerated matrix multiplication (DotGeneral) kernels for the Go backend.
Package neon implements ARM64 NEON accelerated matrix multiplication (DotGeneral) kernels for the Go backend.
avx2
Package avx2 provides AVX2 SIMD implementations for fused operations.
Package avx2 provides AVX2 SIMD implementations for fused operations.
avx512
Package avx512 provides AVX2 SIMD implementations for fused operations.
Package avx512 provides AVX2 SIMD implementations for fused operations.
ops
Package ops has the base implementation for most operations for the Go backend.
Package ops has the base implementation for most operations for the Go backend.
avx2
Package avx2 provides AVX2 SIMD implementations for normal operations.
Package avx2 provides AVX2 SIMD implementations for normal operations.
avx512
Package avx512 provides AVX2 SIMD implementations for normal operations.
Package avx512 provides AVX2 SIMD implementations for normal operations.
neon
Package neon provides ARM64 AdvSIMD (NEON) accelerated kernels for standard operations.
Package neon provides ARM64 AdvSIMD (NEON) accelerated kernels for standard operations.
Package scheduler implements the runtime execution scheduler for the Go compute backend.
Package scheduler implements the runtime execution scheduler for the Go compute backend.

Jump to

Keyboard shortcuts

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