capi

package
v1.2.2 Latest Latest
Warning

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

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

Documentation

Overview

Package capi provides CGO bindings to the lux-accel C library.

Library resolution order:

  1. System paths (/usr/local/lib, /usr/lib)
  2. Homebrew paths (/opt/homebrew/lib)
  3. Local luxcpp install (../../../luxcpp/install/lib)

Install the library using one of:

  • make install-system (from lux/accel)
  • make build-deps && make install-system (build from luxcpp source)
  • scripts/fetch-luxcpp.sh accel (download pre-built)

Package capi — embed the public C header so `go mod vendor` carries it into downstream consumers' vendor trees. Without an embed reference, the vendor tool strips non-Go files from internal/capi/include/, breaking fresh-clone builds of vendored consumers (luxfi/kms, luxfi/node).

The embedded file is the same physical header that capi.go's CFLAGS `-I${SRCDIR}/include` exposes to cgo; we just need the embed directive so the build system keeps it on disk after vendoring.

Package capi default-build stub implementations.

One and only one of `stub_default.go` or `real.go` is in any given build. The selector is the `lux_accel_real` build tag:

go build ./...                          # this file is compiled,
                                        # every C entry returns
                                        # LUX_NO_BACKEND. Portable
                                        # CPU-only binary.

go build -tags lux_accel_real ./...     # real.go is compiled instead,
                                        # binary links -lluxaccel and
                                        # dispatches to the native
                                        # CUDA / Metal plugin.

History: an earlier revision used `__attribute__((weak))` on every stub and tried to override at link time when libluxaccel was present. Modern linkers with --as-needed default resolved the references against the weak stubs (already in the Go object) and dropped the DT_NEEDED entry for libluxaccel entirely. Result: GPU paths silently ran on CPU. Audit on a Spark GB10 host (2026-06-05) measured 9-10% SM during a full ML-DSA bench that was supposed to be GPU-accelerated. The build-tag split removes the weak-symbol ambiguity: either the stub bodies compile, or the link to the real library does — never both.

All stubs return LUX_NO_BACKEND. The Go-side ops dispatcher (see `crypto/backend.Resolve` in luxfi/crypto and `ops/lattice/lattice.go` in this module) maps LUX_NO_BACKEND to a per-element CPU fallback, so default-tag binaries remain functionally complete — just slower.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrOutOfMemory     = errors.New("out of memory")
	ErrInvalidArgument = errors.New("invalid argument")
	ErrNotSupported    = errors.New("not supported")
	ErrNoBackends      = errors.New("no backends")
	ErrKernelFailed    = errors.New("kernel failed")
)

Error types matching C library status codes.

Functions

func Attention

func Attention(session *Session, q, k, v, output *Tensor, scale float32) error

Attention computes attention.

func BFVAdd

func BFVAdd(session *Session, ct1, ct2, result *Tensor) error

BFVAdd adds BFV ciphertexts.

func BFVDecrypt

func BFVDecrypt(session *Session, ciphertext, sk, plaintext *Tensor) error

BFVDecrypt decrypts BFV.

func BFVEncrypt

func BFVEncrypt(session *Session, plaintext, pk, ciphertext *Tensor) error

BFVEncrypt encrypts with BFV.

func BFVMultiply

func BFVMultiply(session *Session, ct1, ct2, relinKey, result *Tensor) error

BFVMultiply multiplies BFV ciphertexts.

func BLSVerifyBatch

func BLSVerifyBatch(session *Session, messages, signatures, pubkeys, results *Tensor) error

BLSVerifyBatch verifies BLS signatures.

func BackendCount

func BackendCount() int

BackendCount returns the number of available backends.

func BackendTypeAt

func BackendTypeAt(index int) int

BackendTypeAt returns the backend type at index.

func ComputeTWAP

func ComputeTWAP(session *Session, prices, timestamps, twap *Tensor, start, end uint64) error

ComputeTWAP computes time-weighted average price.

func ConstantProductSwap

func ConstantProductSwap(session *Session, reserveX, reserveY, amountIn, amountOut *Tensor, xToY bool, fee float32) error

ConstantProductSwap computes AMM swap.

func DeviceCount

func DeviceCount(backend int) int

DeviceCount returns the number of devices for a backend.

func DilithiumSign

func DilithiumSign(session *Session, msg, sk, sig *Tensor) error

DilithiumSign signs a message.

func DilithiumVerify

