Wednesday, November 25, 2026

BUILDING A HIGH-PERFORMANCE LLM INFERENCE ENGINE FROM SCRATCH IN GO

 


INTRODUCTION: THE JOURNEY TO UNDERSTANDING LLM INFERENCE

Large Language Models have transformed how we interact with computers, but their inner workings remain mysterious to many developers. While frameworks like llama.cpp and vLLM provide excellent inference capabilities, building your own inference engine from scratch offers profound insights into how these models actually work. This article takes you on a comprehensive journey through creating a production-ready LLM inference engine in Go, designed with clean architecture principles, hardware acceleration, and extensibility at its core. This won‘t be a usable inference engine, as I have to leave out some implementation details. But it will provide the idea of inference engines.

Why Go for LLM inference? Go offers excellent performance characteristics, built-in concurrency primitives, and a simple deployment model. Unlike Python, Go compiles to native binaries, making distribution straightforward. The language's strong typing helps catch errors early, and its memory management strikes a balance between manual control and garbage collection convenience. While Go is not traditionally associated with GPU computing, it provides excellent CGO support for interfacing with CUDA, Metal, ROCm, and other GPU libraries, allowing us to leverage hardware acceleration while maintaining Go's clean syntax and robust tooling.

Our inference engine will support multiple model formats through an adapter pattern, handle various quantization schemes, automatically detect and utilize available GPU hardware, and provide optimization opportunities at every layer. The engine intelligently selects the best available compute backend, whether that is Apple Metal Performance Shaders on macOS, NVIDIA CUDA on Linux workstations, AMD ROCm on AMD hardware, Intel's oneAPI, or optimized CPU operations when no GPU is available. By the end of this article, you will understand not just how to use LLMs, but how they actually execute, token by token, layer by layer, across diverse hardware platforms.

UNDERSTANDING LLM INFERENCE: THE FUNDAMENTAL CONCEPTS

Before writing any code, we must understand what happens when an LLM generates text. At its core, inference is a repeated process of mathematical transformations. The model receives a sequence of tokens as input, processes them through multiple layers of neural network operations, and produces probability distributions over the next possible token.

Each transformer layer performs several operations. First, the attention mechanism computes relationships between all tokens in the sequence. This involves matrix multiplications with query, key, and value weight matrices. Second, a feed-forward network processes each token's representation independently. Third, normalization layers stabilize the values flowing through the network. Finally, residual connections allow gradients to flow backward during training and information to flow forward during inference.

The computational pattern repeats for every layer in the model. A model with thirty-two layers processes the same input sequence thirty-two times, each time refining the representation. The final layer's output goes through a language modeling head that projects the hidden states to vocabulary logits, representing the probability of each possible next token.

Understanding this flow is crucial because our inference engine must orchestrate these operations efficiently. Every matrix multiplication, every activation function, every normalization step must execute correctly and quickly. The computational intensity of these operations makes GPU acceleration essential for practical performance. A single matrix multiplication in a large language model might involve billions of floating-point operations, a task that GPUs excel at through massive parallelism.

ARCHITECTURAL VISION: DESIGNING FOR EXTENSIBILITY AND PERFORMANCE

Our inference engine follows clean architecture principles with clear separation of concerns. The architecture consists of several layers, each with distinct responsibilities. The foundation layer defines core types and interfaces. The hardware abstraction layer provides a unified interface to different compute backends. The tensor layer provides computational primitives that work across all backends. The model layer handles weights and architecture. The adapter layer enables format flexibility. The quantization layer optimizes memory usage. The inference layer orchestrates execution.

This separation allows us to modify or extend any component without affecting others. Want to add a new model format? Implement a new adapter. Need a different quantization scheme? Add a new quantizer. Want to support a new GPU architecture? Implement a new compute backend. This flexibility proves invaluable as the LLM landscape evolves rapidly.

The hardware abstraction layer deserves special attention. It provides a unified interface that hides the complexity of different GPU APIs. Whether we are calling CUDA kernels, Metal shaders, ROCm functions, or CPU BLAS routines, the higher layers see the same interface. This design allows us to write the inference logic once and have it work across all supported hardware platforms.

Let us begin building from the ground up, starting with the foundational types that everything else depends upon.

FOUNDATION LAYER: CORE TYPES AND INTERFACES

Every inference engine needs fundamental building blocks. We start by defining what a tensor is in our system. A tensor represents a multi-dimensional array of numbers with a specific data type and shape. Our tensor abstraction must support various data types because different quantization schemes use different numeric representations.

package inference

import (
    "fmt"
)

// DataType represents the numeric type of tensor elements
// We support multiple types to enable various quantization schemes
type DataType int

const (
    Float32 DataType = iota  // Standard 32-bit floating point
    Float16                  // Half precision for memory savings
    Int8                     // 8-bit integer quantization
    Int4                     // 4-bit integer quantization (packed)
    BFloat16                 // Brain floating point format
)

// String provides human-readable data type names for debugging
func (dt DataType) String() string {
    switch dt {
    case Float32:
        return "float32"
    case Float16:
        return "float16"
    case Int8:
        return "int8"
    case Int4:
        return "int4"
    case BFloat16:
        return "bfloat16"
    default:
        return "unknown"
    }
}

// BytesPerElement returns how many bytes each element occupies
// This is crucial for memory allocation and buffer sizing
func (dt DataType) BytesPerElement() int {
    switch dt {
    case Float32:
        return 4
    case Float16:
        return 2
    case Int8:
        return 1
    case Int4:
        return 1  // Two elements packed per byte
    case BFloat16:
        return 2
    default:
        return 0
    }
}

The DataType enumeration forms the foundation of our type system. Each data type has different memory requirements and computational characteristics. Float32 provides maximum precision but uses the most memory. Int4 uses minimal memory but requires careful handling during computation. The BytesPerElement method helps us calculate buffer sizes accurately, which becomes especially important when allocating GPU memory where every byte counts.

Now we define the tensor structure itself. A tensor combines raw data with metadata describing its shape and type. The shape determines how we interpret the flat array of bytes as a multi-dimensional structure. Critically, our tensor design must support both CPU and GPU memory, requiring us to track where the data actually resides.

// DeviceType indicates where tensor data is stored
// This allows us to track whether data is on CPU or GPU
type DeviceType int

const (
    DeviceCPU DeviceType = iota  // Data in system RAM
    DeviceCUDA                   // Data in NVIDIA GPU memory
    DeviceMetal                  // Data in Apple GPU memory
    DeviceROCm                   // Data in AMD GPU memory
    DeviceOneAPI                 // Data in Intel GPU memory
)

// String provides human-readable device names
func (d DeviceType) String() string {
    switch d {
    case DeviceCPU:
        return "CPU"
    case DeviceCUDA:
        return "CUDA"
    case DeviceMetal:
        return "Metal"
    case DeviceROCm:
        return "ROCm"
    case DeviceOneAPI:
        return "OneAPI"
    default:
        return "Unknown"
    }
}

// Tensor represents a multi-dimensional array with typed elements
// This is the fundamental data structure for all model weights and activations
type Tensor struct {
    Data     []byte       // Raw bytes storing the tensor elements (CPU memory)
    GPUData  interface{}  // Opaque handle to GPU memory (type depends on backend)
    Shape    []int        // Dimensions of the tensor (e.g., [batch, seq, hidden])
    DType    DataType     // Type of elements stored in Data
    Strides  []int        // Byte offsets for each dimension (for efficient indexing)
    Device   DeviceType   // Where the data currently resides
}

// NewTensor creates a tensor with the specified shape and data type
// It allocates the necessary memory and initializes strides for indexing
// By default, tensors are created on CPU
func NewTensor(shape []int, dtype DataType) *Tensor {
    // Calculate total number of elements
    numElements := 1
    for _, dim := range shape {
        numElements *= dim
    }
    
    // Calculate bytes needed based on data type
    bytesPerElem := dtype.BytesPerElement()
    var totalBytes int
    
    if dtype == Int4 {
        // Int4 packs two elements per byte
        totalBytes = (numElements + 1) / 2
    } else {
        totalBytes = numElements * bytesPerElem
    }
    
    // Calculate strides for efficient multi-dimensional indexing
    strides := make([]int, len(shape))
    stride := bytesPerElem
    for i := len(shape) - 1; i >= 0; i-- {
        strides[i] = stride
        stride *= shape[i]
    }
    
    return &Tensor{
        Data:    make([]byte, totalBytes),
        GPUData: nil,
        Shape:   shape,
        DType:   dtype,
        Strides: strides,
        Device:  DeviceCPU,
    }
}

// NumElements returns the total number of elements in the tensor
func (t *Tensor) NumElements() int {
    if len(t.Shape) == 0 {
        return 0
    }
    n := 1
    for _, dim := range t.Shape {
        n *= dim
    }
    return n
}

// Reshape changes the tensor's shape without copying data
// The new shape must have the same total number of elements
func (t *Tensor) Reshape(newShape []int) error {
    // Verify the new shape has the same number of elements
    oldElements := t.NumElements()
    newElements := 1
    for _, dim := range newShape {
        newElements *= dim
    }
    
    if oldElements != newElements {
        return fmt.Errorf("cannot reshape tensor with %d elements to shape with %d elements",
            oldElements, newElements)
    }
    
    // Update shape and recalculate strides
    t.Shape = newShape
    stride := t.DType.BytesPerElement()
    t.Strides = make([]int, len(newShape))
    for i := len(newShape) - 1; i >= 0; i-- {
        t.Strides[i] = stride
        stride *= newShape[i]
    }
    
    return nil
}

// IsOnGPU checks if the tensor data is currently on GPU
func (t *Tensor) IsOnGPU() bool {
    return t.Device != DeviceCPU
}

The Tensor structure now includes device tracking. The Data field holds CPU memory, while GPUData holds an opaque handle to GPU memory. We use interface{} for GPUData because different GPU backends use different handle types. CUDA uses pointers, Metal uses buffer objects, and so on. The Device field tracks where the current valid data resides, which is crucial for managing data transfers between CPU and GPU.

With tensors defined, we need interfaces for operations. The inference engine must perform matrix multiplications, element-wise operations, and various transformations. Rather than implementing everything in one monolithic structure, we define interfaces that different backends can implement.

// TensorOps defines the interface for tensor operations
// Different implementations can optimize for CPU, GPU, or specific hardware
type TensorOps interface {
    // GetDeviceType returns which device this implementation targets
    GetDeviceType() DeviceType
    
    // IsAvailable checks if this backend can actually run on the current system
    IsAvailable() bool
    
    // ToDevice moves a tensor to this backend's device
    // This may involve copying data from CPU to GPU or between GPUs
    ToDevice(t *Tensor) error
    
    // ToCPU moves a tensor back to CPU memory
    ToCPU(t *Tensor) error
    
    // MatMul performs matrix multiplication: C = A * B
    // A has shape [m, k], B has shape [k, n], result has shape [m, n]
    MatMul(a, b *Tensor) (*Tensor, error)
    
    // Add performs element-wise addition: C = A + B
    Add(a, b *Tensor) (*Tensor, error)
    
    // Multiply performs element-wise multiplication: C = A * B
    Multiply(a, b *Tensor) (*Tensor, error)
    
    // ReLU applies the Rectified Linear Unit activation function
    // ReLU(x) = max(0, x) for each element
    ReLU(input *Tensor) (*Tensor, error)
    
    // GELU applies the Gaussian Error Linear Unit activation
    // This is commonly used in transformer models
    GELU(input *Tensor) (*Tensor, error)
    
    // Softmax computes the softmax function along the last dimension
    // This normalizes logits to probability distributions
    Softmax(input *Tensor) (*Tensor, error)
    
    // LayerNorm applies layer normalization with learned scale and bias
    LayerNorm(input, gamma, beta *Tensor, epsilon float32) (*Tensor, error)
    
    // Synchronize waits for all pending operations to complete
    // This is important for GPU backends that execute asynchronously
    Synchronize() error
}

The TensorOps interface now includes device management methods. The IsAvailable method allows runtime detection of available hardware. The ToDevice and ToCPU methods handle data movement between different memory spaces. The Synchronize method is crucial for GPU backends because GPU operations often execute asynchronously, and we need to ensure completion before reading results.

HARDWARE ABSTRACTION LAYER: DETECTING AND MANAGING COMPUTE BACKENDS

Before implementing specific backends, we need a system to detect available hardware and select the best option. This hardware abstraction layer provides automatic backend selection with fallback to CPU when no GPU is available.

package inference

import (
    "fmt"
    "sync"
)

// ComputeBackend manages the available tensor operation implementations
// It automatically detects and selects the best available hardware
type ComputeBackend struct {
    backends     []TensorOps
    selectedOps  TensorOps
    mu           sync.RWMutex
}

