guda

package module
v0.0.0-...-4ddd2c0 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2025 License: BSD-3-Clause Imports: 24 Imported by: 0

README

🧀 GUDA: A High-Performance CPU-Based CUDA-Compatible Linear Algebra Library

📚 Read the Full Manual | 🚀 Quick Start Guide | 🏗️ Architecture Overview

🚀 Breaking News: 18x AI Inference Speedup!

GUDA now includes Fixed-Function Unit (FFU) support, automatically leveraging specialized CPU instructions:

  • AVX512-VNNI: 37.5 GOPS for INT8 ops (18x speedup!)
  • AES-NI: 8.4 GB/s crypto throughput
  • AMX: 2 TOPS potential (experimental)

Performance Highlights

GUDA achieves 150+ GFLOPS sustained performance on modern CPUs through aggressive optimization:

Operation Performance vs. Practical Peak Cache Impact
GEMM 1024×1024 154 GFLOPS 154% <1% drop cold
AXPY 16K 40 GFLOPS Memory limited 0% drop cold
DOT 1K 68 GFLOPS Memory limited 0% drop cold
Memory BW 240+ GB/s 90% of DDR5 -

📊 Full Benchmark Results | 🧊 Cold Cache Analysis | 📈 Benchmarking Guide

Abstract

We present GUDA (Go Unified Device Architecture), a novel implementation of CUDA-compatible APIs designed for CPU execution. Rather than simulating GPU hardware, GUDA provides a unified memory architecture and maps CUDA operations to highly optimized native CPU implementations. This library enables seamless deployment of CUDA applications on CPU-only infrastructure through aggressive SIMD optimization, native BLAS integration, and elimination of host-device memory transfers. Our implementation demonstrates that CPU-native approaches can provide a practical alternative for running CUDA applications where GPU hardware is unavailable.

1. Introduction

The proliferation of GPU computing has created a dichotomy in the high-performance computing landscape, where applications are often tightly coupled to specific hardware accelerators. This coupling presents challenges for deployment flexibility, development workflows, and resource utilization in heterogeneous computing environments.

GUDA addresses these challenges by providing a CPU-based implementation of core CUDA APIs, enabling:

  • Development and testing of CUDA applications without GPU hardware
  • Deployment flexibility in CPU-only environments
  • Performance portability across different architectures
  • A foundation for heterogeneous computing strategies
1.1 Motivation

The primary motivations for this work include:

  1. Development Accessibility: Enabling CUDA development on systems without NVIDIA GPUs
  2. Deployment Flexibility: Running CUDA applications in CPU-only production environments
  3. Performance Investigation: Understanding the performance characteristics of GPU algorithms on modern CPUs
  4. Architectural Research: Exploring the convergence of CPU and GPU programming models
1.2 Contributions

This work makes the following contributions:

  • A comprehensive CPU implementation of core CUDA runtime and cuBLAS APIs
  • Novel SIMD-optimized kernels for both x86-64 (AVX2/AVX-512) and ARM64 (NEON) architectures
  • Architecture-aware floating-point tolerance system handling platform-specific numerical differences
  • Extensive numerical validation framework ensuring compatibility within architecture constraints
  • Performance analysis demonstrating the viability of CPU execution for GPU-designed algorithms

2. Background

2.1 CUDA Programming Model

CUDA (Compute Unified Device Architecture) provides a parallel computing platform and programming model for NVIDIA GPUs. Key abstractions include:

  • Kernels: Functions executed in parallel by many threads
  • Thread Hierarchy: Threads organized into blocks and grids
  • Memory Hierarchy: Global, shared, and local memory spaces
  • Synchronization: Barriers and atomic operations
2.2 CPU SIMD Architecture

Modern CPUs provide SIMD (Single Instruction, Multiple Data) extensions:

  • x86-64: AVX2 (256-bit vectors, 8 float32 values) and AVX-512 (512-bit vectors, 16 float32 values)
  • ARM64: NEON (128-bit vectors, 4 float32 values) with architecture-aware floating-point tolerances
  • Memory Bandwidth: Increasingly important bottleneck for data-parallel algorithms

Previous efforts to bridge GPU and CPU computing include:

  • Intel's ISPC (Intel SPMD Program Compiler)
  • OpenCL implementations for CPUs
  • Various CUDA-to-CPU translation tools

GUDA differs by providing direct API compatibility rather than source translation.

3. Design and Implementation

3.1 Architecture Overview

GUDA consists of several key components:

guda/
├── core.go          # Core CUDA runtime API implementation
├── memory.go        # Memory management and allocation
├── stream.go        # Stream and event management
├── blas.go          # cuBLAS API implementation
├── kernel.go        # Kernel execution framework
└── simd/           # Platform-specific SIMD implementations
graph TB
    subgraph "Application Layer"
        APP[CUDA Application]
    end
    
    subgraph "GUDA API Layer"
        RT[Runtime API<br/>cudaMalloc, cudaMemcpy]
        BLAS[cuBLAS API<br/>GEMM, AXPY, DOT]
        KERNEL[Kernel API<br/>Launch, Synchronize]
    end
    
    subgraph "Execution Layer"
        MEM[Memory Manager<br/>Unified Memory Model]
        EXEC[Kernel Executor<br/>Thread→CPU Core Mapping]
        STREAM[Stream Manager<br/>Async Operations]
    end
    
    subgraph "Optimization Layer"
        SIMD[SIMD Kernels<br/>AVX2/AVX-512]
        FUSED[Fused Operations<br/>GEMM+Bias+Activation]
        CACHE[Cache Optimization<br/>Tiling & Prefetch]
    end
    
    subgraph "Hardware"
        CPU[CPU Cores<br/>x86-64 AVX2/AVX-512<br/>ARM64 NEON]
    end
    
    APP --> RT
    APP --> BLAS
    APP --> KERNEL
    
    RT --> MEM
    BLAS --> EXEC
    KERNEL --> EXEC
    
    MEM --> SIMD
    EXEC --> SIMD
    EXEC --> FUSED
    STREAM --> EXEC
    
    SIMD --> CPU
    FUSED --> CPU
    CACHE --> CPU
    
    %% High contrast styling for accessibility
    classDef appLayer fill:#2E86AB,stroke:#ffffff,stroke-width:3px,color:#ffffff
    classDef apiLayer fill:#A23B72,stroke:#ffffff,stroke-width:2px,color:#ffffff
    classDef execLayer fill:#F18F01,stroke:#ffffff,stroke-width:2px,color:#ffffff
    classDef optLayer fill:#C73E1D,stroke:#ffffff,stroke-width:2px,color:#ffffff
    classDef hwLayer fill:#1B1B1B,stroke:#ffffff,stroke-width:3px,color:#ffffff
    
    class APP appLayer
    class RT,BLAS,KERNEL apiLayer
    class MEM,EXEC,STREAM execLayer
    class SIMD,FUSED,CACHE optLayer
    class CPU hwLayer
3.2 Unified Memory Architecture

GUDA fundamentally differs from traditional GPU computing by implementing a unified memory model where all memory is CPU RAM:

type DevicePtr struct {
    ptr    unsafe.Pointer
    size   int
    offset int
}

Key architectural decisions:

  • No Separate Device Memory: cudaMalloc allocates regular CPU RAM, not GPU memory
  • Zero-Copy Operations: cudaMemcpy operations are no-ops or simple copy() calls
  • Memory Pool Management: Efficient allocation/deallocation with free list reuse
  • Type-Safe Access: DevicePtr provides .Float32(), .Int32(), .Byte() views of the same memory

This eliminates PCIe transfer overhead entirely and enables direct CPU access to all data.

3.3 CPU-Native Execution Model

Rather than simulating GPU threads, GUDA maps CUDA execution patterns to CPU-native optimizations:

  1. Native BLAS Integration: GEMM and BLAS operations call highly optimized CPU libraries (assimilated Gonum)
  2. SIMD-First Design: GPU warps (32 threads) map to AVX2 vectors (8 float32 operations)
  3. Thread Block → Goroutine: Grid/block structures become parallel goroutine work distribution
  4. Cache-Aware Scheduling: Work stealing and tiling optimize for CPU cache hierarchy
  5. Assembly Kernels: Hand-optimized AVX2/FMA assembly for critical mathematical operations

Key Insight: GUDA is NOT a GPU simulator - it's a CPU-optimized implementation providing CUDA API compatibility.

graph LR
    subgraph "GPU Model"
        GRID["Grid<br/>dim3(4,2,1)"]
        BLOCK1["Block(0,0)"]
        BLOCK2["Block(1,0)"]
        BLOCK3["Block(...)"]
        THREAD1["Thread(0)"]
        THREAD2["Thread(1)"]
        THREAD3["Thread(...)"]
        
        GRID --> BLOCK1
        GRID --> BLOCK2
        GRID --> BLOCK3
        BLOCK1 --> THREAD1
        BLOCK1 --> THREAD2
        BLOCK1 --> THREAD3
    end
    
    subgraph "GUDA CPU Mapping"
        CORES["CPU Cores<br/>8 cores"]
        LOOP["Parallel Loops<br/>OpenMP-style"]
        SIMD1["SIMD Lane 0-7<br/>AVX2 256-bit"]
        SIMD2["SIMD Lane 8-15<br/>AVX2 256-bit"]
        
        CORES --> LOOP
        LOOP --> SIMD1
        LOOP --> SIMD2
    end
    
    BLOCK1 -.->|"maps to"| LOOP
    THREAD1 -.->|"maps to"| SIMD1
    
    %% High contrast GPU styling
    classDef gpuGrid fill:#76B900,stroke:#ffffff,stroke-width:3px,color:#ffffff
    classDef gpuBlock fill:#4CAF50,stroke:#ffffff,stroke-width:2px,color:#ffffff
    classDef gpuThread fill:#2E7D32,stroke:#ffffff,stroke-width:2px,color:#ffffff
    
    %% High contrast CPU styling  
    classDef cpuCore fill:#FF6B35,stroke:#ffffff,stroke-width:3px,color:#ffffff
    classDef cpuLoop fill:#E65100,stroke:#ffffff,stroke-width:2px,color:#ffffff
    classDef cpuSIMD fill:#BF360C,stroke:#ffffff,stroke-width:2px,color:#ffffff
    
    class GRID gpuGrid
    class BLOCK1,BLOCK2,BLOCK3 gpuBlock
    class THREAD1,THREAD2,THREAD3 gpuThread
    class CORES cpuCore
    class LOOP cpuLoop
    class SIMD1,SIMD2 cpuSIMD
    
    style GRID fill:#e3f2fd
    style CORES fill:#000000
    style SIMD1 fill:#000000
    style SIMD2 fill:#000000