func DilithiumVerify(session *Session, msg, sig, pk *Tensor) (bool, error)

DilithiumVerify verifies a signature.

func ECDSAVerifyBatch

func ECDSAVerifyBatch(session *Session, messages, signatures, pubkeys, results *Tensor) error

ECDSAVerifyBatch verifies ECDSA signatures.

func Ed25519VerifyBatch

func Ed25519VerifyBatch(session *Session, messages, signatures, pubkeys, results *Tensor) error

Ed25519VerifyBatch verifies Ed25519 signatures.

func GELU

func GELU(session *Session, input, output *Tensor) error

GELU applies GELU activation.

func GetError

func GetError() string

GetError returns the last error message.

func INTT

func INTT(session *Session, input, output, invRoots *Tensor, modulus uint64) error

INTT performs inverse NTT.

func Init

func Init() error

Init initializes the lux-accel library.

func Keccak256

func Keccak256(session *Session, input, output *Tensor) error

Keccak256 computes Keccak-256.

func KyberDecaps

func KyberDecaps(session *Session, ct, sk, ss *Tensor) error

KyberDecaps decapsulates shared secret.

func KyberEncaps

func KyberEncaps(session *Session, pk, ct, ss *Tensor) error

KyberEncaps encapsulates shared secret.

func KyberKeyGen

func KyberKeyGen(session *Session, pk, sk *Tensor) error

KyberKeyGen generates Kyber key pair.

func LatticeNTTMLDSABatch added in v1.2.0

func LatticeNTTMLDSABatch(session *Session, polys *Tensor, inverse bool) error

LatticeNTTMLDSABatch performs the in-place forward (inverse=false) or inverse (inverse=true) Number-Theoretic Transform over Z_q[X]/(X^256 + 1) with q = 8380417 (the ML-DSA prime), batched across n polynomials.

The polys tensor MUST be LUX_DTYPE_I32 with shape [n, 256]; the transform is in-place. Byte-equal to PQCLEAN_MLDSA65_CLEAN_ntt for the forward direction; the inverse direction (when implemented by the backend) is the matching PQCLEAN_MLDSA65_CLEAN_invntt_tomont.

When libluxaccel has not linked an implementation, the weak stub returns LUX_NO_BACKEND which surfaces as ErrNoBackends — callers then route to their per-poly CPU NTT (Pulsar does this via the luxfi/lattice/v7 dispatcher).

func LayerNorm

func LayerNorm(session *Session, input, gamma, beta, output *Tensor, eps float32) error

LayerNorm applies layer normalization.

func LoadBackend

func LoadBackend(path string) error

LoadBackend loads a backend plugin from path.

func MLDSASignBatch added in v1.1.2

func MLDSASignBatch(session *Session, mode int, msgs, sks, sigs *Tensor) error

MLDSASignBatch batch-signs ML-DSA / Dilithium (FIPS 204) messages. mode as for MLDSAVerifyBatch. See doc on MLDSAVerifyBatch for ABI status.

func MLDSAVerifyBatch added in v1.1.2

func MLDSAVerifyBatch(session *Session, mode int, msgs, sigs, pks, results *Tensor) error

MLDSAVerifyBatch batch-verifies ML-DSA / Dilithium (FIPS 204) signatures. mode encodes the parameter set: 2=ML-DSA-44, 3=ML-DSA-65, 5=ML-DSA-87. The results tensor is populated with one uint8 per signature (1 = valid, 0 = invalid).

The C ABI symbol `lux_mldsa_verify_batch` is declared in c_api.h and resolved at link time. When libluxaccel ships an implementation it runs FIPS 204 batched verify on the active backend; when no native library is linked the weak-symbol stub in stub.go returns LUX_NO_BACKEND, which surfaces here as ErrNoBackends. Either way, callers see the Go-level error and can fall through to the per- element CPU verify path — the substrate boundary is the wire, not a stub.

func MSM

func MSM(session *Session, scalars, bases, result *Tensor) error

MSM performs multi-scalar multiplication.

func MatMul

func MatMul(session *Session, a, b, c *Tensor) error

MatMul performs matrix multiplication.

func MatchOrders

func MatchOrders(session *Session, bids, asks, matches, prices, amounts *Tensor) error

MatchOrders matches orders.

func MerkleRoot

func MerkleRoot(session *Session, leaves, root *Tensor) error

MerkleRoot computes Merkle root.

func NTT