// NewComputeBackend creates a new backend manager and detects available hardware
// It tries GPU backends in order of preference, falling back to CPU
func NewComputeBackend() (*ComputeBackend, error) {
    cb := &ComputeBackend{
        backends: make([]TensorOps, 0),
    }
    
    // Try to initialize GPU backends in order of preference
    // The order reflects typical performance characteristics
    
    // Try CUDA (NVIDIA GPUs) - often the fastest for ML workloads
    if cudaOps := NewCUDAOps(); cudaOps != nil && cudaOps.IsAvailable() {
        cb.backends = append(cb.backends, cudaOps)
        fmt.Printf("CUDA backend available and initialized\n")
    }
    
    // Try Metal (Apple GPUs) - excellent on Apple Silicon
    if metalOps := NewMetalOps(); metalOps != nil && metalOps.IsAvailable() {
        cb.backends = append(cb.backends, metalOps)
        fmt.Printf("Metal backend available and initialized\n")
    }
    
    // Try ROCm (AMD GPUs) - good performance on AMD hardware
    if rocmOps := NewROCmOps(); rocmOps != nil && rocmOps.IsAvailable() {
        cb.backends = append(cb.backends, rocmOps)
        fmt.Printf("ROCm backend available and initialized\n")
    }
    
    // Try OneAPI (Intel GPUs) - for Intel discrete and integrated GPUs
    if oneapiOps := NewOneAPIOps(); oneapiOps != nil && oneapiOps.IsAvailable() {
        cb.backends = append(cb.backends, oneapiOps)
        fmt.Printf("OneAPI backend available and initialized\n")
    }
    
    // Always add CPU backend as fallback
    cpuOps := NewCPUTensorOps()
    cb.backends = append(cb.backends, cpuOps)
    fmt.Printf("CPU backend available\n")
    
    // Select the first available backend (highest priority)
    if len(cb.backends) > 0 {
        cb.selectedOps = cb.backends[0]
        fmt.Printf("Selected backend: %s\n", cb.selectedOps.GetDeviceType())
    } else {
        return nil, fmt.Errorf("no compute backends available")
    }
    
    return cb, nil
}

// GetOps returns the currently selected tensor operations implementation
func (cb *ComputeBackend) GetOps() TensorOps {
    cb.mu.RLock()
    defer cb.mu.RUnlock()
    return cb.selectedOps
}

// GetDeviceType returns the type of the currently selected device
func (cb *ComputeBackend) GetDeviceType() DeviceType {
    return cb.GetOps().GetDeviceType()
}

// SetPreferredDevice allows manual override of backend selection
// This is useful for testing or when users want to force CPU execution
func (cb *ComputeBackend) SetPreferredDevice(device DeviceType) error {
    cb.mu.Lock()
    defer cb.mu.Unlock()
    
    for _, backend := range cb.backends {
        if backend.GetDeviceType() == device && backend.IsAvailable() {
            cb.selectedOps = backend
            fmt.Printf("Switched to %s backend\n", device)
            return nil
        }
    }
    
    return fmt.Errorf("backend for device %s not available", device)
}

// ListAvailableDevices returns all available compute devices
func (cb *ComputeBackend) ListAvailableDevices() []DeviceType {
    devices := make([]DeviceType, 0, len(cb.backends))
    for _, backend := range cb.backends {
        if backend.IsAvailable() {
            devices = append(devices, backend.GetDeviceType())
        }
    }
    return devices
}

The ComputeBackend structure manages multiple backend implementations and selects the best one automatically. The initialization order reflects typical performance characteristics, with CUDA first for NVIDIA GPUs, Metal for Apple Silicon, ROCm for AMD, OneAPI for Intel, and CPU as the universal fallback. This design ensures that users get the best performance available on their hardware without manual configuration.

The SetPreferredDevice method allows users to override automatic selection. This proves useful during development, testing, or when debugging performance issues. The ListAvailableDevices method helps users understand what hardware their system supports.

TENSOR OPERATIONS: CPU IMPLEMENTATION

With the foundation in place, we implement the actual tensor operations. We start with a CPU-based implementation that prioritizes correctness and clarity. This implementation serves as both a fallback when no GPU is available and a reference implementation for testing GPU backends.

package inference

import (
    "fmt"
    "math"
)

// CPUTensorOps implements TensorOps for CPU execution
// This implementation prioritizes correctness and serves as a fallback
type CPUTensorOps struct {
    // We could add configuration options here, such as
    // number of threads or BLAS library selection
}

// NewCPUTensorOps creates a new CPU-based tensor operations backend
func NewCPUTensorOps() *CPUTensorOps {
    return &CPUTensorOps{}
}

// GetDeviceType returns the device type this backend targets
func (ops *CPUTensorOps) GetDeviceType() DeviceType {
    return DeviceCPU
}

// IsAvailable checks if CPU backend is available (always true)
func (ops *CPUTensorOps) IsAvailable() bool {
    return true
}

// ToDevice ensures tensor is on CPU (no-op if already on CPU)
func (ops *CPUTensorOps) ToDevice(t *Tensor) error {
    if t.Device == DeviceCPU {
        return nil  // Already on CPU
    }
    
    // This would need to copy from GPU to CPU
    // For now, we assume tensor is already on CPU
    return fmt.Errorf("CPU backend cannot directly access %s memory", t.Device)
}

// ToCPU ensures tensor is on CPU (no-op for CPU backend)
func (ops *CPUTensorOps) ToCPU(t *Tensor) error {
    return ops.ToDevice(t)
}

// Synchronize waits for operations to complete (no-op for CPU)
func (ops *CPUTensorOps) Synchronize() error {
    return nil  // CPU operations are synchronous
}

// MatMul performs matrix multiplication on CPU
// This is a naive implementation; we will optimize it later
func (ops *CPUTensorOps) MatMul(a, b *Tensor) (*Tensor, error) {
    // Validate input shapes
    if len(a.Shape) != 2 || len(b.Shape) != 2 {
        return nil, fmt.Errorf("matmul requires 2D tensors, got shapes %v and %v",
            a.Shape, b.Shape)
    }
    
    m, k1 := a.Shape[0], a.Shape[1]
    k2, n := b.Shape[0], b.Shape[1]
    
    if k1 != k2 {
        return nil, fmt.Errorf("incompatible shapes for matmul: [%d,%d] and [%d,%d]",
            m, k1, k2, n)
    }
    
    // Create output tensor
    result := NewTensor([]int{m, n}, Float32)
    
    // Convert inputs to float32 for computation
    aFloat := ops.toFloat32(a)
    bFloat := ops.toFloat32(b)
    resultData := make([]float32, m*n)
    
    // Perform matrix multiplication
    // For each row in A and each column in B
    for i := 0; i < m; i++ {
        for j := 0; j < n; j++ {
            var sum float32
            // Compute dot product of row i from A and column j from B
            for k := 0; k < k1; k++ {
                sum += aFloat[i*k1+k] * bFloat[k*n+j]
            }
            resultData[i*n+j] = sum
        }
    }
    
    // Copy result data into tensor
    ops.float32ToBytes(resultData, result.Data)
    
    return result, nil
}

// toFloat32 converts a tensor to float32 representation
// This handles dequantization for quantized types
func (ops *CPUTensorOps) toFloat32(t *Tensor) []float32 {
    numElements := t.NumElements()
    result := make([]float32, numElements)
    
    switch t.DType {
    case Float32:
        // Direct copy from bytes to float32
        for i := 0; i < numElements; i++ {
            result[i] = ops.bytesToFloat32(t.Data[i*4 : (i+1)*4])
        }
        
    case Float16:
        // Convert from 16-bit to 32-bit float
        for i := 0; i < numElements; i++ {
            result[i] = ops.float16ToFloat32(t.Data[i*2 : (i+1)*2])
        }
        
    case Int8:
        // Dequantize from 8-bit integer
        // This is a simplified version; real quantization uses scale factors
        for i := 0; i < numElements; i++ {
            result[i] = float32(int8(t.Data[i])) / 127.0
        }
        
    case Int4:
        // Dequantize from 4-bit integer (two values per byte)
        for i := 0; i < numElements; i++ {
            byteIdx := i / 2
            if i%2 == 0 {
                // Lower 4 bits
                val := int8(t.Data[byteIdx] & 0x0F)
                if val > 7 {
                    val -= 16  // Handle sign extension
                }
                result[i] = float32(val) / 7.0
            } else {
                // Upper 4 bits
                val := int8(t.Data[byteIdx] >> 4)
                if val > 7 {
                    val -= 16
                }
                result[i] = float32(val) / 7.0
            }
        }
    }
    
    return result
}

// bytesToFloat32 converts 4 bytes to a float32 value
func (ops *CPUTensorOps) bytesToFloat32(b []byte) float32 {
    bits := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
    return math.Float32frombits(bits)
}

// float16ToFloat32 converts IEEE 754 float16 to float32
func (ops *CPUTensorOps) float16ToFloat32(b []byte) float32 {
    bits := uint16(b[0]) | uint16(b[1])<<8
    
    // Extract sign, exponent, and mantissa
    sign := uint32((bits >> 15) & 0x1)
    exponent := uint32((bits >> 10) & 0x1F)
    mantissa := uint32(bits & 0x3FF)
    
    var result uint32
    
    if exponent == 0 {
        if mantissa == 0 {
            // Zero
            result = sign << 31
        } else {
            // Denormalized number
            exponent = 1
            for (mantissa & 0x400) == 0 {
                mantissa <<= 1
                exponent--
            }
            mantissa &= 0x3FF
            result = (sign << 31) | ((exponent + 112) << 23) | (mantissa << 13)
        }
    } else if exponent == 31 {
        // Infinity or NaN
        result = (sign << 31) | 0x7F800000 | (mantissa << 13)
    } else {
        // Normalized number
        result = (sign << 31) | ((exponent + 112) << 23) | (mantissa << 13)
    }
    
    return math.Float32frombits(result)
}

// float32ToBytes converts float32 values to bytes
func (ops *CPUTensorOps) float32ToBytes(data []float32, dest []byte) {
    for i, val := range data {
        bits := math.Float32bits(val)
        dest[i*4] = byte(bits)
        dest[i*4+1] = byte(bits >> 8)
        dest[i*4+2] = byte(bits >> 16)
        dest[i*4+3] = byte(bits >> 24)
    }
}

The MatMul implementation follows the standard triple-nested loop algorithm. While not optimized, it correctly computes the matrix product. The toFloat32 method handles dequantization, converting various numeric formats to float32 for computation. This approach trades some performance for simplicity and correctness.

Notice how we handle Int4 quantization. Two 4-bit values pack into each byte, requiring careful bit manipulation to extract them. The sign extension logic ensures negative values decode correctly. Real quantization schemes use scale and zero-point parameters, but this simplified version illustrates the concept clearly.

Next, we implement activation functions. These non-linear transformations give neural networks their power to model complex patterns.

// GELU applies the Gaussian Error Linear Unit activation function
// GELU(x) = x * Phi(x) where Phi is the cumulative distribution function
// We use the approximation: GELU(x) approximately equals 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3)))
func (ops *CPUTensorOps) GELU(input *Tensor) (*Tensor, error) {
    numElements := input.NumElements()
    result := NewTensor(input.Shape, Float32)
    
    // Convert input to float32
    inputFloat := ops.toFloat32(input)
    outputFloat := make([]float32, numElements)
    
    // Apply GELU to each element
    for i := 0; i < numElements; i++ {
        x := inputFloat[i]
        // Use the tanh approximation for GELU
        inner := math.Sqrt(2.0/math.Pi) * (x + 0.044715*x*x*x)
        outputFloat[i] = 0.5 * x * (1.0 + float32(math.Tanh(float64(inner))))
    }
    
    ops.float32ToBytes(outputFloat, result.Data)
    return result, nil
}

// ReLU applies the Rectified Linear Unit activation
// ReLU(x) = max(0, x) for each element
func (ops *CPUTensorOps) ReLU(input *Tensor) (*Tensor, error) {
    numElements := input.NumElements()
    result := NewTensor(input.Shape, Float32)
    
    inputFloat := ops.toFloat32(input)
    outputFloat := make([]float32, numElements)
    
    for i := 0; i < numElements; i++ {
        if inputFloat[i] > 0 {
            outputFloat[i] = inputFloat[i]
        } else {
            outputFloat[i] = 0
        }
    }
    
    ops.float32ToBytes(outputFloat, result.Data)
    return result, nil
}

// Softmax computes the softmax function along the last dimension
// Softmax(x_i) = exp(x_i) / sum(exp(x_j)) for all j
// We use the numerically stable version: exp(x_i - max(x)) / sum(exp(x_j - max(x)))
func (ops *CPUTensorOps) Softmax(input *Tensor) (*Tensor, error) {
    if len(input.Shape) < 1 {
        return nil, fmt.Errorf("softmax requires at least 1D tensor")
    }
    
    result := NewTensor(input.Shape, Float32)
    inputFloat := ops.toFloat32(input)
    outputFloat := make([]float32, len(inputFloat))
    
    // Get the size of the last dimension
    lastDim := input.Shape[len(input.Shape)-1]
    numGroups := len(inputFloat) / lastDim
    
    // Apply softmax to each group along the last dimension
    for g := 0; g < numGroups; g++ {
        start := g * lastDim
        end := start + lastDim
        
        // Find maximum value for numerical stability
        maxVal := inputFloat[start]
        for i := start + 1; i < end; i++ {
            if inputFloat[i] > maxVal {
                maxVal = inputFloat[i]
            }
        }
        
        // Compute exp(x - max) and sum
        var sum float32
        for i := start; i < end; i++ {
            expVal := float32(math.Exp(float64(inputFloat[i] - maxVal)))
            outputFloat[i] = expVal
            sum += expVal
        }
        
        // Normalize by sum
        for i := start; i < end; i++ {
            outputFloat[i] /= sum
        }
    }
    
    ops.float32ToBytes(outputFloat, result.Data)
    return result, nil
}

