gpu

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2026 License: BSD-3-Clause Imports: 9 Imported by: 0

Documentation

Overview

Package gpu provides GPU-accelerated ecrecover for batch tx signature verification.

Package gpu provides Go bindings for cross-platform GPU acceleration.

Backends (auto-detected by luxcpp/gpu):

  • Metal: Apple Silicon GPUs (macOS)
  • CUDA: NVIDIA GPUs (Linux/Windows)
  • CPU: Optimized SIMD fallback (all platforms)

The C++ library (luxgpu_core) handles backend selection automatically. Build with CGO_ENABLED=1 for GPU support.

HQC (Hamming Quasi-Cyclic) GPU bindings via the luxcpp/gpu native kernels (libluxgpu_hqc.a). Symbols come from luxcpp/gpu/include/lux/gpu/hqc.h; the canonical CPU implementation in luxcpp/gpu/src/hqc_*.cpp is the byte-equal oracle every backend (Metal / CUDA / WebGPU) must match.

Layering:

luxfi/crypto/hqc   <-- Go consumer (this is what callers import)
luxfi/gpu (here)   <-- thin C ABI binding, threshold routing
luxfi/accel        <-- session / device lifetime
luxcpp/gpu/src     <-- canonical CPU + Metal/CUDA dispatch

Build expects the luxfi sibling-repo layout:

~/work/lux/mlx -> ~/work/luxcpp/gpu (symlink)

so that ${SRCDIR}/../mlx/include resolves to the lux/gpu headers. libluxgpu_hqc.a is statically linked from the same build dir.

Note on the `randombytes` symbol: libluxgpu_hqc.a has unresolved references to PQClean's `randombytes(uint8_t*, size_t)`. The Lux build system intentionally splits the provider out into a separate archive (libluxgpu_hqc_standalone_rng.a) so binaries that supply their own `randombytes` (luxfi/crypto/hqc's randombytes_shim.c under build tag hqc_pqclean, or luxfi/accel/ops/code's code_cpu_randombytes.go strong definition) can avoid linking the shim and get a clean single definition. Linking the shim in here unconditionally collides with those providers. Any consumer that imports luxfi/gpu's HQC entry points reaches them through luxfi/accel or luxfi/crypto/hqc, both of which provide `randombytes`. So we leave the symbol unresolved at the gpu layer and let the higher-level package supply it.

Threshold routing: every entry point inspects the batch count and HQCGetThreshold(opType). Below threshold callers should keep the op on the CPU pure-Go path in crypto/hqc/gpu_nocgo.go to avoid the cgo + device dispatch overhead. The threshold is *advisory*; the C kernel is correct for any count >= 1.

Package gpu provides Go bindings for GPU acceleration. This file contains type definitions shared between CGO and non-CGO builds.

Package gpu provides GPU-accelerated ZK operations via unified luxcpp/gpu. Automatically selects best backend: CUDA > Metal > WebGPU > CPU

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrHQCInvalidArg    = errors.New("hqc: invalid argument")
	ErrHQCInvalidMode   = errors.New("hqc: invalid mode")
	ErrHQCInvalidLength = errors.New("hqc: invalid buffer length")
	ErrHQCOOM           = errors.New("hqc: out of memory")
	ErrHQCDeviceError   = errors.New("hqc: device error")
	ErrHQCNotSupported  = errors.New("hqc: kernel not supported on this backend")
	ErrHQCRNGFailed     = errors.New("hqc: RNG / seed buffer exhausted")
)

Granular HQC error sentinels — produced by the C kernels and translated here. Callers normally only need ErrHQCNotAvailable but these allow precise error handling (e.g. surface RNG starvation distinctly from buffer length mismatch).

View Source
var (
	ErrSessionClosed   = errors.New("session closed")
	ErrBackendNotAvail = errors.New("backend not available")
	ErrNoBackends      = errors.New("no GPU backends available")
	ErrOutOfMemory     = errors.New("out of GPU memory")
	ErrInvalidShape    = errors.New("invalid tensor shape")
)

