Documentation
¶
Overview ¶
Package guda configuration constants
Package guda provides a CUDA-compatible API for CPU execution with high performance.
GUDA has fully assimilated the Gonum numerical computing libraries as its native compute engine, providing optimized BLAS operations, linear algebra, and scientific computing capabilities specifically tuned for machine learning workloads.
The integrated compute engine includes:
- Optimized BLAS implementations with AVX2/FMA support
- Float32-first design for ML/AI applications
- Fused operations for common neural network patterns
- SIMD-accelerated Float16/BFloat16 operations
This assimilation preserves the full optimization history from Gonum while adapting it for modern machine learning requirements.
Package guda structured error types for better error handling ¶
Package guda provides a CUDA-compatible API for CPU execution. It enables running CUDA applications on CPU-only infrastructure through aggressive SIMD optimization and native CPU implementations.
Example usage:
ctx := guda.NewContext()
defer ctx.Destroy()
// Allocate device memory
d_a, _ := ctx.Malloc(n * 4) // n float32s
d_b, _ := ctx.Malloc(n * 4)
// Copy data to device
ctx.Memcpy(d_a, h_a, n*4, guda.MemcpyHostToDevice)
ctx.Memcpy(d_b, h_b, n*4, guda.MemcpyHostToDevice)
// Launch kernel
grid := guda.Dim3{X: (n + guda.DefaultBlockSize - 1) / guda.DefaultBlockSize}
block := guda.Dim3{X: guda.DefaultBlockSize}
ctx.LaunchKernel(myKernel, grid, block, args...)
Package guda performance counter integration for detailed performance analysis ¶
Package guda provides Linux-specific performance counter implementation ¶
Package guda reference implementations for verification ¶
Package guda tolerance-based verification for floating-point comparisons
Index ¶
- Constants
- Variables
- func AXPY(alpha float32, x, y DevicePtr, n int) error
- func AbsFloat32(x float32) float32
- func Add(a, b, c DevicePtr, n int) error
- func AddBFloat16(a, b, c DevicePtr, n int) error
- func AddBiasGELU(x, bias DevicePtr, n int) error
- func AddBiasReLU(x, bias DevicePtr, n int) error
- func AddFloat16(a, b, c DevicePtr, n int) error
- func AddFloat16SIMD(a, b, c DevicePtr, n int) error
- func AlmostEqual(a, b, tolerance float32) bool
- func BatchedGEMMFloat16SIMD(batch int, transA, transB bool, m, n, k int, alpha float32, aArray []DevicePtr, ...) error
- func BenchmarkWithCounters(b *testing.B, name string, fn func())
- func CacheObliviousGEMM_Float32(transA, transB bool, m, n, k int, alpha float32, a []float32, lda int, ...)
- func Conv2D(input, kernel, bias, output DevicePtr, params *ConvParams) error
- func Conv2DDirect(input, kernel, bias, output DevicePtr, params *ConvParams) error
- func Conv2DFloat16SIMD(input DevicePtr, inputH, inputW, inputC int, kernel DevicePtr, ...) error
- func CumSum(x, out DevicePtr, n int) error
- func DOT(x, y DevicePtr, n int) (float32, error)
- func ErfFloat32(x float32) float32
- func ExpFloat32(x float32) float32
- func FMAFloat16SIMD(a, b, c, d DevicePtr, n int) error
- func Float32NearEqual(a, b float32, tol ToleranceConfig) bool
- func Float32ULPDiff(a, b float32) int
- func ForEach(data DevicePtr, size int, fn func(idx int, val *float32)) error
- func Free(ptr DevicePtr) error
- func FusedGEMMBiasGELU(transA, transB bool, m, n, k int, alpha float32, a DevicePtr, lda int, ...) error
- func FusedGEMMBiasReLU(transA, transB bool, m, n, k int, alpha float32, a DevicePtr, lda int, ...) error
- func GELU(x DevicePtr, n int) error
- func GEMM(transA, transB bool, m, n, k int, alpha float32, a DevicePtr, lda int, ...) error
- func GEMMBFloat16(transA, transB bool, m, n, k int, alpha float32, a DevicePtr, lda int, ...) error
- func GEMMFloat16(transA, transB bool, m, n, k int, alpha float32, a DevicePtr, lda int, ...) error
- func GEMMFloat16SIMD(transA, transB bool, m, n, k int, alpha float32, a DevicePtr, lda int, ...) error
- func GeluFloat32Accurate(x float32) float32
- func GenerateCPUReference() error
- func GenerateDiagonalMatrix(diagonal []float32) []float32
- func GenerateFloat32(size int, seed uint64) []float32
- func GenerateFloat32EdgeCases() []float32
- func GenerateFloat32Range(size int, seed uint64, min, max float32) []float32
- func GenerateIdentityMatrix(size int) []float32
- func GenerateMatrixFloat32(rows, cols int, seed uint64) []float32
- func GenerateSequence(size int, start, step float32) []float32
- func GenerateTestVectorInstructions()
- func GetBestGemmImplementation() string
- func GetCPUInfo() string
- func GetDeviceCount() int
- func GetLatestLogFile() (string, error)
- func HasAVX2() bool
- func HasAVX512() bool
- func InitBenchmarkLogger(sessionName string) error
- func InitFFUDetection() error
- func IntegratePerfCounters(b interface{}, name string, fn func())
- func IsARM64() bool
- func IsDeviceError(err error) bool
- func IsExecutionError(err error) bool
- func IsInvalidArgError(err error) bool
- func IsMemoryError(err error) bool
- func IsNotImplementedError(err error) bool
- func IsNumericalError(err error) bool
- func Launch(kernel Kernel, grid, block Dim3, args ...interface{}) error
- func LaunchFunc(fn KernelFunc, grid, block Dim3, args ...interface{}) error
- func LaunchOrFail(t testing.TB, kernel KernelFunc, grid, block Dim3, args ...interface{})
- func LayerNorm(x DevicePtr, gamma, beta DevicePtr, n int, eps float32) error
- func LayerNormFloat16SIMD(input, gamma, beta, output DevicePtr, n, hidden int) error
- func LinearFloat16(x DevicePtr, alpha, beta float32, n int) error
- func LinearReLU(x DevicePtr, alpha, beta float32, n int) error
- func LoadTestVector(filename string) ([]float32, error)
- func LogBenchmarkFail(name string, err error)
- func LogBenchmarkPass(name string, nsPerOp float64, mbPerSec float64, ops int64)
- func LogBenchmarkResult(result BenchmarkResult)
- func LogBenchmarkTimeout(name string, duration time.Duration)
- func LogSumExp(x DevicePtr, n int) float32
- func Map(input, output DevicePtr, size int, fn func(float32) float32) error
- func Max(x DevicePtr, n int) (float32, error)
- func Memcpy(dst, src interface{}, size int, kind MemcpyKind) error
- func MemcpyOrFail(t testing.TB, dst DevicePtr, src interface{}, size int, direction MemcpyKind)
- func Min(x DevicePtr, n int) (float32, error)
- func MixedPrecisionLinear(x, weights, bias, output DevicePtr, batchSize, inputDim, outputDim int) error
- func Multiply(a, b, c DevicePtr, n int) error
- func MultiplyFloat16(a, b, c DevicePtr, n int) error
- func MultiplyFloat16SIMD(a, b, c DevicePtr, n int) error
- func NewExecutionError(op string, message string, err error) error
- func NewInvalidArgError(op string, message string) error
- func NewMemoryError(op string, message string, err error) error
- func NewNumericalError(op string, message string, context interface{}) error
- func OptimizedGEMM_Float32(transA, transB bool, m, n, k int, alpha float32, a []float32, lda int, ...)
- func PrefetchFloat32(data []float32, index int)
- func PrefetchFloat32Write(data []float32, index int)
- func PrefetchGEMM(a, b, c []float32, currentBlockA, currentBlockB, currentBlockC int, ...)
- func PrintBenchmarkSummary() error
- func ReLU(x DevicePtr, n int) error
- func Reduce(data DevicePtr, size int, op func(a, b float32) float32) (float32, error)
- func ReduceMax(x DevicePtr, shape []int, axis int, out DevicePtr) error
- func ReduceSum(x DevicePtr, shape []int, axis int, out DevicePtr) error
- func Scale(alpha float32, x DevicePtr, n int) error
- func SegmentSum(data DevicePtr, segmentIds []int, nSegments int, out DevicePtr) error
- func SetDevice(id int) error
- func Sigmoid(x DevicePtr, n int) error
- func SigmoidFloat32(x float32) float32
- func SimdF16ToF32(src []uint16, dst []float32)
- func SimdF32ToF16(src []float32, dst []uint16)
- func SlicesAlmostEqual(a, b []float32, tolerance float32) bool
- func Softmax(x DevicePtr, n int) error
- func StreamingGEMM_Float32(transA, transB bool, m, n, k int, alpha float32, a []float32, lda int, ...)
- func StreamingPrefetch(data []float32, currentIdx int)
- func StreamingPrefetchDual(x, y []float32, currentIdx int)
- func Sum(x DevicePtr, n int) (float32, error)
- func Synchronize() error
- func SynchronizeOrFail(t testing.TB)
- func TanhFloat32(x float32) float32
- func TestDataSizes() []int
- func TestMatrixSizes() [][3]int
- func TestWithCUDAVectors(t *testing.T)
- func TiledPrefetch(data []float32, tileStartIdx, tileSize int)
- func TopK(x DevicePtr, n, k int) (values []float32, indices []int, err error)
- func ULPDiffFloat32(a, b float32) int32
- func Version() (version, sum string)
- type ArchToleranceConfig
- type BFloat16
- type BFloat16Slice
- type BatchResult
- type BatchVerifier
- type BenchmarkLogger
- type BenchmarkResult
- type CPUFeatures
- type CacheObliviousGEMM
- type CacheObliviousGEMMParallel
- type Context
- func (ctx *Context) CreateStream() *Stream
- func (ctx *Context) Free(ptr DevicePtr) error
- func (ctx *Context) Launch(kernel Kernel, grid, block Dim3, args ...interface{}) error
- func (ctx *Context) LaunchFunc(fn KernelFunc, grid, block Dim3, args ...interface{}) error
- func (ctx *Context) LaunchFuncStream(fn KernelFunc, grid, block Dim3, stream *Stream, args ...interface{}) error
- func (ctx *Context) LaunchStream(kernel Kernel, grid, block Dim3, stream *Stream, args ...interface{}) error
- func (ctx *Context) Malloc(size int) (DevicePtr, error)
- func (ctx *Context) Memcpy(dst, src interface{}, size int, kind MemcpyKind) error
- func (ctx *Context) Synchronize() error
- type ConvParams
- type Device
- type DevicePtr
- func (d DevicePtr) ArgMax(n int) int
- func (d DevicePtr) ArgMin(n int) int
- func (d DevicePtr) BFloat16() BFloat16Slice
- func (d DevicePtr) Byte() []byte
- func (d DevicePtr) Float16() Float16Slice
- func (d DevicePtr) Float32() []float32
- func (d DevicePtr) Float64() []float64
- func (d DevicePtr) Int32() []int32
- func (d DevicePtr) Max(n int) float32
- func (d DevicePtr) Mean(n int) float32
- func (d DevicePtr) Min(n int) float32
- func (d DevicePtr) Offset(bytes int) DevicePtr
- func (d DevicePtr) Product(n int) float32
- func (d DevicePtr) Size() int
- func (d DevicePtr) Sum(n int) float32
- func (d DevicePtr) SumSquares(n int) float32
- func (d DevicePtr) Variance(n int) float32
- type Dim3
- type ErrorType
- type FFUCapability
- type FFUDetector
- type FFUType
- type Float16
- type Float16Slice
- type FusedKernel
- func (fk *FusedKernel) Add(alpha float32) *FusedKernel
- func (fk *FusedKernel) AddBroadcast(alpha float32, broadcastDim int) *FusedKernel
- func (fk *FusedKernel) AddScalar(alpha float32) *FusedKernel
- func (fk *FusedKernel) Custom(fn func(float32) float32) *FusedKernel
- func (fk *FusedKernel) Execute(x DevicePtr, others []DevicePtr, n int, shapes ...[]int) error
- func (fk *FusedKernel) MulScalar(alpha float32) *FusedKernel
- func (fk *FusedKernel) Multiply() *FusedKernel
- func (fk *FusedKernel) ReLU() *FusedKernel
- type FusedOp
- type FusedOpType
- type FusedTransformerLayer
- type GUDAError
- type Kernel
- type KernelFunc
- type KernelVerifier
- type LinuxPerfMonitor
- type MathConfig
- type MathOp
- type MemcpyKind
- type MemoryPool
- type NumericalParity
- type OperationTolerance
- type OptimizedGEMM
- type PerfCounters
- type PerfMonitor
- type Reference
- func (r Reference) ASUM(x []float32) float32
- func (r Reference) AXPY(alpha float32, x, y []float32)
- func (r Reference) Add(a, b, c []float32)
- func (r Reference) AddBiasReLU(x, bias []float32, n, biasLen int)
- func (r Reference) ArgMax(x []float32) int
- func (r Reference) ArgMin(x []float32) int
- func (r Reference) Conv2D(input []float32, batch, inC, inH, inW int, kernel []float32, ...)
- func (r Reference) DOT(x, y []float32) float32
- func (r Reference) Div(a, b, c []float32)
- func (r Reference) GELU(x []float32)
- func (r Reference) GEMM(transA, transB bool, m, n, k int, alpha float32, a []float32, lda int, ...)
- func (r Reference) GEMMBiasReLU(m, n, k int, alpha float32, a []float32, lda int, b []float32, ldb int, ...)
- func (r Reference) GEMV(transA bool, m, n int, alpha float32, a []float32, lda int, x []float32, ...)
- func (r Reference) LayerNorm(x []float32, gamma, beta []float32, eps float32)
- func (r Reference) LinearReLU(x []float32, alpha, beta float32)
- func (r Reference) Max(x []float32) float32
- func (r Reference) Min(x []float32) float32
- func (r Reference) Mul(a, b, c []float32)
- func (r Reference) NRM2(x []float32) float32
- func (r Reference) ReLU(x []float32)
- func (r Reference) Scale(alpha float32, x []float32)
- func (r Reference) Sigmoid(x []float32)
- func (r Reference) Softmax(x []float32)
- func (r Reference) Sub(a, b, c []float32)
- func (r Reference) Sum(x []float32) float32
- func (r Reference) Tanh(x []float32)
- type Stream
- type StreamingGEMM
- type Tensor
- type TestCase
- type TestResult
- type TestVector
- type ThreadID
- type ToleranceConfig
- type VerificationResult
- type WorkerPool
Constants ¶
const ( // L1 cache size per core (typical for modern CPUs) L1CacheSize = 32 * 1024 // 32KB // L2 cache size per core (typical for modern CPUs) L2CacheSize = 256 * 1024 // 256KB // L3 cache size (shared, typical for modern CPUs) L3CacheSize = 8 * 1024 * 1024 // 8MB )
Cache sizes for different levels (in bytes)
const ( // AVX2 vector width in float32 elements AVX2VectorSize = 8 // AVX512 vector width in float32 elements AVX512VectorSize = 16 // Default SIMD alignment in bytes SIMDAlignment = 64 )
SIMD vector sizes
const ( // Default block size for kernels DefaultBlockSize = 256 // Maximum threads per block (CUDA compatibility) MaxThreadsPerBlock = 1024 // Default grid size multiplier DefaultGridMultiplier = 4 )
Thread and block dimensions
const ( // Minimum allocation size to prevent fragmentation MinAllocationSize = 64 // Memory alignment for allocations MemoryAlignment = 64 // Free list size threshold for reuse FreeListThreshold = 100 )
Memory pool parameters
const ( // Tile size for matrix operations (optimized for L1 cache) MatrixTileSize = 64 // Prefetch distance in cache lines PrefetchDistance = 8 // Unroll factor for loops LoopUnrollFactor = 4 // Generic tiling size for blocked algorithms DefaultTileSize = 64 )
Performance tuning parameters
const ( // im2col workspace multiplier Im2colWorkspaceMultiplier = 2 // Minimum size for using im2col (below this, use direct convolution) Im2colThreshold = 16 )
Convolution parameters
const ( // Machine epsilon for float32 Float32Epsilon = 1.192092896e-07 // Maximum ULP difference for float32 comparisons MaxULPDiff = 4 )
Numerical constants
const ( // Micro-kernel dimensions for AVX2 (8x8 blocks) GEMMMicroKernelM = 8 GEMMMicroKernelN = 8 // Float16 GEMM tile sizes (optimized for F16C+AVX2) Float16TileM = 6 // 6x16 register blocking Float16TileN = 16 // Process 16 columns at once Float16TileK = 8 // Process 8 K elements with F16C )
GEMM micro-kernel parameters
const ( // Layer normalization default epsilon value // Standard value used in most neural network frameworks DefaultLayerNormEpsilon = 1e-5 // Activation function saturation limits DefaultActivationSaturation = 10.0 // Test tolerance levels for different precision requirements TestToleranceStrict = 1e-6 // For critical accuracy tests TestToleranceNormal = 1e-5 // For standard tests TestToleranceRelaxed = 1e-4 // For approximate methods // Mathematical constants with high precision MathE = 2.7182818284590452354 // e MathPi = 3.1415926535897932385 // π MathSqrt2 = 1.4142135623730950488 // √2 MathLn2 = 0.6931471805599453094 // ln(2) MathLn10 = 2.3025850929940456840 // ln(10) MathLog2E = 1.4426950408889634074 // log₂(e) MathLog10E = 0.4342944819032518277 // log₁₀(e) // Reciprocal constants for efficiency MathInvSqrt2 = 0.7071067811865475244 // 1/√2 MathInvSqrtPi = 0.5641895835477562869 // 1/√π MathInvSqrt2Pi = 0.3989422804014326780 // 1/√(2π) // GELU activation constants from Hendrycks & Gimpel paper // GELU(x) = 0.5 * x * (1 + tanh(√(2/π) * (x + 0.044715 * x³))) GELUSqrt2OverPi = 0.7978845608028653559 // √(2/π) GELUCoefficient = 0.044715 // β coefficient // Error function approximation constants (Abramowitz & Stegun) // erf(x) ≈ 1 - exp(-x²) * polynomial(x) ErfA1 = 0.254829592 // a₁ ErfA2 = -0.284496736 // a₂ ErfA3 = 1.421413741 // a₃ ErfA4 = -1.453152027 // a₄ ErfA5 = 1.061405429 // a₅ ErfP = 0.3275911 // p )
Mathematical constants and configuration for GUDA computations
const ( // Exact operations (add, multiply scalars) ToleranceExact = 0 // High precision (GEMM, convolution) ToleranceHigh = 1e-6 // Medium precision (reductions) ToleranceMedium = 1e-5 // Low precision (transcendentals, approximations) ToleranceLow = 1e-4 // ULP tolerances ULPExact = 0 ULPHigh = 2 ULPMedium = 10 ULPLow = 100 )
Tolerance levels for different operations
const ( PERF_TYPE_HARDWARE = 0 PERF_TYPE_SOFTWARE = 1 PERF_TYPE_TRACEPOINT = 2 PERF_TYPE_HW_CACHE = 3 PERF_TYPE_RAW = 4 )
Performance counter types
const ( PERF_COUNT_HW_CPU_CYCLES = 0 PERF_COUNT_HW_INSTRUCTIONS = 1 PERF_COUNT_HW_CACHE_REFERENCES = 2 PERF_COUNT_HW_CACHE_MISSES = 3 PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 4 PERF_COUNT_HW_BRANCH_MISSES = 5 PERF_COUNT_HW_BUS_CYCLES = 6 PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 7 PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 8 PERF_COUNT_HW_REF_CPU_CYCLES = 9 )
Hardware performance counter events
const ( PERF_COUNT_HW_CACHE_L1D = 0 PERF_COUNT_HW_CACHE_L1I = 1 PERF_COUNT_HW_CACHE_LL = 2 // Last Level Cache (L3) PERF_COUNT_HW_CACHE_DTLB = 3 PERF_COUNT_HW_CACHE_ITLB = 4 PERF_COUNT_HW_CACHE_BPU = 5 PERF_COUNT_HW_CACHE_NODE = 6 )
Cache levels and operations for cache events
const ( PERF_COUNT_HW_CACHE_OP_READ = 0 PERF_COUNT_HW_CACHE_OP_WRITE = 1 PERF_COUNT_HW_CACHE_OP_PREFETCH = 2 )
const ( PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0 PERF_COUNT_HW_CACHE_RESULT_MISS = 1 )
const ( PERF_FLAG_FD_NO_GROUP = 1 << 0 PERF_FLAG_FD_OUTPUT = 1 << 1 PERF_FLAG_PID_CGROUP = 1 << 2 )
Flags for perf_event_open
const ( // PrefetchRead - Prefetch for read access PrefetchRead prefetchMode = iota // PrefetchWrite - Prefetch for write access PrefetchWrite )
Variables ¶
var ( // Memory errors ErrOutOfMemory = NewMemoryError("Malloc", "out of memory", nil) ErrInvalidSize = NewInvalidArgError("Malloc", "size must be positive") ErrNullPointer = NewInvalidArgError("Memory", "null pointer") ErrDoubleFree = NewMemoryError("Free", "double free detected", nil) // Device errors ErrInvalidDevice = NewInvalidArgError("SetDevice", "invalid device ID") ErrNoDevice = &GUDAError{Type: ErrTypeDevice, Op: "Device", Message: "no compute device available"} // Execution errors ErrStreamClosed = NewExecutionError("Stream", "stream is closed", nil) ErrKernelFailed = NewExecutionError("Kernel", "kernel execution failed", nil) // Numerical errors ErrNaN = NewNumericalError("Compute", "NaN detected in computation", nil) ErrInf = NewNumericalError("Compute", "Inf detected in computation", nil) ErrOverflow = NewNumericalError("Compute", "numerical overflow", nil) ErrUnderflow = NewNumericalError("Compute", "numerical underflow", nil) )
var ( ErrNotSupported = &GUDAError{Type: ErrTypeNotImplemented, Op: "FusedOp", Message: "operation not supported"} ErrInvalidShape = NewInvalidArgError("FusedOp", "invalid shape") ErrInvalidAxis = NewInvalidArgError("FusedOp", "invalid axis") ErrInvalidIndex = NewInvalidArgError("FusedOp", "invalid index") ErrInvalidParameter = NewInvalidArgError("FusedOp", "invalid parameter") )
var ConvArchTolerance = ArchToleranceConfig{ Base: ToleranceConfig{ AbsTol: 1e-6, RelTol: 1e-5, ULPTol: 8, CheckNaN: true, CheckInf: true, }, ARM64: &ToleranceConfig{ AbsTol: 1e-5, RelTol: 1e-4, ULPTol: 32, }, }
ConvArchTolerance provides architecture-aware tolerances for convolution operations
var GEMMArchTolerance = ArchToleranceConfig{ Base: ToleranceConfig{ AbsTol: 1e-6, RelTol: 1e-5, ULPTol: 4, CheckNaN: true, CheckInf: true, }, ARM64: &ToleranceConfig{ AbsTol: 1e-5, RelTol: 1e-4, ULPTol: 16, }, Generic: &ToleranceConfig{ AbsTol: 1e-4, RelTol: 1e-3, ULPTol: 32, }, }
GEMMArchTolerance provides architecture-aware tolerances for GEMM operations
var ReduceArchTolerance = ArchToleranceConfig{ Base: ToleranceConfig{ AbsTol: 1e-5, RelTol: 1e-4, ULPTol: 16, CheckNaN: true, CheckInf: true, }, ARM64: &ToleranceConfig{ AbsTol: 1e-4, RelTol: 1e-3, ULPTol: 64, }, }
ReduceArchTolerance provides architecture-aware tolerances for reduction operations
var StandardTolerances = map[string]OperationTolerance{ "add": {Name: "add", AbsTol: 0, RelTol: 0, ULPTol: ULPExact}, "multiply": {Name: "multiply", AbsTol: 0, RelTol: 0, ULPTol: ULPExact}, "gemm": {Name: "gemm", AbsTol: ToleranceHigh, RelTol: ToleranceHigh, ULPTol: ULPHigh}, "conv2d": {Name: "conv2d", AbsTol: ToleranceHigh, RelTol: ToleranceHigh, ULPTol: ULPHigh}, "reduce_sum": {Name: "reduce_sum", AbsTol: ToleranceMedium, RelTol: ToleranceMedium, ULPTol: ULPMedium}, "softmax": {Name: "softmax", AbsTol: ToleranceMedium, RelTol: ToleranceMedium, ULPTol: ULPMedium}, "gelu": {Name: "gelu", AbsTol: ToleranceLow, RelTol: ToleranceLow, ULPTol: ULPLow}, "exp": {Name: "exp", AbsTol: ToleranceLow, RelTol: ToleranceLow, ULPTol: ULPLow}, }
Standard tolerances for different operations
Functions ¶
func AXPY ¶
AXPY performs the BLAS Level 1 operation: y = alpha*x + y. This function adds a scaled vector x to vector y.
Parameters:
- alpha: Scalar multiplier for x
- x: Input vector (DevicePtr to float32 data)
- y: Input/output vector (DevicePtr to float32 data)
- n: Number of elements in vectors
The operation is performed in-place on vector y. Uses optimized SIMD operations for maximum performance.
Example:
d_x, _ := guda.Malloc(1024 * 4) d_y, _ := guda.Malloc(1024 * 4) err := guda.AXPY(2.0, d_x, d_y, 1024) // y = 2.0*x + y
func AddBFloat16 ¶
AddBFloat16 performs element-wise addition on BFloat16 arrays
func AddBiasGELU ¶
AddBiasGELU performs x = GELU(x + bias) in one pass GELU(x) = x * Φ(x) where Φ is CDF of standard normal We use the tanh approximation: 0.5 * x * (1 + tanh(sqrt(2/π) * (x + 0.044715 * x^3)))
func AddBiasReLU ¶
AddBiasReLU performs x = ReLU(x + bias) in one pass For neural networks: x is [batch_size, output_dim], bias is [output_dim]
func AddFloat16 ¶
AddFloat16 performs element-wise addition on Float16 arrays
func AddFloat16SIMD ¶
AddFloat16SIMD uses AVX2+F16C for float16 vector addition
func AlmostEqual ¶
AlmostEqual checks if two float32 values are approximately equal within the specified tolerance. Handles special cases like NaN and Inf.
func BatchedGEMMFloat16SIMD ¶
func BatchedGEMMFloat16SIMD( batch int, transA, transB bool, m, n, k int, alpha float32, aArray []DevicePtr, ldaArray []int, bArray []DevicePtr, ldbArray []int, beta float32, cArray []DevicePtr, ldcArray []int) error
BatchedGEMMFloat16SIMD performs multiple GEMMs in parallel Common in transformer models
func BenchmarkWithCounters ¶
BenchmarkWithCounters runs a benchmark with performance counter collection
func CacheObliviousGEMM_Float32 ¶
func CacheObliviousGEMM_Float32(transA, transB bool, m, n, k int, alpha float32, a []float32, lda int, b []float32, ldb int, beta float32, c []float32, ldc int)
Integration with GUDA's GEMM
func Conv2D ¶
func Conv2D(input, kernel, bias, output DevicePtr, params *ConvParams) error
Conv2D performs 2D convolution: output = conv(input, kernel) + bias Input shape: [batch, in_channels, height, width] Kernel shape: [out_channels, in_channels, kernel_height, kernel_width] Output shape: [batch, out_channels, out_height, out_width]
func Conv2DDirect ¶
func Conv2DDirect(input, kernel, bias, output DevicePtr, params *ConvParams) error
Conv2DDirect performs direct convolution without im2col transformation This is more memory efficient for small kernels
func Conv2DFloat16SIMD ¶
func Conv2DFloat16SIMD( input DevicePtr, inputH, inputW, inputC int, kernel DevicePtr, kernelH, kernelW int, output DevicePtr, outputH, outputW, outputC int, strideH, strideW int, padH, padW int) error
Conv2DFloat16SIMD performs 2D convolution with float16
func DOT ¶
DOT computes the dot product of two vectors: result = sum(x[i] * y[i]). This is a BLAS Level 1 operation.
Parameters:
- x: First input vector (DevicePtr to float32 data)
- y: Second input vector (DevicePtr to float32 data)
- n: Number of elements in vectors
Returns the dot product as float32. Uses optimized SIMD operations for maximum performance.
Example:
d_x, _ := guda.Malloc(1024 * 4) d_y, _ := guda.Malloc(1024 * 4) result, err := guda.DOT(d_x, d_y, 1024)
func ErfFloat32 ¶
ErfFloat32 computes the error function with good accuracy Uses rational approximation from Abramowitz & Stegun
func ExpFloat32 ¶
ExpFloat32 computes exp(x) with good accuracy for float32 Uses range reduction and polynomial approximation
func FMAFloat16SIMD ¶
FMAFloat16SIMD performs d = a*b + c using AVX2+F16C+FMA
func Float32NearEqual ¶
func Float32NearEqual(a, b float32, tol ToleranceConfig) bool
Float32NearEqual checks if two float32 values are equal within tolerance
func Float32ULPDiff ¶
Float32ULPDiff computes the difference in ULPs between two float32 values
func ForEach ¶
ForEach applies a function to each element in parallel. This is a convenience function for element-wise operations.
Parameters:
- data: DevicePtr to the data array
- size: Number of elements to process
- fn: Function to apply to each element (receives index and pointer)
Example:
d_data, _ := guda.Malloc(1024 * 4)
guda.ForEach(d_data, 1024, func(idx int, val *float32) {
*val = float32(idx) * 2.0
})
func Free ¶
Free releases device memory allocated by Malloc. It is safe to call Free with a zero-value DevicePtr.
Example:
d_data, _ := guda.Malloc(1024 * 4) defer guda.Free(d_data)
func FusedGEMMBiasGELU ¶
func FusedGEMMBiasGELU( transA, transB bool, m, n, k int, alpha float32, a DevicePtr, lda int, b DevicePtr, ldb int, beta float32, c DevicePtr, ldc int, bias DevicePtr, ) error
FusedGEMMBiasGELU performs C = GELU(alpha*A*B + bias) in a fused operation
func FusedGEMMBiasReLU ¶
func FusedGEMMBiasReLU( transA, transB bool, m, n, k int, alpha float32, a DevicePtr, lda int, b DevicePtr, ldb int, beta float32, c DevicePtr, ldc int, bias DevicePtr, ) error
FusedGEMMBiasReLU performs C = ReLU(alpha*A*B + beta*C + bias) in a single pass This is our memory wall breakthrough - keeping everything in cache!
func GEMM ¶
func GEMM(transA, transB bool, m, n, k int, alpha float32, a DevicePtr, lda int, b DevicePtr, ldb int, beta float32, c DevicePtr, ldc int) error
GEMM performs the general matrix-matrix multiplication: C = alpha*op(A)*op(B) + beta*C. This is a BLAS Level 3 operation and the workhorse of linear algebra.
Parameters:
- transA: If true, use A^T; if false, use A
- transB: If true, use B^T; if false, use B
- m: Number of rows in op(A) and C
- n: Number of columns in op(B) and C
- k: Number of columns in op(A) and rows in op(B)
- alpha: Scalar multiplier for A*B
- a: Matrix A (DevicePtr to float32 data)
- lda: Leading dimension of A
- b: Matrix B (DevicePtr to float32 data)
- ldb: Leading dimension of B
- beta: Scalar multiplier for C
- c: Matrix C (DevicePtr to float32 data, input/output)
- ldc: Leading dimension of C
Uses highly optimized CPU BLAS with SIMD operations.
Example:
d_A, _ := guda.Malloc(m * k * 4) d_B, _ := guda.Malloc(k * n * 4) d_C, _ := guda.Malloc(m * n * 4) err := guda.GEMM(false, false, m, n, k, 1.0, d_A, k, d_B, n, 0.0, d_C, n)
func GEMMBFloat16 ¶
func GEMMBFloat16(transA, transB bool, m, n, k int, alpha float32, a DevicePtr, lda int, b DevicePtr, ldb int, beta float32, c DevicePtr, ldc int) error
GEMMBFloat16 performs matrix multiplication with BFloat16 This is what modern AI accelerators use
func GEMMFloat16 ¶
func GEMMFloat16(transA, transB bool, m, n, k int, alpha float32, a DevicePtr, lda int, b DevicePtr, ldb int, beta float32, c DevicePtr, ldc int) error
GEMMFloat16 performs matrix multiplication with Float16
func GEMMFloat16SIMD ¶
func GEMMFloat16SIMD(transA, transB bool, m, n, k int, alpha float32, a DevicePtr, lda int, b DevicePtr, ldb int, beta float32, c DevicePtr, ldc int) error
GEMMFloat16SIMD performs optimized float16 matrix multiplication using F16C
func GeluFloat32Accurate ¶
GeluFloat32Accurate computes GELU with high accuracy Uses error function (erf) for best results
func GenerateCPUReference ¶
func GenerateCPUReference() error
GenerateCPUReference creates reference test vectors using CPU computation
func GenerateDiagonalMatrix ¶
GenerateDiagonalMatrix generates a diagonal matrix with specified diagonal values. All non-diagonal elements are 0.0.
func GenerateFloat32 ¶
GenerateFloat32 generates deterministic float32 test data using a linear congruential generator (LCG). This ensures reproducible tests across runs.
Parameters:
- size: Number of elements to generate
- seed: Random seed for reproducibility
Example:
data := GenerateFloat32(1024, 12345)
func GenerateFloat32EdgeCases ¶
func GenerateFloat32EdgeCases() []float32
GenerateFloat32EdgeCases generates test data with edge cases for floating point. Includes zero, denormals, infinity, NaN, and extreme values. Useful for testing numerical stability and special case handling.
func GenerateFloat32Range ¶
GenerateFloat32Range generates deterministic float32 data in a specific range.
Parameters:
- size: Number of elements
- seed: Random seed
- min: Minimum value (inclusive)
- max: Maximum value (exclusive)
Example:
data := GenerateFloat32Range(1024, 42, -1.0, 1.0) // Generate values in [-1, 1)
func GenerateIdentityMatrix ¶
GenerateIdentityMatrix generates an identity matrix of the specified size. Diagonal elements are 1.0, all others are 0.0.
func GenerateMatrixFloat32 ¶
GenerateMatrixFloat32 generates a deterministic matrix in row-major order.
Parameters:
- rows: Number of rows
- cols: Number of columns
- seed: Random seed
Example:
A := GenerateMatrixFloat32(128, 256, 12345) // 128x256 matrix
func GenerateSequence ¶
GenerateSequence generates a simple arithmetic sequence for debugging. Useful when you need predictable patterns.
Example:
data := GenerateSequence(10, 0, 2) // [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
func GenerateTestVectorInstructions ¶
func GenerateTestVectorInstructions()
GenerateTestVectorInstructions prints instructions for generating test vectors
func GetBestGemmImplementation ¶
func GetBestGemmImplementation() string
GetBestGemmImplementation returns the optimal GEMM implementation for the CPU
func GetCPUInfo ¶
func GetCPUInfo() string
GetCPUInfo returns a string describing available CPU features
func GetDeviceCount ¶
func GetDeviceCount() int
GetDeviceCount returns the number of available devices. GUDA always returns 1 as it only supports CPU execution.
Example:
count := guda.GetDeviceCount()
fmt.Printf("Available devices: %d\n", count)
func GetLatestLogFile ¶
GetLatestLogFile returns the path to the most recent log file
func HasAVX512 ¶
func HasAVX512() bool
HasAVX512 returns true if the CPU supports AVX-512 operations needed for GEMM
func InitBenchmarkLogger ¶
InitBenchmarkLogger initializes the logger for a new benchmark session
func InitFFUDetection ¶
func InitFFUDetection() error
InitFFUDetection initializes the global FFU detector
func IntegratePerfCounters ¶
func IntegratePerfCounters(b interface{}, name string, fn func())
IntegratePerfCounters enhances benchmarks with hardware counter collection
func IsDeviceError ¶
IsDeviceError checks if an error is a device error
func IsExecutionError ¶
IsExecutionError checks if an error is an execution error
func IsInvalidArgError ¶
IsInvalidArgError checks if an error is an invalid argument error
func IsMemoryError ¶
IsMemoryError checks if an error is a memory error
func IsNotImplementedError ¶
IsNotImplementedError checks if an error is a not implemented error
func IsNumericalError ¶
IsNumericalError checks if an error is a numerical error
func Launch ¶
Launch executes a kernel on the default stream. The kernel is executed across a grid of thread blocks.
Parameters:
- kernel: The kernel to execute
- grid: Grid dimensions (number of blocks)
- block: Block dimensions (threads per block)
- args: Kernel arguments
Example:
kernel := MyKernel{}
err := guda.Launch(kernel, guda.Dim3{X: 256, Y: 1, Z: 1}, guda.Dim3{X: 64, Y: 1, Z: 1})
func LaunchFunc ¶
func LaunchFunc(fn KernelFunc, grid, block Dim3, args ...interface{}) error
LaunchFunc executes a kernel function
func LaunchOrFail ¶
func LaunchOrFail(t testing.TB, kernel KernelFunc, grid, block Dim3, args ...interface{})
LaunchOrFail launches a kernel and fails the test if unsuccessful
func LayerNormFloat16SIMD ¶
LayerNormFloat16SIMD performs layer normalization with float16
func LinearFloat16 ¶
LinearFloat16 performs y = alpha*x + beta with Float16
func LinearReLU ¶
LinearReLU performs x = ReLU(alpha*x + beta) in one pass
func LoadTestVector ¶
LoadTestVector loads a binary test vector file
func LogBenchmarkFail ¶
LogBenchmarkFail logs a failed benchmark
func LogBenchmarkPass ¶
LogBenchmarkPass logs a successful benchmark
func LogBenchmarkResult ¶
func LogBenchmarkResult(result BenchmarkResult)
LogBenchmarkResult logs a single benchmark result
func LogBenchmarkTimeout ¶
LogBenchmarkTimeout logs a timed out benchmark
func LogSumExp ¶
LogSumExp computes log(sum(exp(x))) in a numerically stable way This is a key operation in many ML algorithms
func Map ¶
Map applies a transformation function to create a new array. Each element of the input is transformed and stored in the output.
Parameters:
- input: Source data array
- output: Destination data array
- size: Number of elements to process
- fn: Transformation function
Example:
d_input, _ := guda.Malloc(1024 * 4)
d_output, _ := guda.Malloc(1024 * 4)
guda.Map(d_input, d_output, 1024, func(x float32) float32 {
return x * x // Square each element
})
func Memcpy ¶
func Memcpy(dst, src interface{}, size int, kind MemcpyKind) error
Memcpy copies memory between host and device. In GUDA's unified memory model, this may be a no-op or simple copy. Supports various Go slice types ([]float32, []float64, []int32, etc.).
Parameters:
- dst: Destination (DevicePtr or Go slice)
- src: Source (DevicePtr or Go slice)
- size: Number of bytes to copy
- kind: Transfer direction (MemcpyHostToDevice, MemcpyDeviceToHost, etc.)
Example:
hostData := make([]float32, 1024) d_data, _ := guda.Malloc(1024 * 4) err := guda.Memcpy(d_data, hostData, 1024*4, guda.MemcpyHostToDevice)
func MemcpyOrFail ¶
func MemcpyOrFail(t testing.TB, dst DevicePtr, src interface{}, size int, direction MemcpyKind)
MemcpyOrFail copies data and fails the test if unsuccessful
func MixedPrecisionLinear ¶
func MixedPrecisionLinear(x, weights, bias, output DevicePtr, batchSize, inputDim, outputDim int) error
MixedPrecisionLinear performs FP32 accumulation with BF16 storage This is the key to modern AI training efficiency
func MultiplyFloat16 ¶
MultiplyFloat16 performs element-wise multiplication on Float16 arrays
func MultiplyFloat16SIMD ¶
MultiplyFloat16SIMD uses AVX2+F16C for float16 vector multiplication
func NewExecutionError ¶
NewExecutionError creates an execution error
func NewInvalidArgError ¶
NewInvalidArgError creates an invalid argument error
func NewMemoryError ¶
NewMemoryError creates a memory-related error
func NewNumericalError ¶
NewNumericalError creates a numerical error
func OptimizedGEMM_Float32 ¶
func OptimizedGEMM_Float32(transA, transB bool, m, n, k int, alpha float32, a []float32, lda int, b []float32, ldb int, beta float32, c []float32, ldc int)
OptimizedGEMM_Float32 provides a convenient interface that directly leverages our best kernels
func PrefetchFloat32 ¶
PrefetchFloat32 provides a hint to prefetch float32 data
func PrefetchFloat32Write ¶
PrefetchFloat32Write provides a hint to prefetch float32 data for writing
func PrefetchGEMM ¶
func PrefetchGEMM(a, b, c []float32, currentBlockA, currentBlockB, currentBlockC int, blockSize int)
PrefetchGEMM prefetches data for matrix multiplication Prefetches next blocks of A, B, and C matrices
func PrintBenchmarkSummary ¶
func PrintBenchmarkSummary() error
PrintBenchmarkSummary prints a summary of the latest benchmark session
func Reduce ¶
Reduce performs a parallel reduction operation on the data. It combines all elements using the provided binary operation.
Parameters:
- data: Input data array
- size: Number of elements
- op: Binary operation (e.g., addition, maximum)
Returns the final reduced value.
Example:
d_data, _ := guda.Malloc(1024 * 4)
sum, _ := guda.Reduce(d_data, 1024, func(a, b float32) float32 {
return a + b // Sum all elements
})
func ReduceSum ¶
ReduceSum performs a sum reduction along the specified axis For 2D tensors: axis=0 sums columns, axis=1 sums rows
func SegmentSum ¶
SegmentSum computes the sum of segments defined by segment_ids Essential for graph neural networks and attention mechanisms
func SigmoidFloat32 ¶
SigmoidFloat32 computes sigmoid(x) = 1 / (1 + exp(-x)) with good accuracy Uses a rational approximation for the range [-5, 5] and clips outside
func SimdF16ToF32 ¶
SimdF16ToF32 converts float16 to float32 using F16C instructions
func SimdF32ToF16 ¶
SimdF32ToF16 converts float32 to float16 using F16C instructions
func SlicesAlmostEqual ¶
SlicesAlmostEqual checks if two float32 slices are approximately equal element-wise within the specified tolerance.
func Softmax ¶
Softmax computes the softmax function: exp(x) / sum(exp(x)) Essential for attention mechanisms and classification
func StreamingGEMM_Float32 ¶
func StreamingGEMM_Float32(transA, transB bool, m, n, k int, alpha float32, a []float32, lda int, b []float32, ldb int, beta float32, c []float32, ldc int)
StreamingGEMM_Float32 provides a convenient interface
func StreamingPrefetch ¶
StreamingPrefetch implements software prefetching for streaming patterns This is optimized for sequential access like AXPY, DOT operations
func StreamingPrefetchDual ¶
StreamingPrefetchDual prefetches from two arrays simultaneously Useful for operations like DOT, AXPY that read two arrays
func Synchronize ¶
func Synchronize() error
Synchronize waits for all operations on all streams to complete. This ensures all previously launched kernels and memory operations have finished.
Example:
guda.Launch(kernel, grid, block) err := guda.Synchronize() // Wait for kernel to complete
func SynchronizeOrFail ¶
SynchronizeOrFail synchronizes and fails the test if unsuccessful
func TanhFloat32 ¶
TanhFloat32 computes tanh(x) with good accuracy Uses exp formula for best accuracy across all ranges
func TestDataSizes ¶
func TestDataSizes() []int
TestDataSizes returns common test sizes for benchmarking cache effects. Includes sizes that fit in L1, L2, L3, and main memory.
func TestMatrixSizes ¶
func TestMatrixSizes() [][3]int
TestMatrixSizes returns common matrix sizes for GEMM testing. Includes square and rectangular matrices of various sizes.
func TestWithCUDAVectors ¶
TestWithCUDAVectors runs GUDA against CUDA/ROCm reference vectors
func TiledPrefetch ¶
TiledPrefetch implements prefetching for blocked algorithms Used in GEMM and other tiled operations
func TopK ¶
TopK finds the k largest elements and their indices Returns values and indices in descending order
func ULPDiffFloat32 ¶
ULPDiffFloat32 computes the ULP (Units in Last Place) difference
func Version ¶
func Version() (version, sum string)
Version returns the version of GUDA and its checksum. The returned values are only valid in binaries built with module support.
This function also reports the integrated compute engine (formerly Gonum) version information to maintain attribution and history.
The exact version format returned by Version may change in future.
Types ¶
type ArchToleranceConfig ¶
type ArchToleranceConfig struct {
// Base tolerance for all architectures
Base ToleranceConfig
// Architecture-specific overrides
AMD64 *ToleranceConfig
ARM64 *ToleranceConfig
Generic *ToleranceConfig
}
ArchToleranceConfig provides architecture-specific tolerance configurations
type BFloat16 ¶
type BFloat16 uint16
BFloat16 represents a 16-bit brain floating point number Format: 1 sign bit, 8 exponent bits, 7 mantissa bits
func ToBFloat16 ¶
ToBFloat16 converts float32 to BFloat16 (truncate mantissa)
type BFloat16Slice ¶
type BFloat16Slice struct {
// contains filtered or unexported fields
}
BFloat16Slice wraps a byte slice as BFloat16 values
func NewBFloat16Slice ¶
func NewBFloat16Slice(data []byte) BFloat16Slice
NewBFloat16Slice creates a BFloat16 slice from a byte slice
func (BFloat16Slice) Get ¶
func (s BFloat16Slice) Get(i int) BFloat16
Get returns the BFloat16 at index i
func (BFloat16Slice) GetFloat32 ¶
func (s BFloat16Slice) GetFloat32(i int) float32
GetFloat32 returns the value at index i as float32
func (BFloat16Slice) Len ¶
func (s BFloat16Slice) Len() int
Len returns the number of BFloat16 elements
func (BFloat16Slice) Set ¶
func (s BFloat16Slice) Set(i int, val BFloat16)
Set sets the BFloat16 at index i
func (BFloat16Slice) SetFloat32 ¶
func (s BFloat16Slice) SetFloat32(i int, val float32)
SetFloat32 sets the value at index i from float32
type BatchResult ¶
type BatchResult struct {
KernelName string
Results []TestResult
}
BatchResult contains results for one kernel across all test cases
func (BatchResult) Summary ¶
func (br BatchResult) Summary() string
Summary returns a summary of the batch results
type BatchVerifier ¶
type BatchVerifier struct {
Verifiers []KernelVerifier
TestCases []TestCase
}
BatchVerifier runs multiple test cases and aggregates results
func (BatchVerifier) RunAll ¶
func (bv BatchVerifier) RunAll() ([]BatchResult, error)
RunAll executes all verifiers on all test cases
type BenchmarkLogger ¶
type BenchmarkLogger struct {
// contains filtered or unexported fields
}
BenchmarkLogger manages logging of benchmark results to file
type BenchmarkResult ¶
type BenchmarkResult struct {
Name string `json:"name"`
Status string `json:"status"` // "pass", "fail", "timeout"
Operations int64 `json:"operations,omitempty"`
NsPerOp float64 `json:"ns_per_op,omitempty"`
MBPerSec float64 `json:"mb_per_sec,omitempty"`
AllocsPerOp int64 `json:"allocs_per_op,omitempty"`
BytesPerOp int64 `json:"bytes_per_op,omitempty"`
Duration time.Duration `json:"duration,omitempty"`
Error string `json:"error,omitempty"`
Timestamp time.Time `json:"timestamp"`
CacheCondition string `json:"cache_condition,omitempty"` // "hot" or "cold"
}
BenchmarkResult captures the result of a single benchmark run
type CPUFeatures ¶
type CPUFeatures struct {
HasAVX bool
HasAVX2 bool
HasAVX512F bool // Foundation
HasAVX512DQ bool // Double/Quad precision
HasAVX512BW bool // Byte/Word
HasAVX512VL bool // Vector Length
HasFMA bool
HasSSE4 bool
}
CPUFeatures tracks available CPU instruction set extensions
type CacheObliviousGEMM ¶
type CacheObliviousGEMM struct {
// contains filtered or unexported fields
}
CacheObliviousGEMM implements a cache-oblivious matrix multiplication algorithm using recursive subdivision. This approach automatically adapts to any cache hierarchy without needing to know cache sizes.
The algorithm recursively divides matrices until they fit in cache, achieving near-optimal cache utilization across all cache levels simultaneously.
func NewCacheObliviousGEMM ¶
func NewCacheObliviousGEMM() *CacheObliviousGEMM
NewCacheObliviousGEMM creates a new cache-oblivious GEMM implementation
type CacheObliviousGEMMParallel ¶
type CacheObliviousGEMMParallel struct {
*CacheObliviousGEMM
// contains filtered or unexported fields
}
CacheObliviousGEMMParallel adds parallelism to the cache-oblivious algorithm
func NewCacheObliviousGEMMParallel ¶
func NewCacheObliviousGEMMParallel() *CacheObliviousGEMMParallel
NewCacheObliviousGEMMParallel creates a parallel cache-oblivious GEMM
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context represents an execution context for GUDA operations. It manages device resources, memory allocation, and stream execution. A Context must be created before any GUDA operations and should be destroyed when no longer needed.
func (*Context) CreateStream ¶
CreateStream creates a new execution stream
func (*Context) Free ¶
Free releases device memory allocated by Malloc. It is safe to call Free with a zero DevicePtr. The memory may be retained in the pool for future allocations.
func (*Context) LaunchFunc ¶
func (ctx *Context) LaunchFunc(fn KernelFunc, grid, block Dim3, args ...interface{}) error
LaunchFunc executes a kernel function on the default stream
func (*Context) LaunchFuncStream ¶
func (ctx *Context) LaunchFuncStream(fn KernelFunc, grid, block Dim3, stream *Stream, args ...interface{}) error
LaunchFuncStream executes a kernel function on a specific stream
func (*Context) LaunchStream ¶
func (ctx *Context) LaunchStream(kernel Kernel, grid, block Dim3, stream *Stream, args ...interface{}) error
LaunchStream executes a kernel on a specific stream
func (*Context) Malloc ¶
Malloc allocates device memory of the specified size in bytes. The memory is aligned for optimal SIMD performance.
Example:
ptr, err := ctx.Malloc(1024 * 4) // Allocate 1024 float32s
if err != nil {
return err
}
defer ctx.Free(ptr)
func (*Context) Memcpy ¶
func (ctx *Context) Memcpy(dst, src interface{}, size int, kind MemcpyKind) error
Memcpy copies memory between host and device. Supports various combinations of DevicePtr and Go slices.
Parameters:
- dst: Destination (DevicePtr or Go slice)
- src: Source (DevicePtr or Go slice)
- size: Number of bytes to copy
- kind: Transfer direction (for CUDA compatibility)
Example:
h_data := make([]float32, 1024) d_data, _ := ctx.Malloc(1024 * 4) ctx.Memcpy(d_data, h_data, 1024*4, guda.MemcpyHostToDevice)
func (*Context) Synchronize ¶
Synchronize waits for all streams to complete
type ConvParams ¶
type ConvParams struct {
// Input dimensions: [batch, channels, height, width]
BatchSize int
InChannels int
InHeight int
InWidth int
// Kernel dimensions: [out_channels, in_channels, kernel_height, kernel_width]
OutChannels int
KernelHeight int
KernelWidth int
// Convolution parameters
StrideH int
StrideW int
PadH int
PadW int
DilationH int
DilationW int
// Optional bias: [out_channels]
UseBias bool
}
ConvParams defines parameters for convolution operations
func (*ConvParams) OutputHeight ¶
func (p *ConvParams) OutputHeight() int
OutputHeight computes the output height after convolution
func (*ConvParams) OutputWidth ¶
func (p *ConvParams) OutputWidth() int
OutputWidth computes the output width after convolution
func (*ConvParams) Validate ¶
func (p *ConvParams) Validate() error
Validate checks if convolution parameters are valid
type Device ¶
type Device struct {
ID int // Unique device identifier
Name string // Human-readable device name
TotalMem uint64 // Total available memory in bytes
NumCores int // Number of CPU cores
MaxThreads int // Maximum concurrent threads
}
Device represents a compute device. In GUDA, this is the CPU with its cores and available memory. Each device has a unique ID and capabilities.
func GetDevice ¶
func GetDevice() *Device
GetDevice returns the current device information. In GUDA, this always returns the CPU device.
Example:
device := guda.GetDevice()
fmt.Printf("Running on: %s with %d cores\n", device.Name, device.NumCores)
func GetDeviceProperties ¶
GetDeviceProperties returns device properties
type DevicePtr ¶
type DevicePtr struct {
// contains filtered or unexported fields
}
DevicePtr represents a pointer to device memory. It provides type-safe access to device memory and supports pointer arithmetic through the Offset method. Use the type conversion methods (Float32, Float64, etc.) to access the underlying data with proper type safety.
func Malloc ¶
Malloc allocates device memory of the specified size in bytes. In GUDA, this allocates CPU memory with proper alignment for SIMD operations. The returned DevicePtr can be used with all GUDA operations.
Example:
d_data, err := guda.Malloc(1024 * 4) // Allocate 1024 float32s
if err != nil {
log.Fatal(err)
}
defer guda.Free(d_data)
func MallocOrFail ¶
MallocOrFail allocates device memory and fails the test if unsuccessful
func (DevicePtr) BFloat16 ¶
func (d DevicePtr) BFloat16() BFloat16Slice
BFloat16 returns a BFloat16 slice view of the memory
func (DevicePtr) Byte ¶
Byte returns a byte slice view of the device memory. The slice covers the entire allocated memory region. Useful for raw memory operations or interfacing with I/O.
Example:
d_buffer, _ := guda.Malloc(4096) bytes := d_buffer.Byte() copy(bytes, sourceData) // Copy raw bytes
func (DevicePtr) Float16 ¶
func (d DevicePtr) Float16() Float16Slice
Float16 returns a Float16 slice view of the memory
func (DevicePtr) Float32 ¶
Float32 returns a float32 slice view of the device memory. The slice can be used directly for reading and writing data. Panics if the memory size is not aligned to float32 boundaries.
Example:
d_data, _ := guda.Malloc(1024 * 4) // Allocate for 1024 float32s data := d_data.Float32() data[0] = 3.14 // Direct access
func (DevicePtr) Float64 ¶
Float64 returns a float64 slice view of the device memory. The slice can be used directly for reading and writing data. Panics if the memory size is not aligned to float64 boundaries.
Example:
d_data, _ := guda.Malloc(1024 * 8) // Allocate for 1024 float64s data := d_data.Float64() data[0] = 3.14159 // Direct access
func (DevicePtr) Int32 ¶
Int32 returns an int32 slice view of the device memory. The slice can be used directly for reading and writing data. Panics if the memory size is not aligned to int32 boundaries.
Example:
d_indices, _ := guda.Malloc(1024 * 4) // Allocate for 1024 int32s indices := d_indices.Int32() indices[0] = 42 // Direct access
func (DevicePtr) Offset ¶
Offset returns a new DevicePtr offset by the given number of bytes. Useful for accessing sub-regions of allocated memory. The returned DevicePtr shares the same underlying memory.
Example:
d_array, _ := guda.Malloc(1024 * 4) // 1024 float32s d_second_half := d_array.Offset(512 * 4) // Start at element 512 data := d_second_half.Float32() // Access second half
func (DevicePtr) SumSquares ¶
SumSquares computes the sum of squares of all elements Useful for L2 norm computation
type Dim3 ¶
type Dim3 struct {
X, Y, Z int
}
Dim3 represents 3D dimensions for grid and block configurations. This matches CUDA's dim3 structure for kernel launch parameters.
type FFUCapability ¶
type FFUCapability struct {
Type FFUType
Name string
DeviceID int
Available bool
// Performance characteristics
Throughput float64 // Operations per second
Latency float64 // Microseconds
PowerDraw float64 // Watts (estimated)
// Supported operations
SupportsInt8 bool
SupportsInt16 bool
SupportsFloat16 bool
SupportsFloat32 bool
SupportsFloat64 bool
// Specific capabilities
MaxMatrixSize int // For matrix operations
MaxVectorLength int // For vector operations
// Backend information
Backend string // "cpu", "rocm", "directml", "metal", etc.
VendorID uint32
DeviceInfo string
}
FFUCapability describes a fixed-function unit's capabilities
func (FFUCapability) String ¶
func (c FFUCapability) String() string
String returns a string representation of an FFU capability
type FFUDetector ¶
type FFUDetector struct {
// contains filtered or unexported fields
}
FFUDetector manages detection and enumeration of fixed-function units
func GetGlobalFFUDetector ¶
func GetGlobalFFUDetector() *FFUDetector
GetGlobalFFUDetector returns the global FFU detector
func (*FFUDetector) Detect ¶
func (d *FFUDetector) Detect() error
Detect discovers all available fixed-function units
func (*FFUDetector) FindBestFFUForWorkload ¶
func (d *FFUDetector) FindBestFFUForWorkload(workloadType string) *FFUCapability
FindBestFFUForWorkload returns the best FFU for a given workload type
func (*FFUDetector) GetCapabilities ¶
func (d *FFUDetector) GetCapabilities() []FFUCapability
GetCapabilities returns all detected FFU capabilities
func (*FFUDetector) GetCapabilitiesByType ¶
func (d *FFUDetector) GetCapabilitiesByType(ffuType FFUType) []FFUCapability
GetCapabilitiesByType returns FFUs of a specific type
type FFUType ¶
type FFUType int
FFUType represents the type of fixed-function unit
const ( FFUTypeUnknown FFUType = iota FFUTypeCPU // General purpose CPU FFUTypeAVX512VNNI // AVX-512 Vector Neural Network Instructions FFUTypeAMX // Intel Advanced Matrix Extensions FFUTypeAESNI // AES New Instructions FFUTypeSHA // SHA extensions FFUTypeGPU // General GPU compute FFUTypeVideoEncode // Hardware video encoder (NVENC, VCN, QuickSync) FFUTypeVideoDecode // Hardware video decoder FFUTypeTexture // GPU texture units FFUTypeDSP // Digital Signal Processor FFUTypeFPGA // Field Programmable Gate Array FFUTypeNPU // Neural Processing Unit )
type Float16Slice ¶
type Float16Slice struct {
// contains filtered or unexported fields
}
Float16Slice wraps a byte slice as Float16 values
func NewFloat16Slice ¶
func NewFloat16Slice(data []byte) Float16Slice
NewFloat16Slice creates a Float16 slice from a byte slice
func (Float16Slice) Get ¶
func (s Float16Slice) Get(i int) Float16
Get returns the Float16 at index i
func (Float16Slice) GetFloat32 ¶
func (s Float16Slice) GetFloat32(i int) float32
GetFloat32 returns the value at index i as float32
func (Float16Slice) Len ¶
func (s Float16Slice) Len() int
Len returns the number of Float16 elements
func (Float16Slice) Set ¶
func (s Float16Slice) Set(i int, val Float16)
Set sets the Float16 at index i
func (Float16Slice) SetFloat32 ¶
func (s Float16Slice) SetFloat32(i int, val float32)
SetFloat32 sets the value at index i from float32
type FusedKernel ¶
type FusedKernel struct {
// contains filtered or unexported fields
}
FusedKernel represents a kernel that performs multiple operations in one pass
func NewFusedKernel ¶
func NewFusedKernel() *FusedKernel
NewFusedKernel creates a new fused kernel builder
func (*FusedKernel) Add ¶
func (fk *FusedKernel) Add(alpha float32) *FusedKernel
Add adds vector addition to the fused kernel: x = x + alpha*y
func (*FusedKernel) AddBroadcast ¶
func (fk *FusedKernel) AddBroadcast(alpha float32, broadcastDim int) *FusedKernel
AddBroadcast adds broadcasted vector addition: x = x + alpha*y[broadcast]
func (*FusedKernel) AddScalar ¶
func (fk *FusedKernel) AddScalar(alpha float32) *FusedKernel
AddScalar adds scalar addition: x = x + alpha
func (*FusedKernel) Custom ¶
func (fk *FusedKernel) Custom(fn func(float32) float32) *FusedKernel
Custom adds a custom function
func (*FusedKernel) Execute ¶
Execute runs the fused kernel on the given data x: primary tensor of shape [n] others: additional tensors for binary operations shapes: shape information for broadcasting support [[dim1, dim2], ...]
func (*FusedKernel) MulScalar ¶
func (fk *FusedKernel) MulScalar(alpha float32) *FusedKernel
MulScalar adds scalar multiplication: x = x * alpha
func (*FusedKernel) Multiply ¶
func (fk *FusedKernel) Multiply() *FusedKernel
Multiply adds element-wise multiplication: x = x * y
type FusedOp ¶
type FusedOp struct {
Type FusedOpType
Alpha float32
Beta float32
Func func(float32) float32
Broadcast bool // If true, the other operand is broadcast
BroadcastDim int // Dimension to broadcast along (-1 for scalar)
}
FusedOp represents a single operation in a fused kernel
type FusedOpType ¶
type FusedOpType int
FusedOpType identifies the type of fused operation
const ( FusedAdd FusedOpType = iota FusedMul FusedAddScalar FusedMulScalar FusedReLU FusedSigmoid FusedCustom )
type FusedTransformerLayer ¶
type FusedTransformerLayer struct {
// Weights packed for cache efficiency
W_qkv *Tensor // Combined Q,K,V weights
W_o *Tensor // Output projection
// contains filtered or unexported fields
}
FusedTransformerLayer performs an entire transformer layer in one pass, keeping everything in cache to bust through the memory wall.
Traditional approach (6 memory passes):
- Q = X @ W_q
- K = X @ W_k
- V = X @ W_v
- Attention = Softmax(Q @ K^T / sqrt(d_k)) @ V
- Output = Attention @ W_o
- LayerNorm(Output + X)
Our approach (1-2 memory passes):
- Process in tiles that fit in L2 cache
- Fuse all operations while data is hot
- Use Float16 to double effective cache size
func (*FusedTransformerLayer) Forward ¶
func (t *FusedTransformerLayer) Forward(x *Tensor) *Tensor
Forward performs a full transformer layer forward pass with minimal memory access
type GUDAError ¶
type GUDAError struct {
Type ErrorType
Op string // Operation that failed
Message string // Human-readable message
Err error // Underlying error if any
Context interface{} // Additional context
}
GUDAError represents a structured error with context
type Kernel ¶
type Kernel interface {
Execute(tid ThreadID, args ...interface{})
}
Kernel represents a compute kernel that can be executed in parallel. Implementations should be thread-safe as Execute will be called concurrently from multiple threads.
type KernelFunc ¶
type KernelFunc func(tid ThreadID, args ...interface{})
KernelFunc is a function that can be launched as a kernel. It receives thread identification and variadic arguments.
func (KernelFunc) Execute ¶
func (fn KernelFunc) Execute(tid ThreadID, args ...interface{})
Implement KernelFunc as Kernel
type KernelVerifier ¶
type KernelVerifier struct {
Name string
Reference func([]float32) []float32
Optimized func(DevicePtr) error
Tolerance ToleranceConfig
}
VerifyKernel runs a kernel with reference implementation and verifies results
func (KernelVerifier) Verify ¶
func (kv KernelVerifier) Verify(input []float32) (VerificationResult, error)
Verify runs both implementations and compares results
type LinuxPerfMonitor ¶
type LinuxPerfMonitor struct {
// contains filtered or unexported fields
}
LinuxPerfMonitor provides direct access to hardware performance counters
func NewLinuxPerfMonitor ¶
func NewLinuxPerfMonitor() *LinuxPerfMonitor
NewLinuxPerfMonitor creates a performance monitor using perf_event_open
func (*LinuxPerfMonitor) Start ¶
func (pm *LinuxPerfMonitor) Start() error
Start begins performance counter collection
func (*LinuxPerfMonitor) Stop ¶
func (pm *LinuxPerfMonitor) Stop() *PerfCounters
Stop ends collection and returns counters
type MathConfig ¶
type MathConfig struct {
// Layer normalization epsilon for numerical stability
LayerNormEpsilon float32
// Activation function saturation limits
ActivationSaturation float32
// Test tolerance for numerical comparisons
TestTolerance float64
// Use high-precision implementations (slower but more accurate)
HighPrecision bool
}
MathConfig allows runtime configuration of mathematical parameters
func DefaultMathConfig ¶
func DefaultMathConfig() MathConfig
DefaultMathConfig returns the default mathematical configuration
func FastMathConfig ¶
func FastMathConfig() MathConfig
FastMathConfig returns a configuration optimized for speed
func StrictMathConfig ¶
func StrictMathConfig() MathConfig
StrictMathConfig returns a configuration optimized for accuracy
type MemcpyKind ¶
type MemcpyKind int
MemcpyKind specifies the direction of memory transfer. In GUDA's unified memory model, these are provided for CUDA compatibility but may be treated identically since all memory is CPU-accessible.
const ( MemcpyHostToHost MemcpyKind = iota // Host to host transfer MemcpyHostToDevice // Host to device transfer MemcpyDeviceToHost // Device to host transfer MemcpyDeviceToDevice // Device to device transfer MemcpyDefault // Default transfer (infer direction) )
type MemoryPool ¶
type MemoryPool struct {
// contains filtered or unexported fields
}
MemoryPool manages device memory allocation with efficient reuse. It maintains a free list of previously allocated blocks to reduce allocation overhead and memory fragmentation.
func NewMemoryPool ¶
func NewMemoryPool() *MemoryPool
NewMemoryPool creates a new memory pool for efficient memory management. The pool tracks allocations and provides statistics on memory usage.
func (*MemoryPool) Allocate ¶
func (mp *MemoryPool) Allocate(size int) (DevicePtr, error)
Allocate allocates memory from the pool
func (*MemoryPool) Free ¶
func (mp *MemoryPool) Free(ptr DevicePtr) error
Free returns memory to the pool
func (*MemoryPool) GetStats ¶
func (mp *MemoryPool) GetStats() (allocated, peak int64)
GetStats returns memory pool statistics
type NumericalParity ¶
type NumericalParity struct {
MaxAbsError float32
MaxRelError float32
MaxULPError int32
NumErrors int
}
NumericalParity provides tools for comparing floating point results
func (*NumericalParity) CheckTolerance ¶
func (np *NumericalParity) CheckTolerance(tol OperationTolerance) bool
CheckTolerance returns true if the numerical differences are within tolerance
func (*NumericalParity) CompareFloat32 ¶
func (np *NumericalParity) CompareFloat32(expected, actual float32)
CompareFloat32 compares two float32 values and updates error statistics
func (*NumericalParity) CompareSlices ¶
func (np *NumericalParity) CompareSlices(expected, actual []float32)
CompareSlices compares two slices of float32
type OperationTolerance ¶
OperationTolerance defines acceptable error for an operation
type OptimizedGEMM ¶
type OptimizedGEMM struct {
// contains filtered or unexported fields
}
OptimizedGEMM provides a high-performance GEMM implementation that combines our insights from the memory wall document with our existing AVX2/AVX512 kernels
func NewOptimizedGEMM ¶
func NewOptimizedGEMM() *OptimizedGEMM
NewOptimizedGEMM creates an optimized GEMM instance
func (*OptimizedGEMM) Compute ¶
func (og *OptimizedGEMM) Compute( transA, transB bool, m, n, k int, alpha float32, a []float32, lda int, b []float32, ldb int, beta float32, c []float32, ldc int, )
Compute performs C = alpha * A * B + beta * C This implementation reuses our existing optimized kernels but with better memory access patterns
type PerfCounters ¶
type PerfCounters struct {
// Timing
Duration time.Duration
// CPU counters
Cycles uint64
Instructions uint64
BranchMisses uint64
CacheMisses uint64
L1DCacheMisses uint64
L3CacheMisses uint64
// Memory counters
MemoryBandwidth float64 // GB/s
// Floating point counters
FP32Operations uint64
FMAOperations uint64
// Derived metrics
IPC float64 // Instructions per cycle
GFLOPS float64 // Billions of FP ops per second
CacheMissRate float64 // L3 miss rate
}
PerfCounters holds performance counter measurements
func MeasureKernel ¶
func MeasureKernel(name string, kernel func() error) (*PerfCounters, error)
MeasureKernel runs a kernel and collects performance counters
func MeasureWithHardwareCounters ¶
func MeasureWithHardwareCounters(name string, fn func() error) (*PerfCounters, error)
MeasureWithHardwareCounters runs a function and collects hardware counters
func (*PerfCounters) CalculateMetrics ¶
func (pc *PerfCounters) CalculateMetrics(flops uint64, bytes uint64)
CalculateMetrics computes derived performance metrics
func (*PerfCounters) String ¶
func (pc *PerfCounters) String() string
String formats performance counters for display
type PerfMonitor ¶
type PerfMonitor struct {
// contains filtered or unexported fields
}
PerfMonitor manages performance counter collection
func NewPerfMonitor ¶
func NewPerfMonitor() *PerfMonitor
NewPerfMonitor creates a new performance monitor
func (*PerfMonitor) Start ¶
func (pm *PerfMonitor) Start() error
Start begins collecting performance counters
func (*PerfMonitor) Stop ¶
func (pm *PerfMonitor) Stop() (*PerfCounters, error)
Stop ends collection and returns counters
type Reference ¶
type Reference struct{}
Reference contains simple, correct implementations of all kernels These are used for testing and verification of optimized implementations
func (Reference) AddBiasReLU ¶
AddBiasReLURef performs x = ReLU(x + bias) where bias is broadcast
func (Reference) Conv2D ¶
func (r Reference) Conv2D( input []float32, batch, inC, inH, inW int, kernel []float32, outC, kernelH, kernelW int, output []float32, strideH, strideW, padH, padW int)
Conv2DRef performs 2D convolution (NCHW format) This is a simple direct convolution, not optimized
func (Reference) GEMM ¶
func (r Reference) GEMM(transA, transB bool, m, n, k int, alpha float32, a []float32, lda int, b []float32, ldb int, beta float32, c []float32, ldc int)
GEMMRef performs general matrix multiplication: C = alpha*A*B + beta*C
func (Reference) GEMMBiasReLU ¶
func (r Reference) GEMMBiasReLU( m, n, k int, alpha float32, a []float32, lda int, b []float32, ldb int, bias []float32, c []float32, ldc int)
GEMMBiasReLURef performs C = ReLU(alpha*A*B + bias)
func (Reference) GEMV ¶
func (r Reference) GEMV(transA bool, m, n int, alpha float32, a []float32, lda int, x []float32, incX int, beta float32, y []float32, incY int)
GEMVRef performs matrix-vector multiplication: y = alpha*A*x + beta*y
func (Reference) LinearReLU ¶
LinearReLURef performs x = ReLU(alpha*x + beta)
type Stream ¶
type Stream struct {
// contains filtered or unexported fields
}
Stream represents an ordered sequence of operations that execute asynchronously. Operations within a stream execute in order, but operations in different streams may execute concurrently.
func (*Stream) Synchronize ¶
func (s *Stream) Synchronize()
Synchronize waits for all tasks in the stream to complete
type StreamingGEMM ¶
type StreamingGEMM struct {
// contains filtered or unexported fields
}
StreamingGEMM implements a memory-bandwidth optimized GEMM that minimizes memory traffic by processing data in streaming fashion
func NewStreamingGEMM ¶
func NewStreamingGEMM() *StreamingGEMM
NewStreamingGEMM creates a streaming GEMM optimized for memory bandwidth
type Tensor ¶
type Tensor struct {
// contains filtered or unexported fields
}
Tensor represents a multi-dimensional array for GUDA operations
func AllocateTensor ¶
AllocateTensor creates a new tensor with the given shape
type TestResult ¶
type TestResult struct {
TestName string
Result VerificationResult
Error error
}
TestResult contains the result of one test case
type TestVector ¶
type TestVector struct {
Name string
M, N, K int
Alpha, Beta float32
A, B, CInput []float32
CExpected []float32
}
TestVector represents a test case with inputs and expected output
func LoadTestCase ¶
func LoadTestCase(basePath, name string) (*TestVector, error)
LoadTestCase loads all files for a test case
type ThreadID ¶
type ThreadID struct {
BlockIdx Dim3 // Block index within the grid
ThreadIdx Dim3 // Thread index within the block
BlockDim Dim3 // Dimensions of the block
GridDim Dim3 // Dimensions of the grid
}
ThreadID identifies a thread's position within the execution hierarchy. It provides the same indexing semantics as CUDA's built-in variables: blockIdx, threadIdx, blockDim, and gridDim.
type ToleranceConfig ¶
type ToleranceConfig struct {
// AbsTol is the absolute tolerance for values near zero
AbsTol float32
// RelTol is the relative tolerance as a fraction of the larger value
RelTol float32
// ULPTol is the maximum allowed difference in ULPs (Units in Last Place)
ULPTol int
// CheckNaN determines if NaN values should be considered equal
CheckNaN bool
// CheckInf determines if Inf values should be considered equal
CheckInf bool
}
ToleranceConfig defines tolerance parameters for floating-point comparison
func DefaultTolerance ¶
func DefaultTolerance() ToleranceConfig
DefaultTolerance returns default tolerance configuration
func GetArchTolerance ¶
func GetArchTolerance(config ArchToleranceConfig) ToleranceConfig
GetArchTolerance returns the appropriate tolerance for the current architecture
func GetOperationTolerance ¶
func GetOperationTolerance(operation string) ToleranceConfig
GetOperationTolerance returns architecture-specific tolerance for an operation
func RelaxedTolerance ¶
func RelaxedTolerance() ToleranceConfig
RelaxedTolerance returns relaxed tolerance for accumulated operations
func StrictTolerance ¶
func StrictTolerance() ToleranceConfig
StrictTolerance returns strict tolerance configuration for high precision
type VerificationResult ¶
type VerificationResult struct {
MaxAbsError float32
MaxRelError float32
MaxULPError int
NumErrors int
TotalItems int
FirstError int // Index of first error, -1 if none
}
VerifyFloat32Array compares two float32 arrays with tolerance
func VerifyFloat32Array ¶
func VerifyFloat32Array(expected, actual []float32, tol ToleranceConfig) VerificationResult
VerifyFloat32Array compares two float32 arrays and returns detailed results
func (VerificationResult) IsAcceptable ¶
func (r VerificationResult) IsAcceptable(tol ToleranceConfig) bool
IsAcceptable returns true if the verification result is within tolerance
func (VerificationResult) String ¶
func (r VerificationResult) String() string
String formats the verification result for display
type WorkerPool ¶
type WorkerPool struct {
// contains filtered or unexported fields
}
WorkerPool manages a pool of worker goroutines for kernel execution. It provides efficient task distribution and execution across CPU cores.
func NewWorkerPool ¶
func NewWorkerPool(workers int) *WorkerPool
NewWorkerPool creates a new worker pool with the specified number of workers. If workers <= 0, it defaults to runtime.NumCPU(). The pool starts workers immediately and is ready to accept tasks.
Example:
pool := guda.NewWorkerPool(8) // 8 worker threads defer pool.Close()
func (*WorkerPool) Submit ¶
func (wp *WorkerPool) Submit(task func())
Submit adds a task to the pool
Source Files
¶
- activations.go
- benchmark_logger.go
- bfloat16.go
- cache_oblivious_gemm.go
- config.go
- conv.go
- cpu_features.go
- doc.go
- errors.go
- execution.go
- ffu_detector.go
- float16.go
- float16_simd_amd64.go
- fused.go
- fused_gelu.go
- fused_transformer_layer.go
- generate_cpu_reference.go
- guda.go
- math.go
- math_constants.go
- memory.go
- numerical_parity.go
- optimized_gemm.go
- perf_counters.go
- perf_counters_linux.go
- prefetch.go
- reduce.go
- reference.go
- streaming_gemm.go
- test_data.go
- test_helpers.go
- test_vector_comparison.go
- tolerance.go
- tolerance_arch.go
- version.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package blas provides interfaces for the BLAS linear algebra standard.
|
Package blas provides interfaces for the BLAS linear algebra standard. |
|
blas32
Package blas32 provides a simple interface to the float32 BLAS API.
|
Package blas32 provides a simple interface to the float32 BLAS API. |
|
blas64
Package blas64 provides a simple interface to the float64 BLAS API.
|
Package blas64 provides a simple interface to the float64 BLAS API. |
|
cblas128
Package cblas128 provides a simple interface to the complex128 BLAS API.
|
Package cblas128 provides a simple interface to the complex128 BLAS API. |
|
cblas64
Package cblas64 provides a simple interface to the complex64 BLAS API.
|
Package cblas64 provides a simple interface to the complex64 BLAS API. |
|
gonum
Package gonum is a Go implementation of the BLAS API.
|
Package gonum is a Go implementation of the BLAS API. |
|
testblas
Package testblas provides tests for blas implementations.
|
Package testblas provides tests for blas implementations. |
|
testblas/benchautogen
command
Script for automatic code generation of the benchmark routines.
|
Script for automatic code generation of the benchmark routines. |
|
cmd
|
|
|
baseline
command
Command baseline captures performance and numerical baselines before optimization
|
Command baseline captures performance and numerical baselines before optimization |
|
bench-parser
command
|
|
|
cache_flush
command
|
|
|
compare
command
Command compare compares current results against baseline
|
Command compare compares current results against baseline |
|
example
command
|
|
|
Package cmplxs provides a set of helper routines for dealing with slices of complex128.
|
Package cmplxs provides a set of helper routines for dealing with slices of complex128. |
|
cscalar
Package cscalar provides a set of helper routines for dealing with complex128 values.
|
Package cscalar provides a set of helper routines for dealing with complex128 values. |
|
Package gonum is a Go implementation of the BLAS API.
|
Package gonum is a Go implementation of the BLAS API. |
|
asm/f32
Package f32 provides float32 vector primitives.
|
Package f32 provides float32 vector primitives. |
|
asm/f64
Package f64 provides float64 vector primitives.
|
Package f64 provides float64 vector primitives. |
|
blas
Package blas provides interfaces for the BLAS linear algebra standard.
|
Package blas provides interfaces for the BLAS linear algebra standard. |
|
internal/math32
Package math32 provides float32 versions of standard library math package routines used by gonum/blas/native.
|
Package math32 provides float32 versions of standard library math package routines used by gonum/blas/native. |
|
diff
|
|
|
fd
Package fd provides functions to approximate derivatives using finite differences.
|
Package fd provides functions to approximate derivatives using finite differences. |
|
dsp
|
|
|
fourier
Package fourier provides functions to perform Discrete Fourier Transforms.
|
Package fourier provides functions to perform Discrete Fourier Transforms. |
|
fourier/internal/fftpack
Package fftpack implements Discrete Fourier Transform functions ported from the Fortran implementation of FFTPACK.
|
Package fftpack implements Discrete Fourier Transform functions ported from the Fortran implementation of FFTPACK. |
|
transform
Package transform provides important transforms on signals used in digital signal processing.
|
Package transform provides important transforms on signals used in digital signal processing. |
|
window
Package window provides a set of functions to perform the transformation of sequence by different window functions.
|
Package window provides a set of functions to perform the transformation of sequence by different window functions. |
|
window/cmd/leakage
command
The leakage program provides summary characteristics and a plot of spectral response for window functions or csv input.
|
The leakage program provides summary characteristics and a plot of spectral response for window functions or csv input. |
|
examples
|
|
|
comparison
command
|
|
|
ffu_aes
command
|
|
|
float16_simd_benchmark
command
|
|
|
float16_test
command
|
|
|
fusion
command
|
|
|
matrix_multiply
command
|
|
|
perf_validation
command
Performance validation example demonstrating GUDA's performance counter integration This validates the 2K GFLOPS claims with hardware performance counters
|
Performance validation example demonstrating GUDA's performance counter integration This validates the 2K GFLOPS claims with hardware performance counters |
|
simd_test
command
|
|
|
tolerance_verification
command
Example demonstrating tolerance-based verification in GUDA
|
Example demonstrating tolerance-based verification in GUDA |
|
vector_add
command
|
|
|
Package floats provides a set of helper routines for dealing with slices of float64.
|
Package floats provides a set of helper routines for dealing with slices of float64. |
|
scalar
Package scalar provides a set of helper routines for dealing with float64 values.
|
Package scalar provides a set of helper routines for dealing with float64 values. |
|
Package graph defines graph interfaces.
|
Package graph defines graph interfaces. |
|
coloring
Package coloring provides graph coloring functions.
|
Package coloring provides graph coloring functions. |
|
community
Package community provides graph community detection functions.
|
Package community provides graph community detection functions. |
|
encoding
Package encoding provides a common graph encoding API.
|
Package encoding provides a common graph encoding API. |
|
encoding/digraph6
Package digraph6 implements graphs specified by digraph6 strings.
|
Package digraph6 implements graphs specified by digraph6 strings. |
|
encoding/dot
Package dot implements GraphViz DOT marshaling and unmarshaling of graphs.
|
Package dot implements GraphViz DOT marshaling and unmarshaling of graphs. |
|
encoding/graph6
Package graph6 implements graphs specified by graph6 strings.
|
Package graph6 implements graphs specified by graph6 strings. |
|
encoding/graphql
Package graphql implements JSON marshaling and unmarshaling of graph as used by GraphQL
|
Package graphql implements JSON marshaling and unmarshaling of graph as used by GraphQL |
|
flow
Package flow provides control flow analysis functions.
|
Package flow provides control flow analysis functions. |
|
formats/cytoscapejs
Package cytoscapejs implements marshaling and unmarshaling of Cytoscape.js JSON documents.
|
Package cytoscapejs implements marshaling and unmarshaling of Cytoscape.js JSON documents. |
|
formats/dot
Package dot implements a parser for Graphviz DOT files.
|
Package dot implements a parser for Graphviz DOT files. |
|
formats/dot/ast
Package ast declares the types used to represent abstract syntax trees of Graphviz DOT graphs.
|
Package ast declares the types used to represent abstract syntax trees of Graphviz DOT graphs. |
|
formats/dot/internal/astx
Package astx implements utility functions for generating abstract syntax trees of Graphviz DOT graphs.
|
Package astx implements utility functions for generating abstract syntax trees of Graphviz DOT graphs. |
|
formats/dot/internal/errors
Package errors provides generated internal error functions for DOT parsing.
|
Package errors provides generated internal error functions for DOT parsing. |
|
formats/dot/internal/lexer
Package lexer provides generated internal lexer functions for DOT parsing.
|
Package lexer provides generated internal lexer functions for DOT parsing. |
|
formats/dot/internal/parser
Package parser provides generated internal parsing functions for DOT parsing.
|
Package parser provides generated internal parsing functions for DOT parsing. |
|
formats/dot/internal/token
Package token provides generated internal tokenizing functions for DOT parsing.
|
Package token provides generated internal tokenizing functions for DOT parsing. |
|
formats/dot/internal/util
Package util provides generated internal utility functions for DOT parsing.
|
Package util provides generated internal utility functions for DOT parsing. |
|
formats/gexf12
Package gexf12 implements marshaling and unmarshaling of GEXF1.2 documents.
|
Package gexf12 implements marshaling and unmarshaling of GEXF1.2 documents. |
|
formats/rdf
Package rdf implements decoding the RDF 1.1 N-Quads line-based plain text format for encoding an RDF dataset.
|
Package rdf implements decoding the RDF 1.1 N-Quads line-based plain text format for encoding an RDF dataset. |
|
formats/sigmajs
Package sigmajs implements marshaling and unmarshaling of Sigma.js JSON documents.
|
Package sigmajs implements marshaling and unmarshaling of Sigma.js JSON documents. |
|
graphs/gen
Package gen provides random graph generation functions.
|
Package gen provides random graph generation functions. |
|
internal/linear
Package linear provides common linear data structures.
|
Package linear provides common linear data structures. |
|
internal/set
Package set provides integer and graph.Node sets.
|
Package set provides integer and graph.Node sets. |
|
iterator
Package iterator provides node, edge and line iterators.
|
Package iterator provides node, edge and line iterators. |
|
layout
Package layout defines functions for performing graph layout.
|
Package layout defines functions for performing graph layout. |
|
multi
Package multi provides a suite of multigraph implementations satisfying the gonum/graph interfaces.
|
Package multi provides a suite of multigraph implementations satisfying the gonum/graph interfaces. |
|
network
Package network provides network analysis functions.
|
Package network provides network analysis functions. |
|
path
Package path provides graph path finding functions.
|
Package path provides graph path finding functions. |
|
path/dynamic
Package dynamic provides incremental heuristic graph path finding functions.
|
Package dynamic provides incremental heuristic graph path finding functions. |
|
path/internal/testgraphs
Package testgraphs provides a number of graphs used for testing routines in the path and path/dynamic packages.
|
Package testgraphs provides a number of graphs used for testing routines in the path and path/dynamic packages. |
|
product
Package product implements graph product functions.
|
Package product implements graph product functions. |
|
set/uid
Package uid implements unique ID provision for graphs.
|
Package uid implements unique ID provision for graphs. |
|
simple
Package simple provides a suite of simple graph implementations satisfying the gonum/graph interfaces.
|
Package simple provides a suite of simple graph implementations satisfying the gonum/graph interfaces. |
|
spectral
Package spectral provides graph spectral analysis functions.
|
Package spectral provides graph spectral analysis functions. |
|
testgraph
Package testgraph provides a set of testing helper functions that test Gonum graph interface implementations.
|
Package testgraph provides a set of testing helper functions that test Gonum graph interface implementations. |
|
topo
Package topo provides graph topology analysis functions.
|
Package topo provides graph topology analysis functions. |
|
traverse
Package traverse provides basic graph traversal primitives.
|
Package traverse provides basic graph traversal primitives. |
|
Package integrate provides functions to compute an integral given a specific list of evaluations.
|
Package integrate provides functions to compute an integral given a specific list of evaluations. |
|
quad
Package quad provides numerical evaluation of definite integrals of single-variable functions.
|
Package quad provides numerical evaluation of definite integrals of single-variable functions. |
|
testquad
Package testquad provides integrals for testing quadrature algorithms.
|
Package testquad provides integrals for testing quadrature algorithms. |
|
internal
|
|
|
asm/c128
Package c128 provides complex128 vector primitives.
|
Package c128 provides complex128 vector primitives. |
|
asm/c64
Package c64 provides complex64 vector primitives.
|
Package c64 provides complex64 vector primitives. |
|
asm/f64
Package f64 provides float64 vector primitives.
|
Package f64 provides float64 vector primitives. |
|
cmplx64
Package cmplx64 provides complex64 versions of standard library math/cmplx package routines used by gonum/blas.
|
Package cmplx64 provides complex64 versions of standard library math/cmplx package routines used by gonum/blas. |
|
math32
Package math32 provides float32 versions of standard library math package routines used by gonum/blas/native.
|
Package math32 provides float32 versions of standard library math package routines used by gonum/blas/native. |
|
order
Package order provides common sorting functions.
|
Package order provides common sorting functions. |
|
testrand
Package testrand provides random generation and flags for testing.
|
Package testrand provides random generation and flags for testing. |
|
Package interp implements 1-dimensional algorithms for interpolating values.
|
Package interp implements 1-dimensional algorithms for interpolating values. |
|
Package lapack provides interfaces for the LAPACK linear algebra standard.
|
Package lapack provides interfaces for the LAPACK linear algebra standard. |
|
gonum
Package gonum is a pure-go implementation of the LAPACK API.
|
Package gonum is a pure-go implementation of the LAPACK API. |
|
lapack64
Package lapack64 provides a set of convenient wrapper functions for LAPACK calls, as specified in the netlib standard (www.netlib.org).
|
Package lapack64 provides a set of convenient wrapper functions for LAPACK calls, as specified in the netlib standard (www.netlib.org). |
|
testlapack
Package testlapack implements a set of testing routines for Lapack functions.
|
Package testlapack implements a set of testing routines for Lapack functions. |
|
Package mat provides implementations of float64 and complex128 matrix structures and linear algebra operations on them.
|
Package mat provides implementations of float64 and complex128 matrix structures and linear algebra operations on them. |
|
Package mathext implements special math functions not implemented by the Go standard library.
|
Package mathext implements special math functions not implemented by the Go standard library. |
|
internal/amos
Package amos implements functions originally in the Netlib code by Donald Amos.
|
Package amos implements functions originally in the Netlib code by Donald Amos. |
|
internal/cephes
Package cephes implements functions originally in the Netlib code by Stephen Mosher.
|
Package cephes implements functions originally in the Netlib code by Stephen Mosher. |
|
internal/gonum
Package gonum contains functions implemented by the gonum team.
|
Package gonum contains functions implemented by the gonum team. |
|
prng
Package prng provides random source PRNG implementations.
|
Package prng provides random source PRNG implementations. |
|
num
|
|
|
dual
Package dual provides the dual numeric type and functions.
|
Package dual provides the dual numeric type and functions. |
|
dualcmplx
Package dualcmplx provides the anti-commutative dual complex numeric type and functions.
|
Package dualcmplx provides the anti-commutative dual complex numeric type and functions. |
|
dualquat
Package dualquat provides the dual quaternion numeric type and functions.
|
Package dualquat provides the dual quaternion numeric type and functions. |
|
hyperdual
Package hyperdual provides the hyperdual numeric type and functions.
|
Package hyperdual provides the hyperdual numeric type and functions. |
|
quat
Package quat provides the quaternion numeric type and functions.
|
Package quat provides the quaternion numeric type and functions. |
|
Package optimize implements algorithms for finding the optimum value of functions.
|
Package optimize implements algorithms for finding the optimum value of functions. |
|
convex/lp
Package lp implements routines to solve linear programming problems.
|
Package lp implements routines to solve linear programming problems. |
|
functions
Package functions provides objective functions for testing optimization algorithms.
|
Package functions provides objective functions for testing optimization algorithms. |
|
spatial
|
|
|
barneshut
Package barneshut provides routines for calculating n-body force approximations using the Barnes-Hut algorithm.
|
Package barneshut provides routines for calculating n-body force approximations using the Barnes-Hut algorithm. |
|
curve
Package curve defines space filling curves.
|
Package curve defines space filling curves. |
|
kdtree
Package kdtree implements a k-d tree.
|
Package kdtree implements a k-d tree. |
|
r1
Package r1 provides 1D vectors and intervals and operations on them.
|
Package r1 provides 1D vectors and intervals and operations on them. |
|
r2
Package r2 provides 2D vectors and boxes and operations on them.
|
Package r2 provides 2D vectors and boxes and operations on them. |
|
r3
Package r3 provides 3D vectors and boxes and operations on them.
|
Package r3 provides 3D vectors and boxes and operations on them. |
|
vptree
Package vptree implements a vantage point tree.
|
Package vptree implements a vantage point tree. |
|
Package stat provides generalized statistical functions.
|
Package stat provides generalized statistical functions. |
|
card
Package card provides cardinality estimation functions.
|
Package card provides cardinality estimation functions. |
|
combin
Package combin implements routines involving combinatorics (permutations, combinations, etc.).
|
Package combin implements routines involving combinatorics (permutations, combinations, etc.). |
|
distmat
Package distmat provides probability distributions over matrices.
|
Package distmat provides probability distributions over matrices. |
|
distmv
Package distmv provides multivariate random distribution types.
|
Package distmv provides multivariate random distribution types. |
|
distuv
Package distuv provides univariate random distribution types.
|
Package distuv provides univariate random distribution types. |
|
mds
Package mds provides multidimensional scaling functions.
|
Package mds provides multidimensional scaling functions. |
|
samplemv
Package samplemv implements advanced sampling routines from explicit and implicit probability distributions.
|
Package samplemv implements advanced sampling routines from explicit and implicit probability distributions. |
|
sampleuv
Package sampleuv implements advanced sampling routines from explicit and implicit probability distributions.
|
Package sampleuv implements advanced sampling routines from explicit and implicit probability distributions. |
|
spatial
Package spatial provides spatial statistical functions.
|
Package spatial provides spatial statistical functions. |
|
Package unit provides a set of types and constants that facilitate the use of the International System of Units (SI).
|
Package unit provides a set of types and constants that facilitate the use of the International System of Units (SI). |
|
constant
Package constant provides fundamental constants satisfying unit.Uniter.
|
Package constant provides fundamental constants satisfying unit.Uniter. |