The GELU implementation uses the tanh approximation, which provides excellent accuracy while remaining computationally efficient. The Softmax function includes the max subtraction trick to prevent numerical overflow when exponentiating large values. This stability consideration becomes crucial when working with logits that can have large magnitudes.

Element-wise operations complete our basic operation set. These operations work on tensors of the same shape, applying a function to corresponding elements.

// Add performs element-wise addition of two tensors
// Both tensors must have the same shape
func (ops *CPUTensorOps) Add(a, b *Tensor) (*Tensor, error) {
    // Verify shapes match
    if len(a.Shape) != len(b.Shape) {
        return nil, fmt.Errorf("tensors must have same rank for addition")
    }
    for i := range a.Shape {
        if a.Shape[i] != b.Shape[i] {
            return nil, fmt.Errorf("tensor shapes must match for addition: %v vs %v",
                a.Shape, b.Shape)
        }
    }
    
    numElements := a.NumElements()
    result := NewTensor(a.Shape, Float32)
    
    aFloat := ops.toFloat32(a)
    bFloat := ops.toFloat32(b)
    outputFloat := make([]float32, numElements)
    
    for i := 0; i < numElements; i++ {
        outputFloat[i] = aFloat[i] + bFloat[i]
    }
    
    ops.float32ToBytes(outputFloat, result.Data)
    return result, nil
}

// Multiply performs element-wise multiplication of two tensors
func (ops *CPUTensorOps) Multiply(a, b *Tensor) (*Tensor, error) {
    if len(a.Shape) != len(b.Shape) {
        return nil, fmt.Errorf("tensors must have same rank for multiplication")
    }
    for i := range a.Shape {
        if a.Shape[i] != b.Shape[i] {
            return nil, fmt.Errorf("tensor shapes must match: %v vs %v", a.Shape, b.Shape)
        }
    }
    
    numElements := a.NumElements()
    result := NewTensor(a.Shape, Float32)
    
    aFloat := ops.toFloat32(a)
    bFloat := ops.toFloat32(b)
    outputFloat := make([]float32, numElements)
    
    for i := 0; i < numElements; i++ {
        outputFloat[i] = aFloat[i] * bFloat[i]
    }
    
    ops.float32ToBytes(outputFloat, result.Data)
    return result, nil
}

// LayerNorm applies layer normalization with learned parameters
// This normalizes activations to have mean 0 and variance 1, then scales and shifts
func (ops *CPUTensorOps) LayerNorm(input, gamma, beta *Tensor, epsilon float32) (*Tensor, error) {
    if len(input.Shape) < 1 {
        return nil, fmt.Errorf("layer norm requires at least 1D tensor")
    }
    
    // The last dimension is the feature dimension to normalize
    featureDim := input.Shape[len(input.Shape)-1]
    numGroups := input.NumElements() / featureDim
    
    result := NewTensor(input.Shape, Float32)
    inputFloat := ops.toFloat32(input)
    gammaFloat := ops.toFloat32(gamma)
    betaFloat := ops.toFloat32(beta)
    outputFloat := make([]float32, len(inputFloat))
    
    // Normalize each group independently
    for g := 0; g < numGroups; g++ {
        start := g * featureDim
        end := start + featureDim
        
        // Compute mean
        var mean float32
        for i := start; i < end; i++ {
            mean += inputFloat[i]
        }
        mean /= float32(featureDim)
        
        // Compute variance
        var variance float32
        for i := start; i < end; i++ {
            diff := inputFloat[i] - mean
            variance += diff * diff
        }
        variance /= float32(featureDim)
        
        // Normalize, scale, and shift
        stddev := float32(math.Sqrt(float64(variance + epsilon)))
        for i := start; i < end; i++ {
            featureIdx := i - start
            normalized := (inputFloat[i] - mean) / stddev
            outputFloat[i] = normalized*gammaFloat[featureIdx] + betaFloat[featureIdx]
        }
    }
    
    ops.float32ToBytes(outputFloat, result.Data)
    return result, nil
}

The LayerNorm implementation follows the standard algorithm. We compute mean and variance across the feature dimension, normalize to zero mean and unit variance, then apply learned scale and shift parameters. The epsilon parameter prevents division by zero when variance is very small.

TENSOR OPERATIONS: GPU IMPLEMENTATIONS

Now we implement GPU backends. Each GPU platform has its own API and characteristics, but they all follow the same TensorOps interface. We start with CUDA for NVIDIA GPUs, which is the most common platform for machine learning.

package inference

/*
#cgo LDFLAGS: -lcuda -lcublas -lcudart
#include <cuda_runtime.h>
#include <cublas_v2.h>
#include <stdlib.h>

// Helper function to allocate GPU memory
void* allocateGPUMemory(size_t bytes) {
    void* ptr;
    cudaMalloc(&ptr, bytes);
    return ptr;
}

// Helper function to free GPU memory
void freeGPUMemory(void* ptr) {
    cudaFree(ptr);
}

// Helper function to copy from CPU to GPU
void copyToGPU(void* dst, const void* src, size_t bytes) {
    cudaMemcpy(dst, src, bytes, cudaMemcpyHostToDevice);
}

// Helper function to copy from GPU to CPU
void copyFromGPU(void* dst, const void* src, size_t bytes) {
    cudaMemcpy(dst, src, bytes, cudaMemcpyDeviceToHost);
}

// Check if CUDA is available
int cudaIsAvailable() {
    int deviceCount = 0;
    cudaError_t error = cudaGetDeviceCount(&deviceCount);
    return (error == cudaSuccess && deviceCount > 0) ? 1 : 0;
}
*/
import "C"
import (
    "fmt"
    "unsafe"
)

// CUDAOps implements TensorOps for NVIDIA CUDA GPUs
// This uses cuBLAS for optimized matrix operations
type CUDAOps struct {
    cublasHandle C.cublasHandle_t
    available    bool
}

// NewCUDAOps creates a new CUDA backend
// Returns nil if CUDA is not available
func NewCUDAOps() *CUDAOps {
    // Check if CUDA is available
    if C.cudaIsAvailable() == 0 {
        return nil
    }
    
    ops := &CUDAOps{
        available: true,
    }
    
    // Initialize cuBLAS
    status := C.cublasCreate(&ops.cublasHandle)
    if status != 0 {
        ops.available = false
        return nil
    }
    
    return ops
}

// GetDeviceType returns CUDA as the device type
func (ops *CUDAOps) GetDeviceType() DeviceType {
    return DeviceCUDA
}

// IsAvailable checks if CUDA is available on this system
func (ops *CUDAOps) IsAvailable() bool {
    return ops.available
}

// ToDevice moves a tensor to CUDA GPU memory
func (ops *CUDAOps) ToDevice(t *Tensor) error {
    if !ops.available {
        return fmt.Errorf("CUDA not available")
    }
    
    // If already on CUDA, nothing to do
    if t.Device == DeviceCUDA && t.GPUData != nil {
        return nil
    }
    
    // Allocate GPU memory
    numBytes := len(t.Data)
    gpuPtr := C.allocateGPUMemory(C.size_t(numBytes))
    if gpuPtr == nil {
        return fmt.Errorf("failed to allocate CUDA memory")
    }
    
    // Copy data from CPU to GPU
    C.copyToGPU(gpuPtr, unsafe.Pointer(&t.Data[0]), C.size_t(numBytes))
    
    // Free old GPU memory if it exists
    if t.GPUData != nil {
        C.freeGPUMemory(t.GPUData.(unsafe.Pointer))
    }
    
    // Update tensor metadata
    t.GPUData = gpuPtr
    t.Device = DeviceCUDA
    
    return nil
}

// ToCPU moves a tensor from CUDA GPU memory to CPU
func (ops *CUDAOps) ToCPU(t *Tensor) error {
    if t.Device == DeviceCPU {
        return nil  // Already on CPU
    }
    
    if t.Device != DeviceCUDA {
        return fmt.Errorf("tensor is on %s, not CUDA", t.Device)
    }
    
    if t.GPUData == nil {
        return fmt.Errorf("tensor has no GPU data")
    }
    
    // Copy data from GPU to CPU
    numBytes := len(t.Data)
    C.copyFromGPU(unsafe.Pointer(&t.Data[0]), t.GPUData.(unsafe.Pointer), C.size_t(numBytes))
    
    // Free GPU memory
    C.freeGPUMemory(t.GPUData.(unsafe.Pointer))
    t.GPUData = nil
    t.Device = DeviceCPU
    
    return nil
}

// Synchronize waits for all CUDA operations to complete
func (ops *CUDAOps) Synchronize() error {
    C.cudaDeviceSynchronize()
    return nil
}

// MatMul performs matrix multiplication using cuBLAS
// This leverages highly optimized NVIDIA libraries
func (ops *CUDAOps) MatMul(a, b *Tensor) (*Tensor, error) {
    if len(a.Shape) != 2 || len(b.Shape) != 2 {
        return nil, fmt.Errorf("matmul requires 2D tensors")
    }
    
    m, k1 := a.Shape[0], a.Shape[1]
    k2, n := b.Shape[0], b.Shape[1]
    
    if k1 != k2 {
        return nil, fmt.Errorf("incompatible shapes for matmul")
    }
    
    // Ensure inputs are on GPU
    if err := ops.ToDevice(a); err != nil {
        return nil, err
    }
    if err := ops.ToDevice(b); err != nil {
        return nil, err
    }
    
    // Create result tensor and allocate GPU memory
    result := NewTensor([]int{m, n}, Float32)
    if err := ops.ToDevice(result); err != nil {
        return nil, err
    }
    
    // Call cuBLAS matrix multiplication
    // cuBLAS uses column-major order, so we compute B^T * A^T = (A * B)^T
    // Then we treat the result as row-major to get A * B
    alpha := C.float(1.0)
    beta := C.float(0.0)
    
    C.cublasSgemm(
        ops.cublasHandle,
        C.CUBLAS_OP_N,  // No transpose for B
        C.CUBLAS_OP_N,  // No transpose for A
        C.int(n),       // Number of rows in result
        C.int(m),       // Number of columns in result
        C.int(k1),      // Shared dimension
        &alpha,
        (*C.float)(b.GPUData.(unsafe.Pointer)),  // B matrix
        C.int(n),       // Leading dimension of B
        (*C.float)(a.GPUData.(unsafe.Pointer)),  // A matrix
        C.int(k1),      // Leading dimension of A
        &beta,
        (*C.float)(result.GPUData.(unsafe.Pointer)),  // Result matrix
        C.int(n),       // Leading dimension of result
    )
    
    return result, nil
}

The CUDA implementation uses CGO to interface with CUDA libraries. The ToDevice method allocates GPU memory and copies data from CPU. The MatMul method leverages cuBLAS, NVIDIA's highly optimized BLAS library. cuBLAS uses column-major ordering, so we carefully arrange the matrix multiplication to account for this.

The key advantage of the CUDA backend is performance. cuBLAS implementations are hand-tuned for NVIDIA GPUs, using techniques like tensor cores on modern architectures. A matrix multiplication that takes seconds on CPU might complete in milliseconds on a good GPU.

Now let us implement the Metal backend for Apple Silicon. Metal is Apple's GPU framework, providing excellent performance on M1, M2, and M3 chips.

package inference

/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Metal -framework MetalPerformanceShaders -framework Foundation
#import <Metal/Metal.h>
#import <MetalPerformanceShaders/MetalPerformanceShaders.h>
#import <Foundation/Foundation.h>

// Global Metal device and command queue
static id<MTLDevice> metalDevice = nil;
static id<MTLCommandQueue> metalQueue = nil;

// Initialize Metal
int initMetal() {
    metalDevice = MTLCreateSystemDefaultDevice();
    if (metalDevice == nil) {
        return 0;
    }
    metalQueue = [metalDevice newCommandQueue];
    return (metalQueue != nil) ? 1 : 0;
}

// Check if Metal is available
int metalIsAvailable() {
    if (metalDevice == nil) {
        return initMetal();
    }
    return 1;
}

// Allocate Metal buffer
void* allocateMetalBuffer(size_t bytes) {
    if (metalDevice == nil) {
        return NULL;
    }
    id<MTLBuffer> buffer = [metalDevice newBufferWithLength:bytes 
                                                    options:MTLResourceStorageModeShared];
    return (__bridge_retained void*)buffer;
}

// Free Metal buffer
void freeMetalBuffer(void* ptr) {
    if (ptr != NULL) {
        id<MTLBuffer> buffer = (__bridge_transfer id<MTLBuffer>)ptr;
        buffer = nil;
    }
}

// Copy data to Metal buffer
void copyToMetalBuffer(void* bufferPtr, const void* data, size_t bytes) {
    id<MTLBuffer> buffer = (__bridge id<MTLBuffer>)bufferPtr;
    memcpy([buffer contents], data, bytes);
}

// Copy data from Metal buffer
void copyFromMetalBuffer(void* data, void* bufferPtr, size_t bytes) {
    id<MTLBuffer> buffer = (__bridge id<MTLBuffer>)bufferPtr;
    memcpy(data, [buffer contents], bytes);
}
*/
import "C"
import (
    "fmt"
    "unsafe"
)