Common errors

View Source
var (
	// ErrNoGPU is returned when GPU is requested but not available
	ErrNoGPU = errors.New("no GPU available")

	// ErrInvalidBackend is returned for invalid backend selection
	ErrInvalidBackend = errors.New("invalid backend")

	// Version is the GPU library version
	Version = "0.1.0"
)
View Source
var (
	ErrZKInvalidArg = errors.New("zk: invalid argument")
	ErrZKSize       = errors.New("zk: invalid size")
	ErrZKAlloc      = errors.New("zk: allocation failed")
	ErrZKNotImpl    = errors.New("zk: not implemented")
	ErrZKNoDevice   = errors.New("zk: no GPU device available")
)

Error codes from C API

View Source
var ErrHQCNotAvailable = errors.New("HQC operation not available")

ErrHQCNotAvailable is returned when an HQC entry point hits a condition the CGO bindings can't satisfy (mode mismatch, buffer length, RNG starvation). Same sentinel value the non-CGO stub exports so callers can switch on it uniformly.

Functions

func Eval

func Eval(arrays ...*Array)

Eval forces evaluation of lazy operations (no-op in unified API)

func GF2PolymulBatch

func GF2PolymulBatch(mode HQCMode, c, a, b []uint64, count int) error

GF2PolymulBatch computes count independent polymuls in one call. Slot i reads a[i*N:(i+1)*N] and b[i*N:(i+1)*N], writes c[i*N:(i+1)*N]. Failure short-circuits and returns the slot's error code (no partial results are guaranteed).

func GF2PolymulMod

func GF2PolymulMod(mode HQCMode, c, a, b []uint64) error

GF2PolymulMod computes c(x) = a(x) * b(x) mod (X^n - 1) in GF(2)[X] for ONE polynomial. All three buffers must be length VecNSize64 (per HQCParamsFor(mode)); they must be distinct (no aliasing). The kernel is constant-time and identical to PQClean's vect_mul.

func GetMemoryInfo

func GetMemoryInfo() (total, free uint64)

GetMemoryInfo returns total and free GPU memory in bytes.

func HQCDecapsBatch

func HQCDecapsBatch(mode HQCMode, sss, cts, sks []byte, count int) error

HQCDecapsBatch runs count independent decapsulations.

sss layout count * params.shared_secret_bytes
cts layout count * params.ciphertext_bytes
sks layout count * params.secret_key_bytes

Implicit rejection: a tampered ciphertext does NOT error; the corresponding sss slot receives a pseudorandom 64 bytes derived from (sk, ct) (Hofheinz-Hövelmanns-Kiltz construction).

func HQCEncapsBatch

func HQCEncapsBatch(mode HQCMode, cts, sss, pks, seeds []byte, count int) error

HQCEncapsBatch runs count independent encapsulations.

cts   layout count * params.ciphertext_bytes
sss   layout count * params.shared_secret_bytes
pks   layout count * params.public_key_bytes
seeds layout count * 32 bytes (PARAM_K + 16 salt, padded to 32)

func HQCGPUAvailable

func HQCGPUAvailable() bool

HQCGPUAvailable reports whether the HQC kernels are reachable. The C library is linked statically so this is always true when CGO is enabled. (Returns false on the !cgo stub.)

func HQCGetBackend

func HQCGetBackend() string

HQCGetBackend returns the active HQC backend. Right now every platform routes through the canonical CPU oracle in luxcpp/gpu/src/hqc_*.cpp; Metal/CUDA shims will surface here once they override the lux_hqc_* C symbols.

func HQCGetThreshold

func HQCGetThreshold(opType int) int

HQCGetThreshold returns the per-op batch crossover above which the GPU/native path is preferred. Below the threshold callers should keep the op on the CPU pure-Go path to avoid the cgo + device dispatch overhead.

opType 1  GF(2)^N polynomial multiplication
opType 2  Reed-Solomon decode
opType 3  Reed-Muller decode
opType 4  KEM batch encaps
opType 5  KEM batch decaps