3.4 High-Performance BLAS Implementation

GUDA's cuBLAS compatibility layer leverages the fully assimilated Gonum mathematical computing library:

Architecture:

  • Native CPU BLAS: Direct calls to optimized CPU BLAS routines, not GPU simulation
  • SIMD Assembly Kernels: Hand-written AVX2/FMA assembly for common matrix sizes (4x4, 8x8, 16x16)
  • Parallel Execution: Goroutine-based work distribution across all CPU cores
  • Memory Hierarchy Optimization: L1/L2/L3 cache-aware algorithms with prefetching

Performance Features:

  • Fused Operations: GEMM+Bias+ReLU and other fused kernels in single operations
  • Float16 Hardware Acceleration: F16C instruction support for half-precision
  • Adaptive Algorithms: Different implementations chosen based on matrix size and cache characteristics
  • Zero Memory Copy: Unified memory eliminates host-device transfer overhead

Performance benchmarks are currently being validated and will be published in future releases.

4. Performance Characteristics

4.1 Experimental Setup

Testing environment:

  • CPU: AMD Ryzen 7 7700X (8 cores, 16 threads)
  • Memory: 32GB DDR5-5600
  • Architecture: x86-64 with AVX2 support
  • Compiler: Go 1.21 with CGO for SIMD intrinsics

Platform Support: This proof-of-concept currently supports x86-64 only. ARM64 and other architectures are not yet implemented.

4.2 Performance Results

GUDA achieves exceptional performance through optimized CPU utilization:

GEMM Performance (Hot Cache)
Matrix Size GFLOPS Efficiency* Arithmetic Intensity
256×256 126.5 126% 42.7 FLOPS/byte
512×512 148.7 149% 85.3 FLOPS/byte
1024×1024 154.2 154% 170.7 FLOPS/byte
2048×2048 153.5 154% 341.3 FLOPS/byte

*Efficiency relative to practical peak of 100 GFLOPS (40% of theoretical 288 GFLOPS)

Memory Bandwidth Operations
Operation Size Performance Memory Bandwidth
AXPY 16K 40.4 GFLOPS 242.3 GB/s
DOT 1K 68.4 GFLOPS 273.7 GB/s

These results demonstrate:

  • Near-peak performance: >150 GFLOPS sustained on compute-bound operations
  • Memory saturation: >240 GB/s achieved (approaching DDR5 theoretical limits)
  • Efficient vectorization: Full AVX2 utilization with 8-wide float32 operations
  • Cache optimization: Hot cache performance with effective blocking

See BENCHMARK_RESULTS.md for detailed performance analysis including cold cache results and performance counter validation.

For guidance on running and interpreting benchmarks, see Benchmarking Guide.

4.3 Convolution Implementation

Our convolution implementation uses the im2col + GEMM approach:

graph LR
    subgraph "Input"
        IMG[Input Image<br/>N×C×H×W]
        KERNEL[Kernels<br/>K×C×R×S]
    end
    
    subgraph "Transform"
        IM2COL[im2col Transform<br/>Unfold patches]
        RESHAPE[Reshape Kernels<br/>K×CRS]
    end
    
    subgraph "Compute"
        GEMM[GEMM<br/>K×CRS × CRS×NHW]
    end
    
    subgraph "Output"
        OUT[Output<br/>N×K×H'×W']
    end
    
    IMG --> IM2COL
    KERNEL --> RESHAPE
    IM2COL --> GEMM
    RESHAPE --> GEMM
    GEMM --> OUT
    
    %% High contrast styling for accessibility
    classDef inputData fill:#2E86AB,stroke:#ffffff,stroke-width:3px,color:#ffffff
    classDef transform fill:#A23B72,stroke:#ffffff,stroke-width:2px,color:#ffffff
    classDef compute fill:#C73E1D,stroke:#ffffff,stroke-width:3px,color:#ffffff
    classDef output fill:#F18F01,stroke:#ffffff,stroke-width:3px,color:#ffffff
    
    class IMG,KERNEL inputData
    class IM2COL,RESHAPE transform
    class GEMM compute
    class OUT output
4.4 Numerical Accuracy

Validation testing indicates:

  • IEEE 754 compliance for floating-point operations
  • Bit-exact results for memory operations
  • Numerical parity with reference implementations for core operations

5. Use Cases and Applications