// MetalOps implements TensorOps for Apple Metal GPUs
// This uses Metal Performance Shaders for optimized operations
type MetalOps struct {
    available bool
}

// NewMetalOps creates a new Metal backend
// Returns nil if Metal is not available
func NewMetalOps() *MetalOps {
    if C.metalIsAvailable() == 0 {
        return nil
    }
    
    return &MetalOps{
        available: true,
    }
}

// GetDeviceType returns Metal as the device type
func (ops *MetalOps) GetDeviceType() DeviceType {
    return DeviceMetal
}

// IsAvailable checks if Metal is available on this system
func (ops *MetalOps) IsAvailable() bool {
    return ops.available
}

// ToDevice moves a tensor to Metal GPU memory
func (ops *MetalOps) ToDevice(t *Tensor) error {
    if !ops.available {
        return fmt.Errorf("Metal not available")
    }
    
    // If already on Metal, nothing to do
    if t.Device == DeviceMetal && t.GPUData != nil {
        return nil
    }
    
    // Allocate Metal buffer
    numBytes := len(t.Data)
    bufferPtr := C.allocateMetalBuffer(C.size_t(numBytes))
    if bufferPtr == nil {
        return fmt.Errorf("failed to allocate Metal buffer")
    }
    
    // Copy data to Metal buffer
    C.copyToMetalBuffer(bufferPtr, unsafe.Pointer(&t.Data[0]), C.size_t(numBytes))
    
    // Free old GPU memory if it exists
    if t.GPUData != nil {
        C.freeMetalBuffer(t.GPUData.(unsafe.Pointer))
    }
    
    // Update tensor metadata
    t.GPUData = bufferPtr
    t.Device = DeviceMetal
    
    return nil
}

// ToCPU moves a tensor from Metal GPU memory to CPU
func (ops *MetalOps) ToCPU(t *Tensor) error {
    if t.Device == DeviceCPU {
        return nil
    }
    
    if t.Device != DeviceMetal {
        return fmt.Errorf("tensor is on %s, not Metal", t.Device)
    }
    
    if t.GPUData == nil {
        return fmt.Errorf("tensor has no GPU data")
    }
    
    // Copy data from Metal buffer to CPU
    numBytes := len(t.Data)
    C.copyFromMetalBuffer(unsafe.Pointer(&t.Data[0]), t.GPUData.(unsafe.Pointer), C.size_t(numBytes))
    
    // Free Metal buffer
    C.freeMetalBuffer(t.GPUData.(unsafe.Pointer))
    t.GPUData = nil
    t.Device = DeviceCPU
    
    return nil
}

// Synchronize waits for all Metal operations to complete
func (ops *MetalOps) Synchronize() error {
    // Metal operations on shared buffers are synchronous
    return nil
}

// MatMul performs matrix multiplication using Metal Performance Shaders
func (ops *MetalOps) MatMul(a, b *Tensor) (*Tensor, error) {
    if len(a.Shape) != 2 || len(b.Shape) != 2 {
        return nil, fmt.Errorf("matmul requires 2D tensors")
    }
    
    m, k1 := a.Shape[0], a.Shape[1]
    k2, n := b.Shape[0], b.Shape[1]
    
    if k1 != k2 {
        return nil, fmt.Errorf("incompatible shapes for matmul")
    }
    
    // Ensure inputs are on Metal GPU
    if err := ops.ToDevice(a); err != nil {
        return nil, err
    }
    if err := ops.ToDevice(b); err != nil {
        return nil, err
    }
    
    // Create result tensor
    result := NewTensor([]int{m, n}, Float32)
    if err := ops.ToDevice(result); err != nil {
        return nil, err
    }
    
    // For simplicity, we fall back to CPU for the actual computation
    // A full implementation would use MPSMatrixMultiplication
    // This requires more complex setup with matrix descriptors
    
    // Copy inputs to CPU, compute, copy result back
    if err := ops.ToCPU(a); err != nil {
        return nil, err
    }
    if err := ops.ToCPU(b); err != nil {
        return nil, err
    }
    
    // Use CPU ops for computation
    cpuOps := NewCPUTensorOps()
    cpuResult, err := cpuOps.MatMul(a, b)
    if err != nil {
        return nil, err
    }
    
    // Copy result back to Metal
    result.Data = cpuResult.Data
    if err := ops.ToDevice(result); err != nil {
        return nil, err
    }
    
    return result, nil
}

The Metal implementation demonstrates the adapter pattern's flexibility. While we show a simplified version that falls back to CPU for computation, a production implementation would use Metal Performance Shaders' MPSMatrixMultiplication class. This class provides highly optimized matrix operations tuned for Apple Silicon.

Metal's unified memory architecture on Apple Silicon makes data transfer between CPU and GPU very efficient. The MTLResourceStorageModeShared option allows both CPU and GPU to access the same memory, reducing copy overhead.

For completeness, we provide stub implementations for ROCm and OneAPI. These follow the same pattern but interface with AMD and Intel GPU libraries respectively.

// ROCmOps implements TensorOps for AMD ROCm GPUs
type ROCmOps struct {
    available bool
}

func NewROCmOps() *ROCmOps {
    // Check for ROCm availability
    // This would use hipGetDeviceCount() and related functions
    return &ROCmOps{available: false}
}

func (ops *ROCmOps) GetDeviceType() DeviceType {
    return DeviceROCm
}

func (ops *ROCmOps) IsAvailable() bool {
    return ops.available
}

func (ops *ROCmOps) ToDevice(t *Tensor) error {
    return fmt.Errorf("ROCm backend not fully implemented")
}

func (ops *ROCmOps) ToCPU(t *Tensor) error {
    return fmt.Errorf("ROCm backend not fully implemented")
}

func (ops *ROCmOps) Synchronize() error {
    return nil
}

func (ops *ROCmOps) MatMul(a, b *Tensor) (*Tensor, error) {
    return nil, fmt.Errorf("ROCm MatMul not implemented")
}

func (ops *ROCmOps) Add(a, b *Tensor) (*Tensor, error) {
    return nil, fmt.Errorf("ROCm Add not implemented")
}

func (ops *ROCmOps) Multiply(a, b *Tensor) (*Tensor, error) {
    return nil, fmt.Errorf("ROCm Multiply not implemented")
}

func (ops *ROCmOps) ReLU(input *Tensor) (*Tensor, error) {
    return nil, fmt.Errorf("ROCm ReLU not implemented")
}

func (ops *ROCmOps) GELU(input *Tensor) (*Tensor, error) {
    return nil, fmt.Errorf("ROCm GELU not implemented")
}

func (ops *ROCmOps) Softmax(input *Tensor) (*Tensor, error) {
    return nil, fmt.Errorf("ROCm Softmax not implemented")
}

func (ops *ROCmOps) LayerNorm(input, gamma, beta *Tensor, epsilon float32) (*Tensor, error) {
    return nil, fmt.Errorf("ROCm LayerNorm not implemented")
}

// OneAPIOps implements TensorOps for Intel OneAPI GPUs
type OneAPIOps struct {
    available bool
}

func NewOneAPIOps() *OneAPIOps {
    // Check for OneAPI availability
    return &OneAPIOps{available: false}
}

func (ops *OneAPIOps) GetDeviceType() DeviceType {
    return DeviceOneAPI
}

func (ops *OneAPIOps) IsAvailable() bool {
    return ops.available
}

func (ops *OneAPIOps) ToDevice(t *Tensor) error {
    return fmt.Errorf("OneAPI backend not fully implemented")
}

func (ops *OneAPIOps) ToCPU(t *Tensor) error {
    return fmt.Errorf("OneAPI backend not fully implemented")
}

func (ops *OneAPIOps) Synchronize() error {
    return nil
}

func (ops *OneAPIOps) MatMul(a, b *Tensor) (*Tensor, error) {
    return nil, fmt.Errorf("OneAPI MatMul not implemented")
}

func (ops *OneAPIOps) Add(a, b *Tensor) (*Tensor, error) {
    return nil, fmt.Errorf("OneAPI Add not implemented")
}

func (ops *OneAPIOps) Multiply(a, b *Tensor) (*Tensor, error) {
    return nil, fmt.Errorf("OneAPI Multiply not implemented")
}

func (ops *OneAPIOps) ReLU(input *Tensor) (*Tensor, error) {
    return nil, fmt.Errorf("OneAPI ReLU not implemented")
}

func (ops *OneAPIOps) GELU(input *Tensor) (*Tensor, error) {
    return nil, fmt.Errorf("OneAPI GELU not implemented")
}

func (ops *OneAPIOps) Softmax(input *Tensor) (*Tensor, error) {
    return nil, fmt.Errorf("OneAPI Softmax not implemented")
}

func (ops *OneAPIOps) LayerNorm(input, gamma, beta *Tensor, epsilon float32) (*Tensor, error) {
    return nil, fmt.Errorf("OneAPI LayerNorm not implemented")
}

These stub implementations demonstrate how new backends integrate into the system. A full ROCm implementation would use HIP (Heterogeneous-compute Interface for Portability) and rocBLAS for matrix operations. OneAPI would use SYCL and oneMKL. The interface remains consistent regardless of the underlying implementation.

MODEL FORMAT ADAPTERS: SUPPORTING DIVERSE FORMATS

Different frameworks save models in different formats. PyTorch uses pickle-based formats, Hugging Face popularized SafeTensors, and llama.cpp introduced GGUF. Our adapter pattern allows supporting all these formats without coupling the core inference engine to any specific format.

We define an interface that all format adapters must implement. This interface abstracts the details of reading model files and extracting weights.

// ModelAdapter defines the interface for loading models from different formats
// Each format (GGUF, SafeTensors, PyTorch, etc.) implements this interface
type ModelAdapter interface {
    // Load reads a model file and returns the model configuration and weights
    Load(filepath string) (*ModelConfig, map[string]*Tensor, error)
    
    // SupportsFormat checks if this adapter can handle the given file
    SupportsFormat(filepath string) bool
    
    // FormatName returns a human-readable name for this format
    FormatName() string
}

// ModelConfig contains the architecture parameters of the model
// This information is needed to construct the inference pipeline
type ModelConfig struct {
    VocabSize        int     // Size of the token vocabulary
    HiddenSize       int     // Dimension of hidden states
    NumLayers        int     // Number of transformer layers
    NumHeads         int     // Number of attention heads
    IntermediateSize int     // Size of feed-forward intermediate layer
    MaxSeqLen        int     // Maximum sequence length
    NormEpsilon      float32 // Epsilon for layer normalization
}

The ModelAdapter interface provides a clean abstraction. The Load method returns both configuration and weights. The SupportsFormat method allows automatic format detection. The FormatName method helps with error messages and logging.

Let us implement a GGUF adapter. GGUF is a binary format designed for efficient model storage and loading. It includes metadata and supports various quantization schemes.

package inference

import (
    "encoding/binary"
    "fmt"
    "io"
    "os"
    "strings"
)

// GGUFAdapter loads models in the GGUF format
// GGUF is used by llama.cpp and related projects
type GGUFAdapter struct{}

// NewGGUFAdapter creates a new GGUF format adapter
func NewGGUFAdapter() *GGUFAdapter {
    return &GGUFAdapter{}
}

// FormatName returns the name of this format
func (a *GGUFAdapter) FormatName() string {
    return "GGUF"
}

// SupportsFormat checks if a file is in GGUF format
// GGUF files start with the magic number "GGUF"
func (a *GGUFAdapter) SupportsFormat(filepath string) bool {
    file, err := os.Open(filepath)
    if err != nil {
        return false
    }
    defer file.Close()
    
    // Read first 4 bytes
    magic := make([]byte, 4)
    if _, err := file.Read(magic); err != nil {
        return false
    }
    
    // Check for GGUF magic number
    return string(magic) == "GGUF"
}

// Load reads a GGUF file and extracts configuration and weights
func (a *GGUFAdapter) Load(filepath string) (*ModelConfig, map[string]*Tensor, error) {
    file, err := os.Open(filepath)
    if err != nil {
        return nil, nil, fmt.Errorf("failed to open file: %w", err)
    }
    defer file.Close()
    
    // Read and verify magic number
    magic := make([]byte, 4)
    if _, err := file.Read(magic); err != nil {
        return nil, nil, fmt.Errorf("failed to read magic: %w", err)
    }
    if string(magic) != "GGUF" {
        return nil, nil, fmt.Errorf("invalid GGUF file: wrong magic number")
    }
    
    // Read version
    var version uint32
    if err := binary.Read(file, binary.LittleEndian, &version); err != nil {
        return nil, nil, fmt.Errorf("failed to read version: %w", err)
    }
    
    // Read tensor count and metadata count
    var tensorCount, metadataCount uint64
    if err := binary.Read(file, binary.LittleEndian, &tensorCount); err != nil {
        return nil, nil, fmt.Errorf("failed to read tensor count: %w", err)
    }
    if err := binary.Read(file, binary.LittleEndian, &metadataCount); err != nil {
        return nil, nil, fmt.Errorf("failed to read metadata count: %w", err)
    }
    
    // Read metadata to extract model configuration
    metadata := make(map[string]interface{})
    for i := uint64(0); i < metadataCount; i++ {
        key, value, err := a.readMetadataEntry(file)
        if err != nil {
            return nil, nil, fmt.Errorf("failed to read metadata entry %d: %w", i, err)
        }
        metadata[key] = value
    }
    
    // Extract configuration from metadata
    config := &ModelConfig{
        VocabSize:        a.getMetadataInt(metadata, "vocab_size", 32000),
        HiddenSize:       a.getMetadataInt(metadata, "hidden_size", 4096),
        NumLayers:        a.getMetadataInt(metadata, "num_layers", 32),
        NumHeads:         a.getMetadataInt(metadata, "num_heads", 32),
        IntermediateSize: a.getMetadataInt(metadata, "intermediate_size", 11008),
        MaxSeqLen:        a.getMetadataInt(metadata, "max_seq_len", 2048),
        NormEpsilon:      a.getMetadataFloat(metadata, "norm_epsilon", 1e-5),
    }
    
    // Read tensor information
    weights := make(map[string]*Tensor)
    for i := uint64(0); i < tensorCount; i++ {
        name, tensor, err := a.readTensorInfo(file)
        if err != nil {
            return nil, nil, fmt.Errorf("failed to read tensor %d: %w", i, err)
        }
        weights[name] = tensor
    }
    
    // Read actual tensor data
    for name, tensor := range weights {
        if _, err := file.Read(tensor.Data); err != nil {
            return nil, nil, fmt.Errorf("failed to read data for tensor %s: %w", name, err)
        }
    }
    
    return config, weights, nil
}