func HQCKeypairBatch

func HQCKeypairBatch(mode HQCMode, pks, sks, seeds []byte, count int) error

HQCKeypairBatch generates count HQC keypairs deterministically from the seed buffer.

pks   layout count * params.public_key_bytes
sks   layout count * params.secret_key_bytes
seeds layout count * 48 bytes

func Info

func Info() string

Info returns information about the GPU installation

func ReedMullerDecode

func ReedMullerDecode(mode HQCMode, msg []byte, cdw []uint64) error

ReedMullerDecode runs duplicated RM(1,7) decoding via Fast Hadamard Transform. cdw is the bit-packed VEC_N1N2_SIZE_64 uint64 array, msg is ParamN1 bytes.

func ReedSolomonDecode

func ReedSolomonDecode(mode HQCMode, msg, cdw []byte) error

ReedSolomonDecode runs constant-time RS decoding on one codeword. cdw is ParamN1 bytes, msg is ParamK bytes.

func SetBackend

func SetBackend(backend Backend) error

SetBackend sets the compute backend

func Sync

func Sync() error

Sync waits for all GPU operations to complete.

func Synchronize

func Synchronize()

Synchronize waits for all operations to complete

func ZKGPUAvailable

func ZKGPUAvailable() bool

ZKGPUAvailable returns true if GPU acceleration is available.

func ZKGetBackend

func ZKGetBackend() string

ZKGetBackend returns the active backend name.

func ZKGetDeviceName

func ZKGetDeviceName() string

ZKGetDeviceName returns the GPU device name.

func ZKGetThreshold

func ZKGetThreshold(opType int) int

ZKGetThreshold returns the recommended batch size threshold for GPU. opType: 1=Poseidon2, 2=Merkle, 3=MSM, 4=Commitment, 5=FRI

Types

type Array

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

Array represents a multi-dimensional array

func Add

func Add(a, b *Array) *Array

Add performs element-wise addition

func Arange

func Arange(start, stop, step float64) *Array

Arange creates an array with sequential values

func ArrayFromSlice

func ArrayFromSlice[T int64 | float64 | float32 | int32](data []T, shape []int, dtype Dtype) *Array

ArrayFromSlice creates an array from a typed Go slice with specified shape and dtype. Supports []int64, []float64, []float32, []int32 data types.

func Divide

func Divide(a, b *Array) *Array

Divide performs element-wise division

func FromSlice

func FromSlice(data []float32, shape []int, dtype Dtype) *Array

FromSlice creates an array from a Go slice

func Full

func Full(shape []int, value float64, dtype Dtype) *Array

Full creates an array filled with a value

func MatMul

func MatMul(a, b *Array) *Array

MatMul performs matrix multiplication

func Maximum

func Maximum(a, b *Array) *Array

Maximum computes element-wise maximum

func Mean

func Mean(a *Array, axis ...int) *Array

Mean computes the mean of array elements

func Multiply

func Multiply(a, b *Array) *Array

Multiply performs element-wise multiplication

func Ones

func Ones(shape []int, dtype Dtype) *Array

Ones creates an array filled with ones

func Random

func Random(shape []int, dtype Dtype) *Array

Random creates an array with random values (using Full for now)

func Subtract

func Subtract(a, b *Array) *Array

Subtract performs element-wise subtraction

func Sum

func Sum(a *Array, axis ...int) *Array

Sum computes the sum of array elements

func Zeros

func Zeros(shape []int, dtype Dtype) *Array

Zeros creates a zero-filled array

func (*Array) Handle

func (a *Array) Handle() unsafe.Pointer

Handle returns the internal handle (for validation purposes)

func (*Array) Shape

func (a *Array) Shape() []int

Shape returns the shape of the array

type Backend

type Backend int

Backend represents the compute backend used by Lux GPU