graph TB
    subgraph "Development Environment"
        DEV_LAPTOP[Developer Laptop<br/>No GPU Required]
        CI_PIPELINE[CI/CD Pipeline<br/>GitHub Actions]
        DEBUG[CPU Debugging Tools<br/>GDB, Valgrind, perf]
    end
    
    subgraph "Production Deployment"
        CLOUD[Cloud CPU Instance<br/>Cost-Optimized]
        EDGE[Edge Device<br/>ARM/x86 CPUs]
        CONTAINER[Container Platform<br/>Docker/Kubernetes]
    end
    
    subgraph "Research & Education"
        EDUCATION[CUDA Learning<br/>Academic Environment]
        PROTOTYPE[Algorithm Prototyping<br/>Rapid Iteration]
        ANALYSIS[Performance Analysis<br/>CPU vs GPU Studies]
    end
    
    subgraph "Application Types"
        INFERENCE[ML Inference<br/>Low-Latency]
        SIMULATION[Scientific Computing<br/>Batch Processing]
        TRAINING[Small Model Training<br/>Development Phase]
    end
    
    DEV_LAPTOP --> CLOUD
    CI_PIPELINE --> CONTAINER
    DEBUG --> ANALYSIS
    
    CLOUD --> INFERENCE
    EDGE --> INFERENCE
    CONTAINER --> SIMULATION
    
    EDUCATION --> PROTOTYPE
    PROTOTYPE --> TRAINING
    ANALYSIS --> SIMULATION
    
    %% High contrast deployment styling
    classDef devEnv fill:#2E7D32,stroke:#ffffff,stroke-width:3px,color:#ffffff
    classDef prodDeploy fill:#1565C0,stroke:#ffffff,stroke-width:3px,color:#ffffff
    classDef research fill:#7B1FA2,stroke:#ffffff,stroke-width:3px,color:#ffffff
    classDef appTypes fill:#D84315,stroke:#ffffff,stroke-width:3px,color:#ffffff
    
    class DEV_LAPTOP,CI_PIPELINE,DEBUG devEnv
    class CLOUD,EDGE,CONTAINER prodDeploy
    class EDUCATION,PROTOTYPE,ANALYSIS research
    class INFERENCE,SIMULATION,TRAINING appTypes
5.1 Development and Testing

GUDA enables:

  • CI/CD pipelines without GPU infrastructure
  • Local development on laptops
  • Debugging with standard CPU tools
5.2 Edge Deployment

Suitable for:

  • Inference on edge devices without GPUs
  • Embedded systems with powerful CPUs
  • Cost-sensitive deployments
5.3 Education and Research

Provides:

  • Accessible CUDA learning environment
  • Algorithm prototyping platform
  • Performance analysis opportunities

6. Limitations and Future Work

6.1 Current Limitations
  • Platform Support: x86-64 only - ARM64, RISC-V, and other architectures not yet supported
  • API Coverage: Limited to CUDA runtime and cuBLAS APIs
  • SIMD Requirements: Requires AVX2 for optimal performance; fallback implementations may be slower
  • No GPU Hardware Features: No support for advanced GPU features (tensor cores, RT cores, etc.)
6.2 Future Directions
  1. Multi-Architecture Support: ARM64 with NEON/SVE, RISC-V with vector extensions
  2. API Coverage: Implement cuDNN, cuFFT, cuSPARSE, and other CUDA libraries
  3. Advanced SIMD: AVX-512 optimizations for Intel processors
  4. Heterogeneous Execution: CPU+GPU cooperative processing for hybrid workloads

7. Conclusion

GUDA demonstrates that CPU-native implementations of GPU APIs can provide practical deployment options for CUDA applications on CPU-only infrastructure. Through unified memory architecture, optimized BLAS integration, and elimination of host-device transfers, GUDA enables running CUDA applications where GPU hardware is unavailable or cost-prohibitive. This proof-of-concept validates the viability of CPU-first architectural approaches for CUDA compatibility and suggests future opportunities for heterogeneous computing strategies.

Installation

System Requirements
  • Architecture: x86-64 processor with AVX2 support (Intel Haswell/AMD Excavator or newer)
  • OS: Linux, macOS, or Windows
  • Go: Version 1.19 or later
  • CGO: Required for SIMD assembly optimizations
Install
go get github.com/LynnColeArt/guda

Note: ARM64 and other architectures are not currently supported in this proof-of-concept.

Usage Example

package main

import (
    "github.com/LynnColeArt/guda"
)

func main() {
    // Initialize GUDA
    guda.Init(0)
    defer guda.Reset()
    
    // Allocate memory
    d_a, _ := guda.Malloc(1024 * 1024 * 4)
    d_b, _ := guda.Malloc(1024 * 1024 * 4)
    d_c, _ := guda.Malloc(1024 * 1024 * 4)
    defer guda.Free(d_a)
    defer guda.Free(d_b)
    defer guda.Free(d_c)
    
    // Perform SGEMM
    guda.GEMM(false, false, 1024, 1024, 1024,
        1.0, d_a, 1024, d_b, 1024,
        0.0, d_c, 1024)
}

License

MIT License - See LICENSE file for details

Citation

If you use GUDA in your research, please cite:

@software{guda2025,
  author = {Lynn Cole},
  title = {GUDA: A High-Performance CPU-Based CUDA-Compatible Linear Algebra Library},
  year = {2025},
  url = {https://github.com/LynnColeArt/guda}
}

Acknowledgments

This work was inspired by the need for accessible high-performance computing and the convergence of CPU and GPU architectures.

Gonum Integration

GUDA incorporates substantial portions of the Gonum project (https://github.com/gonum/gonum), a set of numeric libraries for the Go programming language. The Gonum BLAS implementation forms the foundation of GUDA's linear algebra operations. We are grateful to the Gonum authors and contributors for their excellent work in bringing high-performance numeric computing to Go. The Gonum code is used under the BSD 3-Clause License.

Additional Thanks

Special thanks to:

  • The Go community for providing excellent tools for systems programming
  • The developers of CUDA and cuBLAS for establishing the programming model and APIs
  • The open-source community for fostering collaborative scientific computing

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

View Source
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)

View Source
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

View Source
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

View Source
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

View Source
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

View Source
const (
	// im2col workspace multiplier
	Im2colWorkspaceMultiplier = 2

	// Minimum size for using im2col (below this, use direct convolution)
	Im2colThreshold = 16
)

Convolution parameters

View Source
const (
	// Machine epsilon for float32
	Float32Epsilon = 1.192092896e-07

	// Maximum ULP difference for float32 comparisons
	MaxULPDiff = 4
)

Numerical constants

View Source
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

View Source
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

View Source
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

View Source
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

View Source
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

View Source
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

View Source
const (
	PERF_COUNT_HW_CACHE_OP_READ     = 0
	PERF_COUNT_HW_CACHE_OP_WRITE    = 1
	PERF_COUNT_HW_CACHE_OP_PREFETCH = 2
)
View Source
const (
	PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0
	PERF_COUNT_HW_CACHE_RESULT_MISS   = 1
)
View Source
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

View Source
const (
	// PrefetchRead - Prefetch for read access
	PrefetchRead prefetchMode = iota
	// PrefetchWrite - Prefetch for write access
	PrefetchWrite
)

Variables

View Source
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)
)
View Source
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")
)
View Source
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

View Source
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

View Source
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

View Source
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

func AXPY(alpha float32, x, y DevicePtr, n int) error

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 AbsFloat32

func AbsFloat32(x float32) float32

AbsFloat32 returns absolute value

func Add

func Add(a, b, c DevicePtr, n int) error

Add performs element-wise addition: c = a + b

func AddBFloat16

func AddBFloat16(a, b, c DevicePtr, n int) error

AddBFloat16 performs element-wise addition on BFloat16 arrays

func AddBiasGELU

func AddBiasGELU(x, bias DevicePtr, n int) error

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

func AddBiasReLU(x, bias DevicePtr, n int) error

AddBiasReLU performs x = ReLU(x + bias) in one pass For neural networks: x is [batch_size, output_dim], bias is [output_dim]

func AddFloat16

func AddFloat16(a, b, c DevicePtr, n int) error

AddFloat16 performs element-wise addition on Float16 arrays

func AddFloat16SIMD

func AddFloat16SIMD(a, b, c DevicePtr, n int) error

AddFloat16SIMD uses AVX2+F16C for float16 vector addition

func AlmostEqual

func AlmostEqual(a, b, tolerance float32) bool

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

func BenchmarkWithCounters(b *testing.B, name string, fn func())

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 CumSum

func CumSum(x, out DevicePtr, n int) error

CumSum computes the cumulative sum of elements out[i] = sum(x[0:i+1])

func DOT

func DOT(x, y DevicePtr, n int) (float32, error)

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

func ErfFloat32(x float32) float32

ErfFloat32 computes the error function with good accuracy Uses rational approximation from Abramowitz & Stegun

func ExpFloat32

func ExpFloat32(x float32) float32

ExpFloat32 computes exp(x) with good accuracy for float32 Uses range reduction and polynomial approximation

func FMAFloat16SIMD

func FMAFloat16SIMD(a, b, c, d DevicePtr, n int) error

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

func Float32ULPDiff(a, b float32) int

Float32ULPDiff computes the difference in ULPs between two float32 values

func ForEach

func ForEach(data DevicePtr, size int, fn func(idx int, val *float32)) error

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

func Free(ptr DevicePtr) error

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 GELU

func GELU(x DevicePtr, n int) error

GELU performs the GELU activation in one pass

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

func GeluFloat32Accurate(x float32) float32

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

func GenerateDiagonalMatrix(diagonal []float32) []float32

GenerateDiagonalMatrix generates a diagonal matrix with specified diagonal values. All non-diagonal elements are 0.0.

func GenerateFloat32

func GenerateFloat32(size int, seed uint64) []float32

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

func GenerateFloat32Range(size int, seed uint64, min, max float32) []float32

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

func GenerateIdentityMatrix(size int) []float32

GenerateIdentityMatrix generates an identity matrix of the specified size. Diagonal elements are 1.0, all others are 0.0.

func GenerateMatrixFloat32

func GenerateMatrixFloat32(rows, cols int, seed uint64) []float32

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

func GenerateSequence(size int, start, step float32) []float32

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

func GetLatestLogFile() (string, error)

GetLatestLogFile returns the path to the most recent log file

func HasAVX2

func HasAVX2() bool

HasAVX2 returns true if the CPU supports AVX2 operations

func HasAVX512

func HasAVX512() bool

HasAVX512 returns true if the CPU supports AVX-512 operations needed for GEMM

func InitBenchmarkLogger

func InitBenchmarkLogger(sessionName string) error

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 IsARM64

func IsARM64() bool

IsARM64 returns true if running on ARM64 architecture

func IsDeviceError

func IsDeviceError(err error) bool

IsDeviceError checks if an error is a device error

func IsExecutionError

func IsExecutionError(err error) bool

IsExecutionError checks if an error is an execution error

func IsInvalidArgError

func IsInvalidArgError(err error) bool

IsInvalidArgError checks if an error is an invalid argument error

func IsMemoryError

func IsMemoryError(err error) bool

IsMemoryError checks if an error is a memory error

func IsNotImplementedError

func IsNotImplementedError(err error) bool

IsNotImplementedError checks if an error is a not implemented error

func IsNumericalError

func IsNumericalError(err error) bool

IsNumericalError checks if an error is a numerical error