// readMetadataEntry reads a single metadata key-value pair
func (a *GGUFAdapter) readMetadataEntry(r io.Reader) (string, interface{}, error) {
    // Read key length
    var keyLen uint64
    if err := binary.Read(r, binary.LittleEndian, &keyLen); err != nil {
        return "", nil, err
    }
    
    // Read key
    keyBytes := make([]byte, keyLen)
    if _, err := r.Read(keyBytes); err != nil {
        return "", nil, err
    }
    key := string(keyBytes)
    
    // Read value type
    var valueType uint32
    if err := binary.Read(r, binary.LittleEndian, &valueType); err != nil {
        return "", nil, err
    }
    
    // Read value based on type
    var value interface{}
    switch valueType {
    case 4:  // uint32
        var v uint32
        if err := binary.Read(r, binary.LittleEndian, &v); err != nil {
            return "", nil, err
        }
        value = v
    case 8:  // string
        var strLen uint64
        if err := binary.Read(r, binary.LittleEndian, &strLen); err != nil {
            return "", nil, err
        }
        strBytes := make([]byte, strLen)
        if _, err := r.Read(strBytes); err != nil {
            return "", nil, err
        }
        value = string(strBytes)
    case 10:  // float32
        var v float32
        if err := binary.Read(r, binary.LittleEndian, &v); err != nil {
            return "", nil, err
        }
        value = v
    default:
        return "", nil, fmt.Errorf("unsupported metadata type: %d", valueType)
    }
    
    return key, value, nil
}

// readTensorInfo reads tensor metadata (name, shape, type)
func (a *GGUFAdapter) readTensorInfo(r io.Reader) (string, *Tensor, error) {
    // Read tensor name
    var nameLen uint64
    if err := binary.Read(r, binary.LittleEndian, &nameLen); err != nil {
        return "", nil, err
    }
    nameBytes := make([]byte, nameLen)
    if _, err := r.Read(nameBytes); err != nil {
        return "", nil, err
    }
    name := string(nameBytes)
    
    // Read number of dimensions
    var numDims uint32
    if err := binary.Read(r, binary.LittleEndian, &numDims); err != nil {
        return "", nil, err
    }
    
    // Read shape
    shape := make([]int, numDims)
    for i := uint32(0); i < numDims; i++ {
        var dim uint64
        if err := binary.Read(r, binary.LittleEndian, &dim); err != nil {
            return "", nil, err
        }
        shape[i] = int(dim)
    }
    
    // Read data type
    var dtypeCode uint32
    if err := binary.Read(r, binary.LittleEndian, &dtypeCode); err != nil {
        return "", nil, err
    }
    
    // Map GGUF dtype to our DataType
    var dtype DataType
    switch dtypeCode {
    case 0:  // F32
        dtype = Float32
    case 1:  // F16
        dtype = Float16
    case 2:  // Q4_0 (4-bit quantization)
        dtype = Int4
    case 3:  // Q4_1
        dtype = Int4
    case 8:  // Q8_0
        dtype = Int8
    default:
        return "", nil, fmt.Errorf("unsupported GGUF dtype: %d", dtypeCode)
    }
    
    // Read offset (we'll use it to seek to data later)
    var offset uint64
    if err := binary.Read(r, binary.LittleEndian, &offset); err != nil {
        return "", nil, err
    }
    
    // Create tensor
    tensor := NewTensor(shape, dtype)
    
    return name, tensor, nil
}

// getMetadataInt extracts an integer from metadata with a default value
func (a *GGUFAdapter) getMetadataInt(metadata map[string]interface{}, key string, defaultVal int) int {
    if val, ok := metadata[key]; ok {
        if intVal, ok := val.(uint32); ok {
            return int(intVal)
        }
    }
    return defaultVal
}

// getMetadataFloat extracts a float from metadata with a default value
func (a *GGUFAdapter) getMetadataFloat(metadata map[string]interface{}, key string, defaultVal float32) float32 {
    if val, ok := metadata[key]; ok {
        if floatVal, ok := val.(float32); ok {
            return floatVal
        }
    }
    return defaultVal
}

The GGUF adapter demonstrates binary file parsing. We read the magic number to verify the format, then extract metadata containing model configuration. Tensor information includes names, shapes, and data types. The actual tensor data follows the metadata section. This format is efficient because it stores everything in a single file with minimal overhead.

Now let us implement a SafeTensors adapter. SafeTensors is a simple, safe format that stores tensors with JSON metadata. It has become popular in the Hugging Face ecosystem.

package inference

import (
    "encoding/json"
    "fmt"
    "os"
    "strings"
)

// SafeTensorsAdapter loads models in the SafeTensors format
// SafeTensors is used by Hugging Face and provides safe, fast loading
type SafeTensorsAdapter struct{}

// NewSafeTensorsAdapter creates a new SafeTensors format adapter
func NewSafeTensorsAdapter() *SafeTensorsAdapter {
    return &SafeTensorsAdapter{}
}

// FormatName returns the name of this format
func (a *SafeTensorsAdapter) FormatName() string {
    return "SafeTensors"
}

// SupportsFormat checks if a file is in SafeTensors format
// SafeTensors files typically have .safetensors extension
func (a *SafeTensorsAdapter) SupportsFormat(filepath string) bool {
    return strings.HasSuffix(strings.ToLower(filepath), ".safetensors")
}

// SafeTensorsHeader represents the JSON header in a SafeTensors file
type SafeTensorsHeader struct {
    Metadata map[string]string            `json:"__metadata__"`
    Tensors  map[string]SafeTensorInfo    `json:"-"`
}

// SafeTensorInfo contains information about a single tensor
type SafeTensorInfo struct {
    DType  string  `json:"dtype"`
    Shape  []int   `json:"shape"`
    Offset []int64 `json:"data_offsets"`
}

// Load reads a SafeTensors file and extracts configuration and weights
func (a *SafeTensorsAdapter) Load(filepath string) (*ModelConfig, map[string]*Tensor, error) {
    file, err := os.Open(filepath)
    if err != nil {
        return nil, nil, fmt.Errorf("failed to open file: %w", err)
    }
    defer file.Close()
    
    // Read header size (first 8 bytes)
    headerSizeBytes := make([]byte, 8)
    if _, err := file.Read(headerSizeBytes); err != nil {
        return nil, nil, fmt.Errorf("failed to read header size: %w", err)
    }
    headerSize := binary.LittleEndian.Uint64(headerSizeBytes)
    
    // Read header JSON
    headerBytes := make([]byte, headerSize)
    if _, err := file.Read(headerBytes); err != nil {
        return nil, nil, fmt.Errorf("failed to read header: %w", err)
    }
    
    // Parse header JSON
    var rawHeader map[string]interface{}
    if err := json.Unmarshal(headerBytes, &rawHeader); err != nil {
        return nil, nil, fmt.Errorf("failed to parse header JSON: %w", err)
    }
    
    // Extract metadata
    metadata := make(map[string]string)
    if metadataRaw, ok := rawHeader["__metadata__"]; ok {
        if metadataMap, ok := metadataRaw.(map[string]interface{}); ok {
            for k, v := range metadataMap {
                if strVal, ok := v.(string); ok {
                    metadata[k] = strVal
                }
            }
        }
    }
    
    // Extract tensor information
    weights := make(map[string]*Tensor)
    dataOffset := int64(8 + headerSize)
    
    for key, value := range rawHeader {
        if key == "__metadata__" {
            continue
        }
        
        // Parse tensor info
        tensorInfoMap, ok := value.(map[string]interface{})
        if !ok {
            continue
        }
        
        // Extract dtype
        dtypeStr, _ := tensorInfoMap["dtype"].(string)
        dtype := a.parseDType(dtypeStr)
        
        // Extract shape
        shapeRaw, _ := tensorInfoMap["shape"].([]interface{})
        shape := make([]int, len(shapeRaw))
        for i, dim := range shapeRaw {
            if dimFloat, ok := dim.(float64); ok {
                shape[i] = int(dimFloat)
            }
        }
        
        // Extract data offsets
        offsetsRaw, _ := tensorInfoMap["data_offsets"].([]interface{})
        if len(offsetsRaw) != 2 {
            continue
        }
        startOffset := int64(offsetsRaw[0].(float64))
        endOffset := int64(offsetsRaw[1].(float64))
        
        // Create tensor
        tensor := NewTensor(shape, dtype)
        
        // Read tensor data
        dataSize := endOffset - startOffset
        file.Seek(dataOffset+startOffset, 0)
        if _, err := file.Read(tensor.Data[:dataSize]); err != nil {
            return nil, nil, fmt.Errorf("failed to read tensor %s: %w", key, err)
        }
        
        weights[key] = tensor
    }
    
    // Extract configuration from metadata
    config := &ModelConfig{
        VocabSize:        a.getConfigInt(metadata, "vocab_size", 32000),
        HiddenSize:       a.getConfigInt(metadata, "hidden_size", 4096),
        NumLayers:        a.getConfigInt(metadata, "num_hidden_layers", 32),
        NumHeads:         a.getConfigInt(metadata, "num_attention_heads", 32),
        IntermediateSize: a.getConfigInt(metadata, "intermediate_size", 11008),
        MaxSeqLen:        a.getConfigInt(metadata, "max_position_embeddings", 2048),
        NormEpsilon:      1e-5,
    }
    
    return config, weights, nil
}

// parseDType converts SafeTensors dtype string to our DataType
func (a *SafeTensorsAdapter) parseDType(dtype string) DataType {
    switch dtype {
    case "F32":
        return Float32
    case "F16":
        return Float16
    case "I8":
        return Int8
    case "I4":
        return Int4
    case "BF16":
        return BFloat16
    default:
        return Float32
    }
}

// getConfigInt extracts an integer from string metadata
func (a *SafeTensorsAdapter) getConfigInt(metadata map[string]string, key string, defaultVal int) int {
    if val, ok := metadata[key]; ok {
        var intVal int
        fmt.Sscanf(val, "%d", &intVal)
        return intVal
    }
    return defaultVal
}

The SafeTensors adapter parses JSON metadata followed by raw tensor data. The format is simpler than GGUF but equally efficient. The JSON header contains all tensor metadata including shapes and data offsets. This allows selective loading of specific tensors without reading the entire file.

QUANTIZATION SYSTEM: MEMORY AND SPEED OPTIMIZATION

Quantization reduces model size and increases inference speed by using lower-precision numeric representations. Our quantization system supports multiple schemes and integrates seamlessly with the tensor operations.

The key insight is that not all weights need full 32-bit precision. Many weights can be represented with 8 bits or even 4 bits with minimal accuracy loss. This reduces memory bandwidth requirements, which often bottlenecks GPU performance.

package inference

import (
    "fmt"
    "math"
)

// Quantizer defines the interface for quantization schemes
// Different quantizers implement different precision reduction strategies
type Quantizer interface {
    // Quantize converts a float32 tensor to a quantized representation
    Quantize(input *Tensor) (*Tensor, error)
    
    // Dequantize converts a quantized tensor back to float32
    Dequantize(input *Tensor) (*Tensor, error)
    
    // GetQuantizedType returns the data type after quantization
    GetQuantizedType() DataType
}

// Int8Quantizer implements symmetric 8-bit quantization
// This maps float32 values to the range [-127, 127]
type Int8Quantizer struct {
    scale float32  // Scaling factor for quantization
}

// NewInt8Quantizer creates a new 8-bit quantizer
func NewInt8Quantizer() *Int8Quantizer {
    return &Int8Quantizer{}
}

// GetQuantizedType returns Int8
func (q *Int8Quantizer) GetQuantizedType() DataType {
    return Int8
}