const (
	// Auto automatically selects the best available backend
	Auto Backend = iota
	// CPU uses CPU-only computation with SIMD
	CPU
	// Metal uses Apple Metal GPU acceleration
	Metal
	// CUDA uses NVIDIA CUDA GPU acceleration
	CUDA
	// Dawn uses WebGPU via Dawn (cross-platform)
	Dawn
	// ONNX uses ONNX Runtime (Windows fallback)
	ONNX
)

func GetBackend

func GetBackend() Backend

GetBackend returns the current compute backend

func (Backend) String

func (b Backend) String() string

String returns the string representation of the backend

type CKKSCiphertext

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

CKKSCiphertext is an encrypted vector.

type CKKSKeys

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

CKKSKeys holds CKKS key material.

type Context

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

Context manages GPU runtime and resources

var (
	// DefaultContext is the global GPU context
	DefaultContext *Context
)

func (*Context) Add

func (c *Context) Add(a, b *Array) *Array

Add performs element-wise addition (Context method)

func (*Context) Arange

func (c *Context) Arange(start, stop, step float64) *Array

Arange creates an array with sequential values (Context method)

func (*Context) ArrayFromSlice

func (c *Context) ArrayFromSlice(data any, shape []int, dtype Dtype) *Array

ArrayFromSlice creates an array from a typed slice (Context method)

func (*Context) Close

func (c *Context) Close()

Close releases all resources

func (*Context) Divide

func (c *Context) Divide(a, b *Array) *Array

Divide performs element-wise division (Context method)

func (*Context) Free

func (c *Context) Free(a *Array)

Free releases an array's memory

func (*Context) FreeStream

func (c *Context) FreeStream(s *Stream)

FreeStream releases a stream's resources

func (*Context) FromSlice

func (c *Context) FromSlice(data []float32, shape []int, dtype Dtype) *Array

FromSlice creates an array from a Go slice (Context method)

func (*Context) Full

func (c *Context) Full(shape []int, value float64, dtype Dtype) *Array

Full creates an array filled with a value (Context method)

func (*Context) GPU

func (c *Context) GPU() *C.LuxGPU

GPU returns the underlying C GPU handle

func (*Context) GetBackend

func (c *Context) GetBackend() Backend

GetBackend returns the current backend for this context

func (*Context) GetDevice

func (c *Context) GetDevice() *Device

GetDevice returns the current device for this context

func (*Context) MatMul

func (c *Context) MatMul(a, b *Array) *Array

MatMul performs matrix multiplication (Context method)

func (*Context) Maximum

func (c *Context) Maximum(a, b *Array) *Array

Maximum computes element-wise maximum (Context method) Note: Uses host-side fallback since element-wise max is not in core C API

func (*Context) Mean

func (c *Context) Mean(a *Array, axis ...int) *Array

Mean computes the mean (Context method)

func (*Context) Multiply

func (c *Context) Multiply(a, b *Array) *Array

Multiply performs element-wise multiplication (Context method)

func (*Context) NewStream

func (c *Context) NewStream() *Stream

NewStream creates a new compute stream (Context method)

func (*Context) Ones

func (c *Context) Ones(shape []int, dtype Dtype) *Array

Ones creates an array filled with ones (Context method)

func (*Context) Random

func (c *Context) Random(shape []int, dtype Dtype) *Array

Random creates an array with random values (Context method)

func (*Context) SetBackend

func (c *Context) SetBackend(backend Backend) error

SetBackend sets the compute backend for this context

func (*Context) Subtract

func (c *Context) Subtract(a, b *Array) *Array

Subtract performs element-wise subtraction (Context method)

func (*Context) Sum

func (c *Context) Sum(a *Array, axis ...int) *Array

Sum computes the sum (Context method)

func (*Context) Synchronize

func (c *Context) Synchronize()

Synchronize waits for all operations (Context method)

func (*Context) Zeros

func (c *Context) Zeros(shape []int, dtype Dtype) *Array

Zeros creates a zero-filled array (Context method)

type CryptoOps