func NTT(session *Session, input, output, roots *Tensor, modulus uint64) error

NTT performs Number Theoretic Transform.

func PolyMul

func PolyMul(session *Session, a, b, c *Tensor, modulus uint64) error

PolyMul multiplies polynomials.

func Poseidon

func Poseidon(session *Session, input, output *Tensor) error

Poseidon computes Poseidon hash.

func ReLU

func ReLU(session *Session, input, output *Tensor) error

ReLU applies ReLU activation.

func SHA256

func SHA256(session *Session, input, output *Tensor) error

SHA256 computes SHA-256.

func SLHDSASignBatch added in v1.1.0

func SLHDSASignBatch(session *Session, mode int, msgs, sks, sigs *Tensor) error

SLHDSASignBatch batch-signs SLH-DSA (FIPS 205 / Magnetar) messages. mode encodes the parameter set per c_api.h: 2=SHA2-128f, 3=SHA2-192f, 5=SHA2-256f, 12=SHAKE-128f, 13=SHAKE-192f, 15=SHAKE-256f.

func SLHDSAVerifyBatch added in v1.1.0

func SLHDSAVerifyBatch(session *Session, mode int, msgs, sigs, pks, results *Tensor) error

SLHDSAVerifyBatch batch-verifies SLH-DSA (FIPS 205 / Magnetar) signatures. mode as for SLHDSASignBatch. The results tensor is populated with one uint8 per signature (1 = valid, 0 = invalid).

func Shutdown

func Shutdown()

Shutdown releases library resources.

func Softmax

func Softmax(session *Session, input, output *Tensor, axis int) error

Softmax applies softmax.

func Version

func Version() string

Version returns the library version.

Types

type DeviceInfo

type DeviceInfo struct {
	Name             string
	Vendor           string
	Backend          int
	IsDiscrete       bool
	IsUnifiedMemory  bool
	TotalMemory      uint64
	MaxWorkgroupSize uint32
	SIMDWidth        uint32
}

DeviceInfo contains device information.

func GetDeviceInfo

func GetDeviceInfo(backend, index int) (*DeviceInfo, error)

GetDeviceInfo retrieves device information.

type Session

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

Session wraps a C session handle.

func CreateSession

func CreateSession() (*Session, error)

CreateSession creates a new session.

func CreateSessionWithBackend

func CreateSessionWithBackend(backend int) (*Session, error)

CreateSessionWithBackend creates a session with specific backend.

func CreateSessionWithDevice

func CreateSessionWithDevice(backend, deviceIndex int) (*Session, error)

CreateSessionWithDevice creates a session with specific device.

func (*Session) Destroy

func (s *Session) Destroy()

Destroy releases session resources.

func (*Session) Handle

func (s *Session) Handle() C.lux_session

Handle returns the raw C handle.

func (*Session) Sync

func (s *Session) Sync() error

Sync synchronizes all pending operations.

type Tensor

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

Tensor wraps a C tensor handle.

func CreateTensor

func CreateTensor(session *Session, dtype int, shape []int) (*Tensor, error)

CreateTensor creates a new tensor.

func CreateTensorWithData

func CreateTensorWithData(session *Session, dtype int, shape []int, data []byte) (*Tensor, error)

CreateTensorWithData creates a tensor with initial data.

func (*Tensor) Bytes

func (t *Tensor) Bytes() int

Bytes returns the total byte size.

func (*Tensor) DType

func (t *Tensor) DType() int

DType returns the data type.

func (*Tensor) Destroy

func (t *Tensor) Destroy()

Destroy releases tensor resources.

func (*Tensor) FromHost

func (t *Tensor) FromHost(src []byte) error

FromHost copies data from host memory.

func (*Tensor) Handle

func (t *Tensor) Handle() C.lux_tensor

Handle returns the raw C handle.

func (*Tensor) HandlePtr

func (t *Tensor) HandlePtr() uintptr

HandlePtr returns the handle as uintptr.

func (*Tensor) NDim

func (t *Tensor) NDim() int

NDim returns the number of dimensions.

func (*Tensor) NumEl

func (t *Tensor) NumEl() int

NumEl returns the total number of elements.

func (*Tensor) Shape

func (t *Tensor) Shape(dim int) int

Shape returns the size of a dimension.

func (*Tensor) ToHost

func (t *Tensor) ToHost(dst []byte) error

ToHost copies data to host memory.

Jump to

Keyboard shortcuts

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