func Launch

func Launch(kernel Kernel, grid, block Dim3, args ...interface{}) error

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 LayerNorm

func LayerNorm(x DevicePtr, gamma, beta DevicePtr, n int, eps float32) error

LayerNorm performs layer normalization in one pass

func LayerNormFloat16SIMD

func LayerNormFloat16SIMD(input, gamma, beta, output DevicePtr, n, hidden int) error

LayerNormFloat16SIMD performs layer normalization with float16

func LinearFloat16

func LinearFloat16(x DevicePtr, alpha, beta float32, n int) error

LinearFloat16 performs y = alpha*x + beta with Float16

func LinearReLU

func LinearReLU(x DevicePtr, alpha, beta float32, n int) error

LinearReLU performs x = ReLU(alpha*x + beta) in one pass

func LoadTestVector

func LoadTestVector(filename string) ([]float32, error)

LoadTestVector loads a binary test vector file

func LogBenchmarkFail

func LogBenchmarkFail(name string, err error)

LogBenchmarkFail logs a failed benchmark

func LogBenchmarkPass

func LogBenchmarkPass(name string, nsPerOp float64, mbPerSec float64, ops int64)

LogBenchmarkPass logs a successful benchmark

func LogBenchmarkResult

func LogBenchmarkResult(result BenchmarkResult)

LogBenchmarkResult logs a single benchmark result

func LogBenchmarkTimeout

func LogBenchmarkTimeout(name string, duration time.Duration)

LogBenchmarkTimeout logs a timed out benchmark

func LogSumExp

func LogSumExp(x DevicePtr, n int) float32

LogSumExp computes log(sum(exp(x))) in a numerically stable way This is a key operation in many ML algorithms

func Map

func Map(input, output DevicePtr, size int, fn func(float32) float32) error

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 Max

func Max(x DevicePtr, n int) (float32, error)

Max finds the maximum 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 Min

func Min(x DevicePtr, n int) (float32, error)

Min finds the minimum element

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 Multiply

func Multiply(a, b, c DevicePtr, n int) error

Multiply performs element-wise multiplication: c = a * b

func MultiplyFloat16

func MultiplyFloat16(a, b, c DevicePtr, n int) error

MultiplyFloat16 performs element-wise multiplication on Float16 arrays

func MultiplyFloat16SIMD

func MultiplyFloat16SIMD(a, b, c DevicePtr, n int) error

MultiplyFloat16SIMD uses AVX2+F16C for float16 vector multiplication

func NewExecutionError

func NewExecutionError(op string, message string, err error) error

NewExecutionError creates an execution error

func NewInvalidArgError

func NewInvalidArgError(op string, message string) error

NewInvalidArgError creates an invalid argument error

func NewMemoryError

func NewMemoryError(op string, message string, err error) error

NewMemoryError creates a memory-related error

func NewNumericalError

func NewNumericalError(op string, message string, context interface{}) error

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

func PrefetchFloat32(data []float32, index int)

PrefetchFloat32 provides a hint to prefetch float32 data

func PrefetchFloat32Write

func PrefetchFloat32Write(data []float32, index int)

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 ReLU

func ReLU(x DevicePtr, n int) error

ReLU applies the ReLU activation function: x = max(0, x)

func Reduce

func Reduce(data DevicePtr, size int, op func(a, b float32) float32) (float32, error)

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 ReduceMax

func ReduceMax(x DevicePtr, shape []int, axis int, out DevicePtr) error

ReduceMax performs a max reduction along the specified axis

func ReduceSum

func ReduceSum(x DevicePtr, shape []int, axis int, out DevicePtr) error

ReduceSum performs a sum reduction along the specified axis For 2D tensors: axis=0 sums columns, axis=1 sums rows

func Scale

func Scale(alpha float32, x DevicePtr, n int) error

Scale multiplies all elements by a scalar: x = alpha * x

func SegmentSum

func SegmentSum(data DevicePtr, segmentIds []int, nSegments int, out DevicePtr) error

SegmentSum computes the sum of segments defined by segment_ids Essential for graph neural networks and attention mechanisms

func SetDevice

func SetDevice(id int) error

SetDevice sets the active device (no-op for CPU)

func Sigmoid

func Sigmoid(x DevicePtr, n int) error

Sigmoid applies the sigmoid activation function

func SigmoidFloat32

func SigmoidFloat32(x float32) float32

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

func SimdF16ToF32(src []uint16, dst []float32)

SimdF16ToF32 converts float16 to float32 using F16C instructions

func SimdF32ToF16

func SimdF32ToF16(src []float32, dst []uint16)

SimdF32ToF16 converts float32 to float16 using F16C instructions

func SlicesAlmostEqual

func SlicesAlmostEqual(a, b []float32, tolerance float32) bool

SlicesAlmostEqual checks if two float32 slices are approximately equal element-wise within the specified tolerance.

func Softmax

func Softmax(x DevicePtr, n int) error

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

func StreamingPrefetch(data []float32, currentIdx int)

StreamingPrefetch implements software prefetching for streaming patterns This is optimized for sequential access like AXPY, DOT operations

func StreamingPrefetchDual

func StreamingPrefetchDual(x, y []float32, currentIdx int)

StreamingPrefetchDual prefetches from two arrays simultaneously Useful for operations like DOT, AXPY that read two arrays

func Sum