type CryptoOps interface {
	// BLS12-381
	BLSVerify(sig, msg, pubkey []byte) (bool, error)
	BLSVerifyBatch(sigs, msgs, pubkeys [][]byte) ([]bool, error)
	BLSAggregate(sigs [][]byte) ([]byte, error)

	// Poseidon hash
	PoseidonHash(inputs [][]byte) ([][]byte, error)
	PoseidonHashBatch(inputs [][][]byte) ([][]byte, error)

	// MSM (multi-scalar multiplication)
	MSM(scalars, points [][]byte) ([]byte, error)

	// KZG commitments
	KZGCommit(poly []byte) ([]byte, error)
	KZGProve(poly []byte, point []byte) ([]byte, error)
	KZGVerify(commitment, proof, point, value []byte) (bool, error)

	// Shamir secret sharing
	ShamirSplit(secret []byte, n, k int) ([][]byte, error)
	ShamirCombine(shares [][]byte) ([]byte, error)
}

CryptoOps provides GPU-accelerated cryptographic operations.

type Device

type Device struct {
	Type   Backend
	ID     int
	Name   string
	Memory int64 // Memory in bytes
}

Device represents a compute device (CPU or GPU)

func GetDevice

func GetDevice() *Device

GetDevice returns the current compute device

type DeviceInfo

type DeviceInfo = Device

DeviceInfo is an alias for Device (for compatibility)

type Dtype

type Dtype int

Dtype represents tensor data types.

const (
	Float32 Dtype = iota
	Float64
	Float16
	BFloat16
	Int32
	Int64
	Uint32
	Uint64
	Bool
)

func (Dtype) Size

func (d Dtype) Size() int

Size returns bytes per element.

func (Dtype) String

func (d Dtype) String() string

String returns the dtype name.

type EcrecoverResult

type EcrecoverResult struct {
	Address [20]byte // recovered Ethereum address
	Valid   bool     // true if recovery succeeded
}

EcrecoverResult holds the output of a single ecrecover operation.

func BatchEcrecover

func BatchEcrecover(sigs []Signature) ([]EcrecoverResult, error)

BatchEcrecover recovers Ethereum addresses from a batch of signatures using GPU-accelerated secp256k1 ecrecover.

type FHEOps

type FHEOps interface {
	// NTT (Number Theoretic Transform)
	NTTForward(poly []uint64, modulus uint64) ([]uint64, error)
	NTTInverse(poly []uint64, modulus uint64) ([]uint64, error)
	NTTBatch(polys [][]uint64, modulus uint64) ([][]uint64, error)

	// TFHE operations
	TFHEKeyGen(params TFHEParams) (*TFHEKeys, error)
	TFHEEncrypt(keys *TFHEKeys, bit bool) (*TFHECiphertext, error)
	TFHEDecrypt(keys *TFHEKeys, ct *TFHECiphertext) (bool, error)
	TFHEAnd(keys *TFHEKeys, a, b *TFHECiphertext) (*TFHECiphertext, error)
	TFHEOr(keys *TFHEKeys, a, b *TFHECiphertext) (*TFHECiphertext, error)
	TFHENot(keys *TFHEKeys, a *TFHECiphertext) (*TFHECiphertext, error)
	TFHEBootstrap(keys *TFHEKeys, ct *TFHECiphertext) (*TFHECiphertext, error)

	// CKKS operations
	CKKSEncrypt(keys *CKKSKeys, values []float64) (*CKKSCiphertext, error)
	CKKSDecrypt(keys *CKKSKeys, ct *CKKSCiphertext) ([]float64, error)
	CKKSAdd(a, b *CKKSCiphertext) (*CKKSCiphertext, error)
	CKKSMul(keys *CKKSKeys, a, b *CKKSCiphertext) (*CKKSCiphertext, error)
	CKKSRotate(keys *CKKSKeys, ct *CKKSCiphertext, steps int) (*CKKSCiphertext, error)
}

FHEOps provides GPU-accelerated FHE operations.

type Fr256

type Fr256 [4]uint64