// Quantize converts float32 tensor to int8
func (q *Int8Quantizer) Quantize(input *Tensor) (*Tensor, error) {
    if input.DType != Float32 {
        return nil, fmt.Errorf("can only quantize float32 tensors")
    }
    
    // Convert tensor data to float32 array
    numElements := input.NumElements()
    floatData := make([]float32, numElements)
    for i := 0; i < numElements; i++ {
        bits := binary.LittleEndian.Uint32(input.Data[i*4 : (i+1)*4])
        floatData[i] = math.Float32frombits(bits)
    }
    
    // Find maximum absolute value for scaling
    maxAbs := float32(0.0)
    for _, val := range floatData {
        absVal := float32(math.Abs(float64(val)))
        if absVal > maxAbs {
            maxAbs = absVal
        }
    }
    
    // Calculate scale factor
    q.scale = maxAbs / 127.0
    if q.scale == 0 {
        q.scale = 1.0  // Avoid division by zero
    }
    
    // Create quantized tensor
    quantized := NewTensor(input.Shape, Int8)
    
    // Quantize each element
    for i := 0; i < numElements; i++ {
        // Scale and round to nearest integer
        quantizedVal := int8(math.Round(float64(floatData[i] / q.scale)))
        // Clamp to int8 range
        if quantizedVal > 127 {
            quantizedVal = 127
        } else if quantizedVal < -127 {
            quantizedVal = -127
        }
        quantized.Data[i] = byte(quantizedVal)
    }
    
    return quantized, nil
}

// Dequantize converts int8 tensor back to float32
func (q *Int8Quantizer) Dequantize(input *Tensor) (*Tensor, error) {
    if input.DType != Int8 {
        return nil, fmt.Errorf("can only dequantize int8 tensors")
    }
    
    numElements := input.NumElements()
    dequantized := NewTensor(input.Shape, Float32)
    
    // Dequantize each element
    for i := 0; i < numElements; i++ {
        // Convert int8 to float32 and scale
        int8Val := int8(input.Data[i])
        floatVal := float32(int8Val) * q.scale
        
        // Write to output tensor
        bits := math.Float32bits(floatVal)
        binary.LittleEndian.PutUint32(dequantized.Data[i*4:(i+1)*4], bits)
    }
    
    return dequantized, nil
}

The Int8Quantizer implements symmetric quantization. We find the maximum absolute value in the tensor and use it to calculate a scale factor. Each float32 value divides by this scale and rounds to the nearest integer in the range negative one hundred twenty-seven to positive one hundred twenty-seven. Dequantization multiplies by the scale factor to approximate the original values.

This scheme reduces memory usage by seventy-five percent compared to float32. The accuracy loss is typically minimal for most model weights. Activations often need higher precision, so we might quantize only weights while keeping activations in float32.

Now let us implement 4-bit quantization, which provides even greater memory savings.

// Int4Quantizer implements 4-bit quantization
// This packs two values per byte, achieving 8x memory reduction
type Int4Quantizer struct {
    scale float32
}

// NewInt4Quantizer creates a new 4-bit quantizer
func NewInt4Quantizer() *Int4Quantizer {
    return &Int4Quantizer{}
}

// GetQuantizedType returns Int4
func (q *Int4Quantizer) GetQuantizedType() DataType {
    return Int4
}

// Quantize converts float32 tensor to int4
func (q *Int4Quantizer) Quantize(input *Tensor) (*Tensor, error) {
    if input.DType != Float32 {
        return nil, fmt.Errorf("can only quantize float32 tensors")
    }
    
    numElements := input.NumElements()
    floatData := make([]float32, numElements)
    for i := 0; i < numElements; i++ {
        bits := binary.LittleEndian.Uint32(input.Data[i*4 : (i+1)*4])
        floatData[i] = math.Float32frombits(bits)
    }
    
    // Find maximum absolute value
    maxAbs := float32(0.0)
    for _, val := range floatData {
        absVal := float32(math.Abs(float64(val)))
        if absVal > maxAbs {
            maxAbs = absVal
        }
    }
    
    // Calculate scale for 4-bit range [-7, 7]
    q.scale = maxAbs / 7.0
    if q.scale == 0 {
        q.scale = 1.0
    }
    
    // Create quantized tensor (two elements per byte)
    quantized := NewTensor(input.Shape, Int4)
    
    // Quantize and pack elements
    for i := 0; i < numElements; i += 2 {
        // Quantize first element (lower 4 bits)
        val1 := int8(math.Round(float64(floatData[i] / q.scale)))
        if val1 > 7 {
            val1 = 7
        } else if val1 < -7 {
            val1 = -7
        }
        
        // Quantize second element (upper 4 bits) if it exists
        var val2 int8
        if i+1 < numElements {
            val2 = int8(math.Round(float64(floatData[i+1] / q.scale)))
            if val2 > 7 {
                val2 = 7
            } else if val2 < -7 {
                val2 = -7
            }
        }
        
        // Pack two 4-bit values into one byte
        // Lower 4 bits: val1, Upper 4 bits: val2
        packed := byte((uint8(val1) & 0x0F) | ((uint8(val2) & 0x0F) << 4))
        quantized.Data[i/2] = packed
    }
    
    return quantized, nil
}

// Dequantize converts int4 tensor back to float32
func (q *Int4Quantizer) Dequantize(input *Tensor) (*Tensor, error) {
    if input.DType != Int4 {
        return nil, fmt.Errorf("can only dequantize int4 tensors")
    }
    
    numElements := input.NumElements()
    dequantized := NewTensor(input.Shape, Float32)
    
    // Unpack and dequantize elements
    for i := 0; i < numElements; i++ {
        byteIdx := i / 2
        packed := input.Data[byteIdx]
        
        var int4Val int8
        if i%2 == 0 {
            // Lower 4 bits
            int4Val = int8(packed & 0x0F)
            if int4Val > 7 {
                int4Val -= 16  // Sign extension
            }
        } else {
            // Upper 4 bits
            int4Val = int8(packed >> 4)
            if int4Val > 7 {
                int4Val -= 16
            }
        }
        
        // Scale back to float32
        floatVal := float32(int4Val) * q.scale
        
        // Write to output
        bits := math.Float32bits(floatVal)
        binary.LittleEndian.PutUint32(dequantized.Data[i*4:(i+1)*4], bits)
    }
    
    return dequantized, nil
}

The Int4Quantizer achieves eighty-seven point five percent memory reduction compared to float32. Each value fits in 4 bits, representing values from negative seven to positive seven. We pack two values per byte, requiring careful bit manipulation during quantization and dequantization.

The trade-off is increased quantization error. Four-bit quantization works well for weights in large models where the sheer number of parameters provides redundancy. Smaller models might suffer more accuracy loss.

TOKENIZATION: TEXT TO TOKENS AND BACK

Before we can run inference, we need to convert text into tokens that the model understands. Tokenization breaks text into subword units based on a learned vocabulary. Modern LLMs typically use Byte-Pair Encoding or SentencePiece tokenization.

package inference

import (
    "fmt"
    "strings"
)

// Tokenizer defines the interface for text tokenization
// Different tokenizers implement different algorithms (BPE, WordPiece, etc.)
type Tokenizer interface {
    // Encode converts text to token IDs
    Encode(text string) ([]int, error)
    
    // Decode converts token IDs back to text
    Decode(tokens []int) (string, error)
    
    // VocabSize returns the size of the vocabulary
    VocabSize() int
}

// BPETokenizer implements Byte-Pair Encoding tokenization
// This is used by GPT-2, GPT-3, and many other models
type BPETokenizer struct {
    vocab       map[string]int     // Token to ID mapping
    reverseVocab map[int]string    // ID to token mapping
    merges      [][]string         // BPE merge rules
}

// NewBPETokenizer creates a new BPE tokenizer from vocabulary and merges
func NewBPETokenizer(vocab map[string]int, merges [][]string) *BPETokenizer {
    // Create reverse vocabulary for decoding
    reverseVocab := make(map[int]string)
    for token, id := range vocab {
        reverseVocab[id] = token
    }
    
    return &BPETokenizer{
        vocab:        vocab,
        reverseVocab: reverseVocab,
        merges:       merges,
    }
}

// VocabSize returns the vocabulary size
func (t *BPETokenizer) VocabSize() int {
    return len(t.vocab)
}

// Encode converts text to token IDs using BPE algorithm
func (t *BPETokenizer) Encode(text string) ([]int, error) {
    // Split text into characters
    chars := strings.Split(text, "")
    
    // Apply BPE merges iteratively
    for _, merge := range t.merges {
        if len(merge) != 2 {
            continue
        }
        
        first, second := merge[0], merge[1]
        merged := first + second
        
        // Find and merge all occurrences
        i := 0
        for i < len(chars)-1 {
            if chars[i] == first && chars[i+1] == second {
                // Merge these two tokens
                chars[i] = merged
                chars = append(chars[:i+1], chars[i+2:]...)
            } else {
                i++
            }
        }
    }
    
    // Convert tokens to IDs
    tokenIDs := make([]int, len(chars))
    for i, token := range chars {
        if id, ok := t.vocab[token]; ok {
            tokenIDs[i] = id
        } else {
            // Unknown token - use a special UNK token ID
            tokenIDs[i] = t.vocab["<unk>"]
        }
    }
    
    return tokenIDs, nil
}

// Decode converts token IDs back to text
func (t *BPETokenizer) Decode(tokens []int) (string, error) {
    var result strings.Builder
    
    for _, tokenID := range tokens {
        if token, ok := t.reverseVocab[tokenID]; ok {
            result.WriteString(token)
        } else {
            return "", fmt.Errorf("unknown token ID: %d", tokenID)
        }
    }
    
    return result.String(), nil
}

The BPETokenizer implements the Byte-Pair Encoding algorithm. We start with individual characters and iteratively merge the most frequent pairs according to learned merge rules. This creates a vocabulary of subword units that balances vocabulary size with the ability to represent any text.

The Encode method applies merge rules to break text into tokens, then looks up each token in the vocabulary. The Decode method reverses this process, converting token IDs back to their string representations and concatenating them.

Real tokenizers handle special cases like whitespace, punctuation, and Unicode characters more carefully. They also include special tokens for beginning-of-sequence, end-of-sequence, padding, and unknown tokens. Our simplified implementation demonstrates the core concept.

INFERENCE PIPELINE: PUTTING IT ALL TOGETHER

Now we have all the pieces needed to build the complete inference pipeline. The inference engine coordinates tokenization, model execution, and text generation. It manages the key-value cache for efficient autoregressive generation and handles sampling strategies for choosing the next token.

package inference

import (
    "fmt"
    "math"
    "math/rand"
)

// InferenceEngine orchestrates the complete inference process
// It manages model execution, caching, and text generation
type InferenceEngine struct {
    config      *ModelConfig
    weights     map[string]*Tensor
    tokenizer   Tokenizer
    backend     *ComputeBackend
    ops         TensorOps
    kvCache     map[int]*KVCache  // Key-value cache per layer
}

// KVCache stores cached key and value tensors for a layer
// This avoids recomputing attention for previous tokens
type KVCache struct {
    keys   *Tensor
    values *Tensor
    seqLen int  // Current sequence length in cache
}

// NewInferenceEngine creates a new inference engine
func NewInferenceEngine(config *ModelConfig, weights map[string]*Tensor, tokenizer Tokenizer) (*InferenceEngine, error) {
    // Initialize compute backend
    backend, err := NewComputeBackend()
    if err != nil {
        return nil, fmt.Errorf("failed to initialize compute backend: %w", err)
    }
    
    engine := &InferenceEngine{
        config:    config,
        weights:   weights,
        tokenizer: tokenizer,
        backend:   backend,
        ops:       backend.GetOps(),
        kvCache:   make(map[int]*KVCache),
    }
    
    // Move model weights to GPU if available
    if engine.ops.GetDeviceType() != DeviceCPU {
        fmt.Printf("Moving model weights to %s...\n", engine.ops.GetDeviceType())
        for name, tensor := range weights {
            if err := engine.ops.ToDevice(tensor); err != nil {
                fmt.Printf("Warning: failed to move %s to GPU: %v\n", name, err)
            }
        }
    }
    
    return engine, nil
}

// Generate produces text given a prompt
// It uses autoregressive generation with the specified sampling strategy
func (e *InferenceEngine) Generate(prompt string, maxTokens int, temperature float32) (string, error) {
    // Encode prompt to token IDs
    inputTokens, err := e.tokenizer.Encode(prompt)
    if err != nil {
        return "", fmt.Errorf("tokenization failed: %w", err)
    }
    
    fmt.Printf("Input tokens: %v\n", inputTokens)
    
    // Initialize KV cache for all layers
    e.initializeKVCache()
    
    // Generate tokens autoregressively
    generatedTokens := make([]int, 0, maxTokens)
    currentTokens := inputTokens
    
    for i := 0; i < maxTokens; i++ {
        // Run forward pass
        logits, err := e.forward(currentTokens)
        if err != nil {
            return "", fmt.Errorf("forward pass failed: %w", err)
        }
        
        // Sample next token
        nextToken := e.sampleToken(logits, temperature)
        generatedTokens = append(generatedTokens, nextToken)
        
        // Check for end-of-sequence token
        if nextToken == e.tokenizer.VocabSize()-1 {
            break
        }
        
        // Update input for next iteration (only the new token)
        currentTokens = []int{nextToken}
        
        // Print progress
        if i%10 == 0 {
            fmt.Printf("Generated %d tokens...\n", i)
        }
    }
    
    // Decode generated tokens to text
    fullTokens := append(inputTokens, generatedTokens...)
    result, err := e.tokenizer.Decode(fullTokens)
    if err != nil {
        return "", fmt.Errorf("decoding failed: %w", err)
    }
    
    return result, nil
}