func Sum(x DevicePtr, n int) (float32, error)

Sum computes the sum of all elements

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

func SynchronizeOrFail(t testing.TB)

SynchronizeOrFail synchronizes and fails the test if unsuccessful

func TanhFloat32

func TanhFloat32(x float32) float32

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

func TestWithCUDAVectors(t *testing.T)

TestWithCUDAVectors runs GUDA against CUDA/ROCm reference vectors

func TiledPrefetch

func TiledPrefetch(data []float32, tileStartIdx, tileSize int)

TiledPrefetch implements prefetching for blocked algorithms Used in GEMM and other tiled operations

func TopK

func TopK(x DevicePtr, n, k int) (values []float32, indices []int, err error)

TopK finds the k largest elements and their indices Returns values and indices in descending order

func ULPDiffFloat32

func ULPDiffFloat32(a, b float32) int32

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

func ToBFloat16(f float32) BFloat16

ToBFloat16 converts float32 to BFloat16 (truncate mantissa)

func (BFloat16) ToFloat32

func (b BFloat16) ToFloat32() float32

ToFloat32 converts BFloat16 to float32

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

func (*CacheObliviousGEMM) Compute

func (cog *CacheObliviousGEMM) Compute(
	alpha float32,
	a []float32, lda int, aRows, aCols int,
	b []float32, ldb int, bRows, bCols int,
	beta float32,
	c []float32, ldc int,
)

Compute performs C = alpha * A * B + beta * C using recursive subdivision

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

func (*CacheObliviousGEMMParallel) Compute

func (cogp *CacheObliviousGEMMParallel) Compute(
	alpha float32,
	a []float32, lda int, aRows, aCols int,
	b []float32, ldb int, bRows, bCols int,
	beta float32,
	c []float32, ldc int,
)

Compute performs 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

func (ctx *Context) CreateStream() *Stream

CreateStream creates a new execution stream

func (*Context) Free

func (ctx *Context) Free(ptr DevicePtr) error

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

func (ctx *Context) Launch(kernel Kernel, grid, block Dim3, args ...interface{}) error

Launch executes a kernel on the default stream

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

func (ctx *Context) Malloc(size int) (DevicePtr, error)

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

func (ctx *Context) Synchronize() error

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

func GetDeviceProperties(id int) (*Device, error)

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

func Malloc(size int) (DevicePtr, error)

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

func MallocOrFail(t testing.TB, size int) DevicePtr

MallocOrFail allocates device memory and fails the test if unsuccessful

func (DevicePtr) ArgMax

func (d DevicePtr) ArgMax(n int) int

ArgMax returns the index of the maximum value in x

func (DevicePtr) ArgMin

func (d DevicePtr) ArgMin(n int) int

ArgMin returns the index of the minimum value in x

func (DevicePtr) BFloat16

func (d DevicePtr) BFloat16() BFloat16Slice

BFloat16 returns a BFloat16 slice view of the memory

func (DevicePtr) Byte

func (d DevicePtr) Byte() []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

func (d DevicePtr) Float32() []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

func (d DevicePtr) Float64() []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

func (d DevicePtr) Int32() []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) Max

func (d DevicePtr) Max(n int) float32

Max returns the maximum value in x

func (DevicePtr) Mean

func (d DevicePtr) Mean(n int) float32

Mean computes the arithmetic mean of all elements

func (DevicePtr) Min

func (d DevicePtr) Min(n int) float32

Min returns the minimum value in x

func (DevicePtr) Offset

func (d DevicePtr) Offset(bytes int) DevicePtr

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

func (d DevicePtr) Product(n int) float32

Product computes the product of all elements

func (DevicePtr) Size

func (d DevicePtr) Size() int

Size returns the size in bytes of the memory region

func (DevicePtr) Sum

func (d DevicePtr) Sum(n int) float32

Sum computes the sum of all elements in x

func (DevicePtr) SumSquares

func (d DevicePtr) SumSquares(n int) float32

SumSquares computes the sum of squares of all elements Useful for L2 norm computation

func (DevicePtr) Variance

func (d DevicePtr) Variance(n int) float32

Variance computes the variance of all elements Uses Welford's online algorithm for numerical stability

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.

func (Dim3) Size

func (d Dim3) Size() int

Size returns the total number of elements

type ErrorType

type ErrorType int

ErrorType represents categories of errors

const (
	// Memory errors
	ErrTypeMemory ErrorType = iota
	// Invalid argument errors
	ErrTypeInvalidArg
	// Execution errors
	ErrTypeExecution
	// Numerical errors
	ErrTypeNumerical
	// Device errors
	ErrTypeDevice
	// Not implemented errors
	ErrTypeNotImplemented
)

func (ErrorType) String

func (t ErrorType) String() string

String returns the error type as a string

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
	SharedMemorySize int64 // Bytes

	// 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 NewFFUDetector

func NewFFUDetector() *FFUDetector

NewFFUDetector creates a new 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 Float16

type Float16 uint16

Float16 represents a 16-bit floating point number

func FromFloat32

func FromFloat32(f float32) Float16

FromFloat32 converts float32 to Float16

func (Float16) ToFloat32

func (f Float16) ToFloat32() float32

ToFloat32 converts Float16 to float32

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

func (fk *FusedKernel) Execute(x DevicePtr, others []DevicePtr, n int, shapes ...[]int) error

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