Fr256 represents a 256-bit field element (BN254 scalar field). Uses 4 x 64-bit limbs in little-endian order.

func BatchCommitment

func BatchCommitment(values, blindings, salts []Fr256) ([]Fr256, error)

BatchCommitment computes batch Poseidon2 commitments. commitment[i] = Poseidon2(Poseidon2(values[i], blindings[i]), salts[i])

func BatchNullifier

func BatchNullifier(keys, commitments, indices []Fr256) ([]Fr256, error)

BatchNullifier computes batch Poseidon2 nullifiers. nullifier[i] = Poseidon2(Poseidon2(keys[i], commitments[i]), indices[i])

func MerkleLayer

func MerkleLayer(nodes []Fr256) ([]Fr256, error)

MerkleLayer computes one layer of a Poseidon2 Merkle tree. Input nodes must have even count.

func MerkleRoot

func MerkleRoot(leaves []Fr256) (Fr256, error)

MerkleRoot computes Merkle root from leaves. Leaves are padded to power of 2 if needed.

func MerkleTree

func MerkleTree(leaves []Fr256) ([]Fr256, error)

MerkleTree builds complete Merkle tree and returns all internal nodes. Returns n-1 internal nodes for n leaves.

func Poseidon2Hash

func Poseidon2Hash(left, right []Fr256) ([]Fr256, error)

Poseidon2Hash computes batch Poseidon2 hashes. Returns hash outputs where out[i] = Poseidon2(left[i], right[i]).

type HQCMode

type HQCMode int

HQCMode selects the parameter set. Bit pattern matches the C LuxHQCMode enum.

const (
	HQC128 HQCMode = HQCMode(C.LUX_HQC_128)
	HQC192 HQCMode = HQCMode(C.LUX_HQC_192)
	HQC256 HQCMode = HQCMode(C.LUX_HQC_256)
)

type HQCParams

type HQCParams struct {
	PublicKeyBytes    int
	SecretKeyBytes    int
	CiphertextBytes   int
	SharedSecretBytes int
	ParamN            int
	VecNSize64        int
	ParamN1           int
	ParamN2           int
	ParamK            int
}

HQCParams describes the byte sizes for one parameter set. Values come from the C library so they cannot drift from the canonical PQClean reference.

func HQCParamsFor

func HQCParamsFor(mode HQCMode) (HQCParams, error)

HQCParamsFor returns the canonical sizes for mode. Wraps lux_hqc_params() in the C header.

type LuxErr

type LuxErr = error

LuxErr is an alias for error returns from cgo wrappers, with a few well-known sentinels for the common return codes.

type MLOps

type MLOps interface {
	// Matrix operations
	GEMM(a, b *Tensor, alpha, beta float32, transA, transB bool) (*Tensor, error)
	BatchMatMul(a, b *Tensor) (*Tensor, error)

	// Attention
	ScaledDotProductAttention(q, k, v *Tensor, mask *Tensor) (*Tensor, error)
	MultiHeadAttention(q, k, v *Tensor, numHeads int) (*Tensor, error)

	// Activations
	ReLU(t *Tensor) (*Tensor, error)
	GELU(t *Tensor) (*Tensor, error)
	Softmax(t *Tensor, axis int) (*Tensor, error)
	LayerNorm(t *Tensor, gamma, beta *Tensor) (*Tensor, error)

	// Convolution
	Conv2D(input, weight *Tensor, stride, padding []int) (*Tensor, error)
	MaxPool2D(input *Tensor, kernelSize, stride []int) (*Tensor, error)

	// Quantization
	Quantize(t *Tensor, bits int) (*Tensor, float32, int32, error)
	Dequantize(t *Tensor, scale float32, zeroPoint int32) (*Tensor, error)
}

MLOps provides GPU-accelerated ML operations.

type Session

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

Session represents a GPU compute session. It manages device resources and provides access to compute operations.

func DefaultSession

func DefaultSession() (*Session, error)