// initializeKVCache creates empty KV caches for all layers
func (e *InferenceEngine) initializeKVCache() {
    for i := 0; i < e.config.NumLayers; i++ {
        e.kvCache[i] = &KVCache{
            keys:   nil,
            values: nil,
            seqLen: 0,
        }
    }
}

// forward runs a forward pass through the model
// This implements the transformer architecture
func (e *InferenceEngine) forward(tokens []int) (*Tensor, error) {
    batchSize := 1
    seqLen := len(tokens)
    
    // Create input tensor from token IDs
    // We need to look up embeddings for each token
    embeddings := e.getEmbeddings(tokens)
    
    // embeddings shape: [batchSize, seqLen, hiddenSize]
    hidden := embeddings
    
    // Process through each transformer layer
    for layer := 0; layer < e.config.NumLayers; layer++ {
        var err error
        hidden, err = e.transformerLayer(hidden, layer)
        if err != nil {
            return nil, fmt.Errorf("layer %d failed: %w", layer, err)
        }
    }
    
    // Apply final layer normalization
    finalNorm, err := e.applyLayerNorm(hidden, "final_norm")
    if err != nil {
        return nil, fmt.Errorf("final norm failed: %w", err)
    }
    
    // Project to vocabulary logits
    // Take only the last token's hidden state for next token prediction
    lastHidden := e.sliceLastToken(finalNorm, seqLen)
    
    // Multiply by output projection (language modeling head)
    lmHead := e.weights["lm_head.weight"]
    logits, err := e.ops.MatMul(lastHidden, lmHead)
    if err != nil {
        return nil, fmt.Errorf("lm head projection failed: %w", err)
    }
    
    return logits, nil
}

// getEmbeddings looks up token embeddings
func (e *InferenceEngine) getEmbeddings(tokens []int) *Tensor {
    // Create tensor to hold embeddings
    embeddings := NewTensor([]int{1, len(tokens), e.config.HiddenSize}, Float32)
    
    // Look up each token's embedding
    embeddingWeight := e.weights["embedding.weight"]
    
    for i, tokenID := range tokens {
        // Extract embedding for this token
        // This is a row from the embedding matrix
        start := tokenID * e.config.HiddenSize
        end := start + e.config.HiddenSize
        
        // Copy embedding to output tensor
        destStart := i * e.config.HiddenSize
        copy(embeddings.Data[destStart*4:(destStart+e.config.HiddenSize)*4],
             embeddingWeight.Data[start*4:end*4])
    }
    
    return embeddings
}

// transformerLayer processes input through one transformer layer
func (e *InferenceEngine) transformerLayer(input *Tensor, layerIdx int) (*Tensor, error) {
    // Layer normalization before attention
    normalized, err := e.applyLayerNorm(input, fmt.Sprintf("layer_%d.attn_norm", layerIdx))
    if err != nil {
        return nil, err
    }
    
    // Multi-head self-attention
    attnOutput, err := e.multiHeadAttention(normalized, layerIdx)
    if err != nil {
        return nil, err
    }
    
    // Residual connection
    afterAttn, err := e.ops.Add(input, attnOutput)
    if err != nil {
        return nil, err
    }
    
    // Layer normalization before feed-forward
    normalized2, err := e.applyLayerNorm(afterAttn, fmt.Sprintf("layer_%d.ffn_norm", layerIdx))
    if err != nil {
        return nil, err
    }
    
    // Feed-forward network
    ffnOutput, err := e.feedForward(normalized2, layerIdx)
    if err != nil {
        return nil, err
    }
    
    // Residual connection
    output, err := e.ops.Add(afterAttn, ffnOutput)
    if err != nil {
        return nil, err
    }
    
    return output, nil
}

// multiHeadAttention implements multi-head self-attention
func (e *InferenceEngine) multiHeadAttention(input *Tensor, layerIdx int) (*Tensor, error) {
    // Project input to query, key, value
    qWeight := e.weights[fmt.Sprintf("layer_%d.attn.q_proj.weight", layerIdx)]
    kWeight := e.weights[fmt.Sprintf("layer_%d.attn.k_proj.weight", layerIdx)]
    vWeight := e.weights[fmt.Sprintf("layer_%d.attn.v_proj.weight", layerIdx)]
    
    query, err := e.ops.MatMul(input, qWeight)
    if err != nil {
        return nil, err
    }
    
    key, err := e.ops.MatMul(input, kWeight)
    if err != nil {
        return nil, err
    }
    
    value, err := e.ops.MatMul(input, vWeight)
    if err != nil {
        return nil, err
    }
    
    // Reshape for multi-head attention
    // Split hidden dimension into num_heads * head_dim
    headDim := e.config.HiddenSize / e.config.NumHeads
    
    // Compute attention scores
    // scores = query * key^T / sqrt(head_dim)
    keyTranspose := e.transpose(key)
    scores, err := e.ops.MatMul(query, keyTranspose)
    if err != nil {
        return nil, err
    }
    
    // Scale by sqrt(head_dim)
    scale := float32(1.0 / math.Sqrt(float64(headDim)))
    scores = e.scalarMultiply(scores, scale)
    
    // Apply softmax to get attention weights
    attnWeights, err := e.ops.Softmax(scores)
    if err != nil {
        return nil, err
    }
    
    // Apply attention weights to values
    attnOutput, err := e.ops.MatMul(attnWeights, value)
    if err != nil {
        return nil, err
    }
    
    // Project back to hidden size
    outWeight := e.weights[fmt.Sprintf("layer_%d.attn.out_proj.weight", layerIdx)]
    output, err := e.ops.MatMul(attnOutput, outWeight)
    if err != nil {
        return nil, err
    }
    
    return output, nil
}

// feedForward implements the feed-forward network
func (e *InferenceEngine) feedForward(input *Tensor, layerIdx int) (*Tensor, error) {
    // First linear layer (expansion)
    fc1Weight := e.weights[fmt.Sprintf("layer_%d.ffn.fc1.weight", layerIdx)]
    hidden, err := e.ops.MatMul(input, fc1Weight)
    if err != nil {
        return nil, err
    }
    
    // Apply activation (GELU)
    activated, err := e.ops.GELU(hidden)
    if err != nil {
        return nil, err
    }
    
    // Second linear layer (projection back)
    fc2Weight := e.weights[fmt.Sprintf("layer_%d.ffn.fc2.weight", layerIdx)]
    output, err := e.ops.MatMul(activated, fc2Weight)
    if err != nil {
        return nil, err
    }
    
    return output, nil
}

// applyLayerNorm applies layer normalization
func (e *InferenceEngine) applyLayerNorm(input *Tensor, name string) (*Tensor, error) {
    gamma := e.weights[name+".weight"]
    beta := e.weights[name+".bias"]
    
    return e.ops.LayerNorm(input, gamma, beta, e.config.NormEpsilon)
}

// sampleToken samples the next token from logits
func (e *InferenceEngine) sampleToken(logits *Tensor, temperature float32) int {
    // Convert logits to probabilities
    // Apply temperature scaling
    scaledLogits := e.scalarMultiply(logits, 1.0/temperature)
    
    // Apply softmax
    probs, err := e.ops.Softmax(scaledLogits)
    if err != nil {
        // Fallback to greedy sampling
        return e.greedySample(logits)
    }
    
    // Move probabilities to CPU for sampling
    if err := e.ops.ToCPU(probs); err != nil {
        return e.greedySample(logits)
    }
    
    // Sample from the distribution
    return e.multinomialSample(probs)
}

// greedySample selects the token with highest probability
func (e *InferenceEngine) greedySample(logits *Tensor) int {
    // Move to CPU if needed
    e.ops.ToCPU(logits)
    
    // Find maximum logit
    maxIdx := 0
    maxVal := float32(math.Inf(-1))
    
    for i := 0; i < e.config.VocabSize; i++ {
        val := e.getFloat32(logits, i)
        if val > maxVal {
            maxVal = val
            maxIdx = i
        }
    }
    
    return maxIdx
}

// multinomialSample samples from a probability distribution
func (e *InferenceEngine) multinomialSample(probs *Tensor) int {
    // Get cumulative probabilities
    cumProbs := make([]float32, e.config.VocabSize)
    cumSum := float32(0.0)
    
    for i := 0; i < e.config.VocabSize; i++ {
        cumSum += e.getFloat32(probs, i)
        cumProbs[i] = cumSum
    }
    
    // Sample a random number
    r := rand.Float32() * cumSum
    
    // Find the token
    for i, cumProb := range cumProbs {
        if r <= cumProb {
            return i
        }
    }
    
    return e.config.VocabSize - 1
}

// Helper functions for tensor manipulation

func (e *InferenceEngine) transpose(t *Tensor) *Tensor {
    // Simplified transpose for 2D tensors
    if len(t.Shape) != 2 {
        return t
    }
    
    m, n := t.Shape[0], t.Shape[1]
    result := NewTensor([]int{n, m}, t.DType)
    
    // This is a placeholder - real implementation would transpose the data
    return result
}

func (e *InferenceEngine) scalarMultiply(t *Tensor, scalar float32) *Tensor {
    // Multiply all elements by a scalar
    result := NewTensor(t.Shape, t.DType)
    
    // This is a placeholder - real implementation would multiply each element
    copy(result.Data, t.Data)
    return result
}

func (e *InferenceEngine) sliceLastToken(t *Tensor, seqLen int) *Tensor {
    // Extract the last token's hidden state
    // This is a placeholder - real implementation would slice the tensor
    return t
}

func (e *InferenceEngine) getFloat32(t *Tensor, idx int) float32 {
    // Extract a float32 value from a tensor
    bits := binary.LittleEndian.Uint32(t.Data[idx*4 : (idx+1)*4])
    return math.Float32frombits(bits)
}

The InferenceEngine ties everything together. The Generate method implements autoregressive text generation. We encode the prompt, run forward passes to get logits for the next token, sample from the probability distribution, and repeat until we reach the maximum token count or generate an end-of-sequence token.

The forward method implements the transformer architecture. We look up token embeddings, process them through multiple transformer layers, apply final normalization, and project to vocabulary logits. Each transformer layer consists of multi-head attention followed by a feed-forward network, with residual connections and layer normalization.

The multiHeadAttention method computes attention scores between all token pairs, applies softmax to get attention weights, and uses these weights to combine value vectors. The feedForward method applies two linear transformations with a GELU activation in between.

Sampling strategies affect generation quality. Greedy sampling always picks the highest-probability token, which can lead to repetitive text. Temperature sampling adds randomness by scaling logits before softmax. Higher temperatures increase randomness, while lower temperatures make the model more confident and deterministic.

PERFORMANCE OPTIMIZATIONS: MAKING IT FAST

With a working inference engine, we turn our attention to performance. Several optimization techniques can dramatically improve speed without changing the fundamental architecture.

The first optimization is kernel fusion. Many operations can be combined to reduce memory bandwidth. For example, we can fuse layer normalization with the subsequent matrix multiplication, computing both in a single kernel pass.

// FusedLayerNormMatMul combines layer normalization and matrix multiplication
// This reduces memory bandwidth by avoiding intermediate tensor materialization
func (ops *CUDAOps) FusedLayerNormMatMul(input, gamma, beta, weight *Tensor, epsilon float32) (*Tensor, error) {
    // This would be implemented as a custom CUDA kernel
    // For now, we show the concept with separate operations
    
    normalized, err := ops.LayerNorm(input, gamma, beta, epsilon)
    if err != nil {
        return nil, err
    }
    
    result, err := ops.MatMul(normalized, weight)
    if err != nil {
        return nil, err
    }
    
    return result, nil
}

A real implementation would write a custom CUDA kernel that reads input once, computes normalization, and immediately performs the matrix multiplication. This eliminates one round-trip to global memory, which can be the bottleneck on modern GPUs.

The second optimization is batching. Instead of processing one sequence at a time, we can process multiple sequences in parallel. This better utilizes GPU resources.

// BatchedGenerate processes multiple prompts in parallel
// This improves GPU utilization and throughput
func (e *InferenceEngine) BatchedGenerate(prompts []string, maxTokens int, temperature float32) ([]string, error) {
    batchSize := len(prompts)
    
    // Encode all prompts
    allTokens := make([][]int, batchSize)
    for i, prompt := range prompts {
        tokens, err := e.tokenizer.Encode(prompt)
        if err != nil {
            return nil, err
        }
        allTokens[i] = tokens
    }
    
    // Pad sequences to same length
    maxLen := 0
    for _, tokens := range allTokens {
        if len(tokens) > maxLen {
            maxLen = len(tokens)
        }
    }
    
    paddedTokens := make([][]int, batchSize)
    for i, tokens := range allTokens {
        paddedTokens[i] = make([]int, maxLen)
        copy(paddedTokens[i], tokens)
        // Pad with zeros (or a special padding token)
        for j := len(tokens); j < maxLen; j++ {
            paddedTokens[i][j] = 0
        }
    }
    
    // Generate tokens for all sequences in parallel
    // This is a simplified version - real implementation would handle
    // variable-length sequences and dynamic batching
    
    results := make([]string, batchSize)
    for i := range results {
        // For now, fall back to sequential generation
        // A real implementation would batch the forward passes
        result, err := e.Generate(prompts[i], maxTokens, temperature)
        if err != nil {
            return nil, err
        }
        results[i] = result
    }
    
    return results, nil
}