func (*FusedKernel) ReLU

func (fk *FusedKernel) ReLU() *FusedKernel

ReLU adds ReLU activation

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

  1. Q = X @ W_q
  2. K = X @ W_k
  3. V = X @ W_v
  4. Attention = Softmax(Q @ K^T / sqrt(d_k)) @ V
  5. Output = Attention @ W_o
  6. 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

func (*GUDAError) Error

func (e *GUDAError) Error() string

Error implements the error interface

func (*GUDAError) Unwrap

func (e *GUDAError) Unwrap() error

Unwrap allows error chain inspection

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 MathOp

type MathOp int

MathOp represents a mathematical operation

const (
	OpAdd MathOp = iota
	OpSub
	OpMul
	OpDiv
	OpMax
	OpMin
)

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

type OperationTolerance struct {
	Name   string
	AbsTol float32
	RelTol float32
	ULPTol int32
}

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

func (r Reference) ASUM(x []float32) float32

ASUMRef computes the sum of absolute values (reference implementation)

func (Reference) AXPY

func (r Reference) AXPY(alpha float32, x, y []float32)

AXPYRef performs y = alpha*x + y (reference implementation)

func (Reference) Add

func (r Reference) Add(a, b, c []float32)

AddRef performs element-wise addition: c = a + b

func (Reference) AddBiasReLU

func (r Reference) AddBiasReLU(x, bias []float32, n, biasLen int)

AddBiasReLURef performs x = ReLU(x + bias) where bias is broadcast

func (Reference) ArgMax

func (r Reference) ArgMax(x []float32) int

ArgMaxRef finds the index of the maximum element

func (Reference) ArgMin

func (r Reference) ArgMin(x []float32) int

ArgMinRef finds the index of the minimum element

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

func (r Reference) DOT(x, y []float32) float32

DOTRef computes dot product of x and y (reference implementation)

func (Reference) Div

func (r Reference) Div(a, b, c []float32)

DivRef performs element-wise division: c = a / b

func (Reference) GELU

func (r Reference) GELU(x []float32)

GELURef applies GELU activation using the accurate formula

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

func (r Reference) LayerNorm(x []float32, gamma, beta []float32, eps float32)

LayerNormRef applies layer normalization

func (Reference) LinearReLU

func (r Reference) LinearReLU(x []float32, alpha, beta float32)

LinearReLURef performs x = ReLU(alpha*x + beta)

func (Reference) Max

func (r Reference) Max(x []float32) float32

MaxRef finds the maximum element

func (Reference) Min

func (r Reference) Min(x []float32) float32

MinRef finds the minimum element

func (Reference) Mul

func (r Reference) Mul(a, b, c []float32)

MulRef performs element-wise multiplication: c = a * b

func (Reference) NRM2

func (r Reference) NRM2(x []float32) float32

NRM2Ref computes the 2-norm of vector x (reference implementation)

func (Reference) ReLU

func (r Reference) ReLU(x []float32)

ReLURef applies ReLU activation: y = max(0, x)

func (Reference) Scale

func (r Reference) Scale(alpha float32, x []float32)

ScaleRef performs x = alpha*x (reference implementation)

func (Reference) Sigmoid

func (r Reference) Sigmoid(x []float32)

SigmoidRef applies sigmoid activation: y = 1 / (1 + exp(-x))

func (Reference) Softmax

func (r Reference) Softmax(x []float32)

SoftmaxRef applies softmax: y[i] = exp(x[i]) / sum(exp(x))

func (Reference) Sub

func (r Reference) Sub(a, b, c []float32)

SubRef performs element-wise subtraction: c = a - b

func (Reference) Sum

func (r Reference) Sum(x []float32) float32

SumRef computes the sum of all elements

func (Reference) Tanh

func (r Reference) Tanh(x []float32)

TanhRef applies tanh activation

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

func (s *Stream) Submit(task func())

Submit adds a task to the stream

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

func (*StreamingGEMM) Compute

func (sg *StreamingGEMM) Compute(
	alpha float32,
	a []float32, lda int, m, k int,
	b []float32, ldb int, k2, n int,
	beta float32,
	c []float32, ldc int,
)

Compute performs C = alpha * A * B + beta * C using a streaming approach that maximizes cache reuse

type Tensor

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

Tensor represents a multi-dimensional array for GUDA operations

func AllocateTensor

func AllocateTensor(shape []int) *Tensor

AllocateTensor creates a new tensor with the given shape

func (*Tensor) Shape

func (t *Tensor) Shape() []int

Shape returns the shape of the tensor

type TestCase

type TestCase struct {
	Name  string
	Input []float32
}

TestCase represents a single test input

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.

func (ThreadID) Global

func (tid ThreadID) Global() int

Global returns the global thread index

func (ThreadID) GlobalX

func (tid ThreadID) GlobalX() int

GlobalX returns the global X index

func (ThreadID) GlobalY

func (tid ThreadID) GlobalY() int

GlobalY returns the global Y index

func (ThreadID) GlobalZ

func (tid ThreadID) GlobalZ() int

GlobalZ returns the global Z index

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

func (wp *WorkerPool) Close()

Close shuts down the worker pool

func (*WorkerPool) Submit

func (wp *WorkerPool) Submit(task func())

Submit adds a task to the pool

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_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
ffu
amx
sha
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.

Jump to

Keyboard shortcuts

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