DefaultSession returns the global default session. It auto-detects the best available backend.

func NewSession

func NewSession(opts ...SessionOption) (*Session, error)

NewSession creates a new GPU session with the specified options.

func (*Session) Backend

func (s *Session) Backend() Backend

Backend returns the current backend.

func (*Session) Close

func (s *Session) Close() error

Close releases session resources.

func (*Session) Crypto

func (s *Session) Crypto() CryptoOps

Crypto returns cryptographic operations.

func (*Session) Device

func (s *Session) Device() Device

Device returns the current device info.

func (*Session) FHE

func (s *Session) FHE() FHEOps

FHE returns FHE operations.

func (*Session) ML

func (s *Session) ML() MLOps

ML returns machine learning operations.

func (*Session) SetBackend

func (s *Session) SetBackend(b Backend) error

SetBackend switches to a different backend. Returns an error if the backend is not available.

func (*Session) Sync

func (s *Session) Sync() error

Sync waits for all pending operations to complete.

func (*Session) SyncContext

func (s *Session) SyncContext(ctx context.Context) error

SyncContext waits for pending operations with cancellation support.

func (*Session) Tensor

func (s *Session) Tensor() TensorOps

Tensor returns the tensor operations interface.

type SessionOption

type SessionOption func(*sessionConfig)

SessionOption configures session creation.

func WithBackend

func WithBackend(b Backend) SessionOption

WithBackend sets the desired backend.

func WithDevice

func WithDevice(index int) SessionOption

WithDevice sets the device index for multi-GPU systems.

type Signature

type Signature struct {
	R       [32]byte // r component (big-endian, left-padded)
	S       [32]byte // s component (big-endian, left-padded)
	V       uint8    // recovery id (0 or 1)
	MsgHash [32]byte // Keccak256 signing hash
}

Signature holds the components needed for secp256k1 ecrecover.

type Stream

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

Stream represents a compute stream for async operations

func NewStream

func NewStream() *Stream

NewStream creates a new compute stream

type TFHECiphertext

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

TFHECiphertext is an encrypted bit.

type TFHEKeys

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

TFHEKeys holds TFHE key material.

type TFHEParams

type TFHEParams struct {
	N            int // LWE dimension
	K            int // RLWE dimension
	SecurityBits int // Target security level (80, 128, etc)
}

TFHEParams holds TFHE scheme parameters.

type Tensor

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

Tensor represents a GPU tensor.

func (*Tensor) Dtype

func (t *Tensor) Dtype() Dtype

Dtype returns the element type.

func (*Tensor) Shape

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

Shape returns the tensor dimensions.

func (*Tensor) Size

func (t *Tensor) Size() int

Size returns total number of elements.

type TensorOps

type TensorOps interface {
	// Creation
	Zeros(shape []int, dtype Dtype) (*Tensor, error)
	Ones(shape []int, dtype Dtype) (*Tensor, error)
	Full(shape []int, value float64, dtype Dtype) (*Tensor, error)
	FromSlice(data any, shape []int, dtype Dtype) (*Tensor, error)

	// Arithmetic
	Add(a, b *Tensor) (*Tensor, error)
	Sub(a, b *Tensor) (*Tensor, error)
	Mul(a, b *Tensor) (*Tensor, error)
	Div(a, b *Tensor) (*Tensor, error)
	MatMul(a, b *Tensor) (*Tensor, error)

	// Reductions
	Sum(t *Tensor, axis ...int) (*Tensor, error)
	Mean(t *Tensor, axis ...int) (*Tensor, error)
	Max(t *Tensor, axis ...int) (*Tensor, error)
	Min(t *Tensor, axis ...int) (*Tensor, error)

	// Shape operations
	Reshape(t *Tensor, shape []int) (*Tensor, error)
	Transpose(t *Tensor, axes ...int) (*Tensor, error)
	Concat(tensors []*Tensor, axis int) (*Tensor, error)
}

TensorOps provides tensor creation and manipulation.

Jump to

Keyboard shortcuts

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