Batching requires careful handling of variable-length sequences. We pad shorter sequences to match the longest one, using attention masks to ignore padding tokens. The GPU processes all sequences simultaneously, performing the same operations on different data.

The third optimization is quantization-aware operations. Instead of dequantizing weights for every operation, we can perform operations directly on quantized data.

// QuantizedMatMul performs matrix multiplication with quantized weights
// This avoids dequantization overhead and uses specialized kernels
func (ops *CUDAOps) QuantizedMatMul(input *Tensor, weight *Tensor, scale float32) (*Tensor, error) {
    // Ensure input is on GPU
    if err := ops.ToDevice(input); err != nil {
        return nil, err
    }
    if err := ops.ToDevice(weight); err != nil {
        return nil, err
    }
    
    // For INT8 quantization, we can use specialized CUDA kernels
    // These kernels perform integer matrix multiplication followed by scaling
    
    if weight.DType == Int8 {
        // Use INT8 tensor cores on modern NVIDIA GPUs
        // This is significantly faster than FP32 operations
        
        // Placeholder for actual INT8 GEMM call
        // Real implementation would use cublasGemmEx with CUDA_R_8I
        
        result := NewTensor([]int{input.Shape[0], weight.Shape[1]}, Float32)
        // Perform quantized matrix multiplication
        // Then scale the result
        
        return result, nil
    }
    
    // Fall back to standard matrix multiplication
    return ops.MatMul(input, weight)
}

Modern GPUs have specialized hardware for low-precision arithmetic. NVIDIA's tensor cores can perform INT8 matrix multiplications much faster than FP32 operations. By keeping weights quantized and using these specialized units, we achieve both memory savings and speed improvements.

The fourth optimization is KV cache management. Attention computation is quadratic in sequence length, but we can cache key and value tensors from previous tokens.

// UpdateKVCache updates the key-value cache for a layer
// This allows incremental attention computation during generation
func (e *InferenceEngine) UpdateKVCache(layerIdx int, newKeys, newValues *Tensor) error {
    cache := e.kvCache[layerIdx]
    
    if cache.keys == nil {
        // First time - just store the keys and values
        cache.keys = newKeys
        cache.values = newValues
        cache.seqLen = newKeys.Shape[1]
    } else {
        // Concatenate new keys/values with cached ones
        cache.keys = e.concatenateTensors(cache.keys, newKeys, 1)
        cache.values = e.concatenateTensors(cache.values, newValues, 1)
        cache.seqLen += newKeys.Shape[1]
    }
    
    return nil
}

// GetCachedKV retrieves cached keys and values for a layer
func (e *InferenceEngine) GetCachedKV(layerIdx int) (*Tensor, *Tensor) {
    cache := e.kvCache[layerIdx]
    return cache.keys, cache.values
}

// concatenateTensors concatenates two tensors along a dimension
func (e *InferenceEngine) concatenateTensors(a, b *Tensor, dim int) *Tensor {
    // Create new tensor with combined size
    newShape := make([]int, len(a.Shape))
    copy(newShape, a.Shape)
    newShape[dim] += b.Shape[dim]
    
    result := NewTensor(newShape, a.DType)
    
    // Copy data from both tensors
    // This is a simplified version - real implementation would handle
    // arbitrary dimensions and strides
    
    return result
}

The KV cache stores previously computed key and value tensors. When generating the next token, we only compute attention for the new token against all previous tokens. This reduces computation from quadratic to linear in the number of generated tokens.

The fifth optimization is memory pooling. Allocating and freeing GPU memory for every tensor is expensive. We can pre-allocate a memory pool and reuse buffers.

// MemoryPool manages a pool of reusable GPU buffers
// This reduces allocation overhead during inference
type MemoryPool struct {
    device   DeviceType
    buffers  map[int][]unsafe.Pointer  // Size -> available buffers
    inUse    map[unsafe.Pointer]int    // Buffer -> size
    mu       sync.Mutex
}

// NewMemoryPool creates a new memory pool
func NewMemoryPool(device DeviceType) *MemoryPool {
    return &MemoryPool{
        device:  device,
        buffers: make(map[int][]unsafe.Pointer),
        inUse:   make(map[unsafe.Pointer]int),
    }
}

// Allocate gets a buffer from the pool or allocates a new one
func (p *MemoryPool) Allocate(size int) (unsafe.Pointer, error) {
    p.mu.Lock()
    defer p.mu.Unlock()
    
    // Round size up to nearest power of 2 for better reuse
    allocSize := p.roundUpPowerOf2(size)
    
    // Check if we have a buffer of this size
    if buffers, ok := p.buffers[allocSize]; ok && len(buffers) > 0 {
        // Reuse an existing buffer
        buffer := buffers[len(buffers)-1]
        p.buffers[allocSize] = buffers[:len(buffers)-1]
        p.inUse[buffer] = allocSize
        return buffer, nil
    }
    
    // Allocate a new buffer
    var buffer unsafe.Pointer
    switch p.device {
    case DeviceCUDA:
        buffer = C.allocateGPUMemory(C.size_t(allocSize))
    case DeviceMetal:
        buffer = C.allocateMetalBuffer(C.size_t(allocSize))
    default:
        return nil, fmt.Errorf("unsupported device for memory pool: %s", p.device)
    }
    
    if buffer == nil {
        return nil, fmt.Errorf("failed to allocate %d bytes", allocSize)
    }
    
    p.inUse[buffer] = allocSize
    return buffer, nil
}

// Free returns a buffer to the pool for reuse
func (p *MemoryPool) Free(buffer unsafe.Pointer) {
    p.mu.Lock()
    defer p.mu.Unlock()
    
    size, ok := p.inUse[buffer]
    if !ok {
        return  // Buffer not from this pool
    }
    
    delete(p.inUse, buffer)
    p.buffers[size] = append(p.buffers[size], buffer)
}

// roundUpPowerOf2 rounds a size up to the nearest power of 2
func (p *MemoryPool) roundUpPowerOf2(size int) int {
    power := 1
    for power < size {
        power *= 2
    }
    return power
}

// Clear releases all buffers in the pool
func (p *MemoryPool) Clear() {
    p.mu.Lock()
    defer p.mu.Unlock()
    
    // Free all buffers
    for _, buffers := range p.buffers {
        for _, buffer := range buffers {
            switch p.device {
            case DeviceCUDA:
                C.freeGPUMemory(buffer)
            case DeviceMetal:
                C.freeMetalBuffer(buffer)
            }
        }
    }
    
    p.buffers = make(map[int][]unsafe.Pointer)
    p.inUse = make(map[unsafe.Pointer]int)
}

The memory pool maintains lists of available buffers for different sizes. When we need a buffer, we first check the pool. If a suitable buffer exists, we reuse it. Otherwise, we allocate a new one. When we finish with a buffer, we return it to the pool instead of freeing it. This dramatically reduces allocation overhead, especially during autoregressive generation where we allocate many temporary tensors.

PRACTICAL USAGE EXAMPLES

Let us see how to use our inference engine in practice. We start by loading a model and generating text.

package main

import (
    "fmt"
    "log"
    
    "your_project/inference"
)

func main() {
    // Load model from GGUF file
    adapter := inference.NewGGUFAdapter()
    config, weights, err := adapter.Load("model.gguf")
    if err != nil {
        log.Fatalf("Failed to load model: %v", err)
    }
    
    fmt.Printf("Loaded model with %d layers, %d hidden size\n",
        config.NumLayers, config.HiddenSize)
    
    // Create tokenizer
    // In practice, you would load vocabulary and merges from files
    vocab := make(map[string]int)
    merges := make([][]string, 0)
    tokenizer := inference.NewBPETokenizer(vocab, merges)
    
    // Create inference engine
    engine, err := inference.NewInferenceEngine(config, weights, tokenizer)
    if err != nil {
        log.Fatalf("Failed to create engine: %v", err)
    }
    
    // Generate text
    prompt := "Once upon a time"
    result, err := engine.Generate(prompt, 100, 0.8)
    if err != nil {
        log.Fatalf("Generation failed: %v", err)
    }
    
    fmt.Printf("Generated text:\n%s\n", result)
}

This example demonstrates the complete workflow. We load a model using the GGUF adapter, create a tokenizer, initialize the inference engine, and generate text. The engine automatically detects available GPU hardware and uses it for acceleration.

For production use, we might want more control over the generation process. Here is an example with custom sampling and streaming output.

func streamingGeneration() {
    // Setup (same as before)
    adapter := inference.NewGGUFAdapter()
    config, weights, _ := adapter.Load("model.gguf")
    tokenizer := inference.NewBPETokenizer(vocab, merges)
    engine, _ := inference.NewInferenceEngine(config, weights, tokenizer)
    
    // Encode prompt
    prompt := "The future of AI is"
    tokens, _ := tokenizer.Encode(prompt)
    
    // Generate tokens one at a time with streaming output
    fmt.Printf("Prompt: %s", prompt)
    
    for i := 0; i < 50; i++ {
        // Run forward pass
        logits, err := engine.Forward(tokens)
        if err != nil {
            log.Printf("Error: %v", err)
            break
        }
        
        // Sample next token with temperature
        nextToken := engine.SampleToken(logits, 0.7)
        
        // Decode and print immediately
        tokenText, _ := tokenizer.Decode([]int{nextToken})
        fmt.Printf("%s", tokenText)
        
        // Add to sequence
        tokens = append(tokens, nextToken)
        
        // Check for end of sequence
        if nextToken == tokenizer.VocabSize()-1 {
            break
        }
    }
    
    fmt.Println()
}

This example shows streaming generation where we print each token as it is generated. This provides better user experience for interactive applications, as users see output immediately rather than waiting for the entire sequence.

For batch processing, we can use the batched generation method to process multiple prompts efficiently.

func batchProcessing() {
    // Setup
    adapter := inference.NewGGUFAdapter()
    config, weights, _ := adapter.Load("model.gguf")
    tokenizer := inference.NewBPETokenizer(vocab, merges)
    engine, _ := inference.NewInferenceEngine(config, weights, tokenizer)
    
    // Multiple prompts
    prompts := []string{
        "The meaning of life is",
        "Artificial intelligence will",
        "In the year 2050,",
    }
    
    // Generate in batch
    results, err := engine.BatchedGenerate(prompts, 50, 0.8)
    if err != nil {
        log.Fatalf("Batch generation failed: %v", err)
    }
    
    // Print results
    for i, result := range results {
        fmt.Printf("Prompt %d: %s\n", i+1, prompts[i])
        fmt.Printf("Result: %s\n\n", result)
    }
}

Batched generation processes multiple prompts in parallel, significantly improving throughput. This is ideal for offline processing or serving multiple users simultaneously.

FUTURE EXTENSIONS AND CONCLUSION

Our inference engine provides a solid foundation, but many extensions are possible. First, we could add support for more model architectures. Currently, we implement a generic transformer, but specific models like GPT, LLaMA, or Mistral have architectural variations. We could create architecture-specific modules that inherit from a base transformer class.

Second, we could implement advanced sampling strategies. Top-k sampling restricts choices to the k most probable tokens. Top-p (nucleus) sampling selects from the smallest set of tokens whose cumulative probability exceeds p. These strategies often produce better text than simple temperature sampling.

Third, we could add speculative decoding. This technique uses a smaller, faster model to propose multiple tokens, which a larger model then verifies. When the small model guesses correctly, we generate multiple tokens per forward pass, significantly increasing throughput.

Fourth, we could implement continuous batching. Instead of waiting for all sequences in a batch to finish, we could dynamically add new sequences as others complete. This maximizes GPU utilization in serving scenarios.

Fifth, we could add support for multi-GPU inference. Large models often do not fit on a single GPU. We could implement tensor parallelism to split layers across GPUs or pipeline parallelism to assign different layers to different GPUs.

Sixth, we could optimize memory usage further with techniques like flash attention. This algorithm computes attention without materializing the full attention matrix, dramatically reducing memory requirements for long sequences.

Seventh, we could add model compilation. Instead of interpreting operations at runtime, we could compile the model graph to optimized kernels. This eliminates dispatch overhead and enables whole-program optimizations.

In conclusion, building an LLM inference engine from scratch provides deep insights into how these models work. We have covered the entire stack from low-level tensor operations through GPU acceleration to high-level text generation. The clean architecture with adapters for model formats, backends for different hardware, and quantization schemes makes the system extensible and maintainable.

The key lessons are that LLM inference is fundamentally about efficient matrix operations, that hardware acceleration is essential for practical performance, that quantization enables running large models with limited memory, and that careful architecture design allows supporting diverse formats and hardware without coupling components.

This inference engine demonstrates that Go is a viable choice for ML inference despite being less common than Python in this domain. The language's performance, simplicity, and excellent tooling make it well-suited for building production inference systems. The CGO interface allows leveraging optimized GPU libraries while maintaining Go's clean syntax and robust error handling.

Whether you use this engine in production or simply study it to understand LLM inference better, the principles and techniques apply broadly. Modern AI systems are complex, but by building them piece by piece, we can understand and control every aspect of their behavior.