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 ¶
- Variables
- func Eval(arrays ...*Array)
- func GF2PolymulBatch(mode HQCMode, c, a, b []uint64, count int) error
- func GF2PolymulMod(mode HQCMode, c, a, b []uint64) error
- func GetMemoryInfo() (total, free uint64)
- func HQCDecapsBatch(mode HQCMode, sss, cts, sks []byte, count int) error
- func HQCEncapsBatch(mode HQCMode, cts, sss, pks, seeds []byte, count int) error
- func HQCGPUAvailable() bool
- func HQCGetBackend() string
- func HQCGetThreshold(opType int) int
- func HQCKeypairBatch(mode HQCMode, pks, sks, seeds []byte, count int) error
- func Info() string
- func ReedMullerDecode(mode HQCMode, msg []byte, cdw []uint64) error
- func ReedSolomonDecode(mode HQCMode, msg, cdw []byte) error
- func SetBackend(backend Backend) error
- func Sync() error
- func Synchronize()
- func ZKGPUAvailable() bool
- func ZKGetBackend() string
- func ZKGetDeviceName() string
- func ZKGetThreshold(opType int) int
- type Array
- func Add(a, b *Array) *Array
- func Arange(start, stop, step float64) *Array
- func ArrayFromSlice[T int64 | float64 | float32 | int32](data []T, shape []int, dtype Dtype) *Array
- func Divide(a, b *Array) *Array
- func FromSlice(data []float32, shape []int, dtype Dtype) *Array
- func Full(shape []int, value float64, dtype Dtype) *Array
- func MatMul(a, b *Array) *Array
- func Maximum(a, b *Array) *Array
- func Mean(a *Array, axis ...int) *Array
- func Multiply(a, b *Array) *Array
- func Ones(shape []int, dtype Dtype) *Array
- func Random(shape []int, dtype Dtype) *Array
- func Subtract(a, b *Array) *Array
- func Sum(a *Array, axis ...int) *Array
- func Zeros(shape []int, dtype Dtype) *Array
- type Backend
- type CKKSCiphertext
- type CKKSKeys
- type Context
- func (c *Context) Add(a, b *Array) *Array
- func (c *Context) Arange(start, stop, step float64) *Array
- func (c *Context) ArrayFromSlice(data any, shape []int, dtype Dtype) *Array
- func (c *Context) Close()
- func (c *Context) Divide(a, b *Array) *Array
- func (c *Context) Free(a *Array)
- func (c *Context) FreeStream(s *Stream)
- func (c *Context) FromSlice(data []float32, shape []int, dtype Dtype) *Array
- func (c *Context) Full(shape []int, value float64, dtype Dtype) *Array
- func (c *Context) GPU() *C.LuxGPU
- func (c *Context) GetBackend() Backend
- func (c *Context) GetDevice() *Device
- func (c *Context) MatMul(a, b *Array) *Array
- func (c *Context) Maximum(a, b *Array) *Array
- func (c *Context) Mean(a *Array, axis ...int) *Array
- func (c *Context) Multiply(a, b *Array) *Array
- func (c *Context) NewStream() *Stream
- func (c *Context) Ones(shape []int, dtype Dtype) *Array
- func (c *Context) Random(shape []int, dtype Dtype) *Array
- func (c *Context) SetBackend(backend Backend) error
- func (c *Context) Subtract(a, b *Array) *Array
- func (c *Context) Sum(a *Array, axis ...int) *Array
- func (c *Context) Synchronize()
- func (c *Context) Zeros(shape []int, dtype Dtype) *Array
- type CryptoOps
- type Device
- type DeviceInfo
- type Dtype
- type EcrecoverResult
- type FHEOps
- type Fr256
- func BatchCommitment(values, blindings, salts []Fr256) ([]Fr256, error)
- func BatchNullifier(keys, commitments, indices []Fr256) ([]Fr256, error)
- func MerkleLayer(nodes []Fr256) ([]Fr256, error)
- func MerkleRoot(leaves []Fr256) (Fr256, error)
- func MerkleTree(leaves []Fr256) ([]Fr256, error)
- func Poseidon2Hash(left, right []Fr256) ([]Fr256, error)
- type HQCMode
- type HQCParams
- type LuxErr
- type MLOps
- type Session
- func (s *Session) Backend() Backend
- func (s *Session) Close() error
- func (s *Session) Crypto() CryptoOps
- func (s *Session) Device() Device
- func (s *Session) FHE() FHEOps
- func (s *Session) ML() MLOps
- func (s *Session) SetBackend(b Backend) error
- func (s *Session) Sync() error
- func (s *Session) SyncContext(ctx context.Context) error
- func (s *Session) Tensor() TensorOps
- type SessionOption
- type Signature
- type Stream
- type TFHECiphertext
- type TFHEKeys
- type TFHEParams
- type Tensor
- type TensorOps
Constants ¶
This section is empty.
Variables ¶
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).
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
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" )
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
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ReedMullerDecode ¶
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 ¶
ReedSolomonDecode runs constant-time RS decoding on one codeword. cdw is ParamN1 bytes, msg is ParamK bytes.
func ZKGPUAvailable ¶
func ZKGPUAvailable() bool
ZKGPUAvailable returns true if GPU acceleration is available.
func ZKGetThreshold ¶
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 ArrayFromSlice ¶
ArrayFromSlice creates an array from a typed Go slice with specified shape and dtype. Supports []int64, []float64, []float32, []int32 data types.
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 )
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) ArrayFromSlice ¶
ArrayFromSlice creates an array from a typed slice (Context method)
func (*Context) FreeStream ¶
FreeStream releases a stream's resources
func (*Context) GetBackend ¶
GetBackend returns the current backend for this context
func (*Context) Maximum ¶
Maximum computes element-wise maximum (Context method) Note: Uses host-side fallback since element-wise max is not in core C API
func (*Context) SetBackend ¶
SetBackend sets the compute backend for this context
func (*Context) Synchronize ¶
func (c *Context) Synchronize()
Synchronize waits for all operations (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 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 ¶
BatchCommitment computes batch Poseidon2 commitments. commitment[i] = Poseidon2(Poseidon2(values[i], blindings[i]), salts[i])
func BatchNullifier ¶
BatchNullifier computes batch Poseidon2 nullifiers. nullifier[i] = Poseidon2(Poseidon2(keys[i], commitments[i]), indices[i])
func MerkleLayer ¶
MerkleLayer computes one layer of a Poseidon2 Merkle tree. Input nodes must have even count.
func MerkleRoot ¶
MerkleRoot computes Merkle root from leaves. Leaves are padded to power of 2 if needed.
func MerkleTree ¶
MerkleTree builds complete Merkle tree and returns all internal nodes. Returns n-1 internal nodes for n leaves.
func Poseidon2Hash ¶
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
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 ¶
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 ¶
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) SetBackend ¶
SetBackend switches to a different backend. Returns an error if the backend is not available.
func (*Session) SyncContext ¶
SyncContext waits for pending operations with cancellation support.
type SessionOption ¶
type SessionOption func(*sessionConfig)
SessionOption configures session creation.
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
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.
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.