cudensitymat

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package cudensitymat provides Go bindings for NVIDIA cuDensityMat, the cuQuantum library for many-body quantum operator action and expectation values on dense quantum states.

This package loads and probes libcudensitymat independently. It shares no loader, handle, or symbol table with any other cuQuantum package.

The bound surface is one path: build a Handle, define a State and attach its component storage, build an Operator out of ElementaryOperator products grouped into an OperatorTerm, size a WorkspaceDescriptor with PrepareAction, then accumulate the action with ComputeAction. Expectation computes the unnormalized expectation value of the same operator. Matrix-product states, batched entry points, matrix and MPO operators, gradients, time propagation, eigen-decomposition and the distributed interface table are not bound.

ResetDistributedConfiguration imports a native communicator value. commPtr must point to the selected provider implementation's communicator representation; commSize is its byte size. The library copies that value, not the communicator's underlying resources. Keep the communicator valid while the context uses it. The NCCL provider is experimental in the pinned header. Distributed numerical execution requires separate runtime qualification.

Ownership

Every pointer this package passes to the library is a plain address. None of it may be Go memory whose lifetime Go controls, and none of it is copied by the library unless the header says so.

Component storage attached with State.AttachComponentStorage is caller-owned GPU memory. The library reads and writes it for the whole life of the state and does not free it. Its initial contents are the state's initial value. Free it only after State.Destroy.

Workspace memory attached with WorkspaceDescriptor.SetMemory is caller-owned. It must stay valid and, for the scratch kind, at least as large as WorkspaceDescriptor.GetMemorySize reported after the matching Prepare call, until every operation that names the descriptor has completed on its stream.

Elementary tensor operator storage passed to NewElementaryOperator or ElementaryOperator.AttachBuffer is caller-owned GPU memory that must outlive the operator. The header warns that two elementary operators must not share or overlap storage.

Mode extents, mode lists and duality arrays are borrowed for the duration of the call only. The scaling factors, norm, trace, inner product, expectation value and parameter arrays are GPU-accessible addresses the library reads or writes on the supplied stream, so they must stay valid until that stream is synchronized, not merely until the call returns.

Handles form a lifetime tree that this package does not enforce: an Expectation must not outlive its Operator, an Operator must not outlive the terms appended to it, and none of them may outlive the Handle. Destroy in reverse order of creation.

Streams

Every Compute and Initialize call is asynchronous with respect to the host: it enqueues work on the supplied driver.Stream and returns. A returned nil error means the work was enqueued, not that it finished. Results written to device memory are only readable after the caller synchronizes that stream. Prepare calls take a stream as well and may run device work while measuring the workspace.

Callbacks

cuDensityMat accepts user-supplied scalar and tensor coefficient callbacks. This package deliberately provides no way to build one from a Go function. The wrapped callback structs are bound because they occupy argument slots in the operator-construction calls, and their Callback field is a uintptr, but the zero value -- ScalarCallbackNone and TensorCallbackNone -- is the only value this package supports.

The header fixes the callback signature and says a callback may be a CPU or a GPU function, but it does not say which thread invokes a CPU callback, whether a CUDA context is current on that thread, whether the supplied stream may be used from inside it, or how long the library retains the pointer. Registering a Go function under those unknowns risks calling into the Go runtime from a thread the runtime does not own, so the contract is left unbound rather than guessed.

Verification status

No call in this package has been run against libcudensitymat. It was generated and reviewed on a machine with no NVIDIA GPU, no CUDA driver and no cuQuantum installation.

What has been checked, without hardware: the struct layouts against a clang record dump of the pinned header, the enumerator values against the header text, and the whole bound surface against a CPU-only shared-library fixture that validates every argument it receives -- built for both arm64 and x86_64, so the by-value passing of Complex128 and the wrapped callback structs is exercised under both calling conventions. That establishes argument order, argument width and struct classification. It establishes nothing about what the real library computes.

The tests that would establish that -- a known density matrix, a commutator, and a comparison against a CPU calculation including trace and hermiticity -- are written and have never been run. They skip unless CUDENSITYMAT_PHYSICAL_TEST=1 is set, and a skip is not evidence.

Library context

  • Create: Creates and initializes the library context.
  • Handle.CreateElementaryOperator: Creates an elementary tensor operator acting on a given number of quantum state modes (aka space modes).
  • Handle.CreateExpectation: Creates the operator expectation value computation object.
  • Handle.CreateOperator: Creates an empty operator which is going to be a collection of operator terms with some coefficients.
  • Handle.CreateOperatorTerm: Creates an empty operator term which is going to be a sum of products of either elementary tensor operators or full matrix operators.
  • Handle.CreateState: Defines an empty dense quantum state of a given purity and shape, or a batch of such dense quantum states.
  • Handle.CreateWorkspace: Creates a workspace descriptor.
  • Handle.Close: Destroys the library context.
  • ElementaryOperator.Close: Destroys an elementary tensor operator (simple or batched).
  • Expectation.Close: Destroys an expectation value computation object.
  • Operator.Close: Destroys an operator.
  • OperatorTerm.Close: Destroys an operator term.
  • State.Close: Destroys the quantum state.
  • WorkspaceDescriptor.Close: Destroys a workspace descriptor.
  • Handle.NumRanks: Returns the total number of distributed processes associated with the given library context in its current distributed execution configuration.
  • Handle.ProcRank: Returns the rank of the current process in the distributed execution configuration associated with the given library context.
  • GetVersion: Returns the semantic version number of the cuDensityMat library.
  • Handle.ResetDistributedConfiguration: Resets the current distributed execution configuration associated with the given library context by importing a user-provided inter-process communicator (e.g., MPI_Comm).
  • Handle.ResetRandomSeed: Resets the context-level random seed used by the random number generator inside the library context.

Operator construction

Expectation values

Operator action

  • Operator.ComputeAction: Computes the action of the operator on a given input quantum state, accumulating the result in the output quantum state (accumulative action).
  • Operator.PrepareAction: Prepares the operator for an action on a quantum state.

Quantum state

  • State.AttachComponentStorage: Attaches a user-owned GPU-accessible storage buffer for each component (tensor) constituting the quantum state representation (on the current process in multi-process runs).
  • State.ComputeAccumulation: Computes accumulation of a quantum state(s) into another quantum state(s) of compatible shape.
  • State.ComputeInnerProduct: Computes the inner product(s) between the left quantum state(s) and the right quantum state(s): < state(s)Left | state(s)Right >
  • State.ComputeNorm: Computes the squared Frobenius norm(s) of the quantum state(s).
  • State.ComputeScaling: Multiplies the quantum state(s) by a scalar factor(s).
  • State.ComputeTrace: Computes the trace(s) of the quantum state(s).
  • State.ComponentInfo: Queries information for a locally stored component tensor which represents either the full component or its slice (on the current process in multi-process runs).
  • State.ComponentNumModes: Queries the number of modes in a local component tensor (on the current process in multi-process runs).
  • State.ComponentStorageSize: Queries the storage size (in bytes) for each component (tensor) constituting the quantum state representation (on the current process in multi-process runs).
  • State.NumComponents: Queries the number of components (tensors) constituting the chosen quantum state representation (on the current process in multi-process runs).
  • State.InitializeZero: Initializes the quantum state to zero (null state).

Workspace

Example

Example builds the Liouvillian superoperator -i[H, .] for a single two-level system and applies it to a density matrix held in caller-owned GPU memory. It returns early, printing why, when libcudensitymat or a CUDA device is not available, so it can be compiled and read on a machine that has neither.

The shape it shows is the whole bound surface: a handle, a mixed State whose component storage the caller allocates and keeps, an Operator assembled from ElementaryOperator products, a WorkspaceDescriptor sized by PrepareAction and backed by caller-owned memory, and one ComputeAction that accumulates into a second state.

package main

import (
	"fmt"
	"runtime"
	"unsafe"

	"github.com/tmc/lib/nvidia/cudensitymat"
	"github.com/tmc/lib/nvidia/driver"
)

func main() {
	// Every CUDA call below is bound to the context current on this thread.
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	if err := cudensitymat.Load(""); err != nil {
		fmt.Println("cuDensityMat unavailable:", err)
		return
	}
	if err := driver.Init(0); err != nil {
		fmt.Println("CUDA driver unavailable:", err)
		return
	}
	dev, err := driver.DeviceGet(0)
	if err != nil {
		fmt.Println("no CUDA device:", err)
		return
	}
	ctx, err := dev.PrimaryCtxRetain()
	if err != nil {
		fmt.Println("primary context:", err)
		return
	}
	defer dev.PrimaryCtxRelease()
	if err := ctx.SetCurrent(); err != nil {
		fmt.Println("set context:", err)
		return
	}
	stream, err := driver.NewStream(0)
	if err != nil {
		fmt.Println("stream:", err)
		return
	}
	defer stream.Close()

	handle, err := cudensitymat.Create()
	if err != nil {
		fmt.Println("create handle:", err)
		return
	}
	defer handle.Close()

	// One space mode of extent 2: a qubit. A mixed state over it is a 2x2
	// density matrix stored in the generalized column-major layout.
	extents := []int64{2}
	rho := []complex128{
		0.7, complex(0.1, -0.2), // column j=0: rho[0][0], rho[1][0]
		complex(0.1, 0.2), 0.3, // column j=1: rho[0][1], rho[1][1]
	}

	in, err := handle.CreateState(cudensitymat.StatePurityMixed, 1, &extents[0], 1, cudensitymat.C64F)
	if err != nil {
		fmt.Println("create state:", err)
		return
	}
	defer in.Close()
	out, err := handle.CreateState(cudensitymat.StatePurityMixed, 1, &extents[0], 1, cudensitymat.C64F)
	if err != nil {
		fmt.Println("create state:", err)
		return
	}
	defer out.Close()

	// The library reports the storage it needs; the caller allocates it, owns
	// it for the life of the state, and frees it only after State.Destroy.
	// The buffer's initial contents are the state's initial value.
	var size uint
	if err := in.ComponentStorageSize(handle, 1, &size); err != nil {
		fmt.Println("component storage size:", err)
		return
	}
	inBuf, err := driver.MemAllocBytes(size)
	if err != nil {
		fmt.Println("device alloc:", err)
		return
	}
	defer inBuf.Free()
	outBuf, err := driver.MemAllocBytes(size)
	if err != nil {
		fmt.Println("device alloc:", err)
		return
	}
	defer outBuf.Free()
	if err := inBuf.CopyFromHostPtr(unsafe.Pointer(unsafe.SliceData(rho)), size); err != nil {
		fmt.Println("copy state in:", err)
		return
	}
	inPtr, outPtr := uintptr(inBuf), uintptr(outBuf)
	if err := in.AttachComponentStorage(handle, 1, &inPtr, &size); err != nil {
		fmt.Println("attach storage:", err)
		return
	}
	if err := out.AttachComponentStorage(handle, 1, &outPtr, &size); err != nil {
		fmt.Println("attach storage:", err)
		return
	}
	// ComputeAction accumulates, so the output starts at zero.
	if err := out.InitializeZero(handle, driver.Stream(stream)); err != nil {
		fmt.Println("zero output:", err)
		return
	}

	// H = sigma_y, Hermitian, stored column-major like the state. Its GPU
	// storage is caller-owned too and must outlive the elementary operator.
	sigmaY := []complex128{0, complex(0, 1), complex(0, -1), 0}
	hBuf, err := driver.MemAllocBytes(uint(len(sigmaY)) * 16)
	if err != nil {
		fmt.Println("device alloc:", err)
		return
	}
	defer hBuf.Free()
	if err := hBuf.CopyFromHost(sigmaY); err != nil {
		fmt.Println("copy operator:", err)
		return
	}
	h, err := handle.CreateElementaryOperator(1, &extents[0],
		cudensitymat.OperatorSparsityNone, 0, nil, cudensitymat.C64F, uintptr(hBuf),
		cudensitymat.TensorCallbackNone, cudensitymat.TensorGradientCallbackNone)
	if err != nil {
		fmt.Println("create elementary operator:", err)
		return
	}
	defer h.Close()

	// -i[H, rho] = (-i)(H rho) + (+i)(rho H). Mode action duality 0 applies H
	// to the state's ket mode, a nonzero duality to its bra mode.
	modes := []int32{0}
	left, err := handle.CreateOperatorTerm(1, &extents[0])
	if err != nil {
		fmt.Println("create term:", err)
		return
	}
	defer left.Close()
	ket := []int32{0}
	if err := left.AppendElementaryProduct(handle, 1, &h, &modes[0], &ket[0],
		cudensitymat.Complex128{X: 0, Y: -1},
		cudensitymat.ScalarCallbackNone, cudensitymat.ScalarGradientCallbackNone); err != nil {
		fmt.Println("append product:", err)
		return
	}
	right, err := handle.CreateOperatorTerm(1, &extents[0])
	if err != nil {
		fmt.Println("create term:", err)
		return
	}
	defer right.Close()
	bra := []int32{1}
	if err := right.AppendElementaryProduct(handle, 1, &h, &modes[0], &bra[0],
		cudensitymat.Complex128{X: 0, Y: 1},
		cudensitymat.ScalarCallbackNone, cudensitymat.ScalarGradientCallbackNone); err != nil {
		fmt.Println("append product:", err)
		return
	}

	liouvillian, err := handle.CreateOperator(1, &extents[0])
	if err != nil {
		fmt.Println("create operator:", err)
		return
	}
	defer liouvillian.Close()
	one := cudensitymat.Complex128{X: 1}
	for _, term := range []cudensitymat.OperatorTerm{left, right} {
		if err := liouvillian.AppendTerm(handle, term, 0, one,
			cudensitymat.ScalarCallbackNone, cudensitymat.ScalarGradientCallbackNone); err != nil {
			fmt.Println("append term:", err)
			return
		}
	}

	// PrepareAction reports the scratch it needs; the caller supplies it and
	// keeps it alive until the stream that used it is synchronized.
	ws, err := handle.CreateWorkspace()
	if err != nil {
		fmt.Println("create workspace:", err)
		return
	}
	defer ws.Close()
	if err := liouvillian.PrepareAction(handle, in, out, cudensitymat.Compute64F,
		1<<26, ws, driver.Stream(stream)); err != nil {
		fmt.Println("prepare:", err)
		return
	}
	need, err := handle.WorkspaceGetMemorySize(ws, cudensitymat.MemspaceDevice, cudensitymat.WorkspaceScratch)
	if err != nil {
		fmt.Println("workspace size:", err)
		return
	}
	if need > 0 {
		scratch, err := driver.MemAllocBytes(need)
		if err != nil {
			fmt.Println("workspace alloc:", err)
			return
		}
		defer scratch.Free()
		if err := handle.WorkspaceSetMemory(ws, cudensitymat.MemspaceDevice,
			cudensitymat.WorkspaceScratch, uintptr(scratch), need); err != nil {
			fmt.Println("workspace attach:", err)
			return
		}
	}

	if err := liouvillian.ComputeAction(handle, 0, 1, 0, nil, in, out, ws,
		driver.Stream(stream)); err != nil {
		fmt.Println("compute action:", err)
		return
	}
	// ComputeAction only enqueued work. Nothing in outBuf is readable until
	// the stream has been synchronized.
	if err := stream.Synchronize(); err != nil {
		fmt.Println("synchronize:", err)
		return
	}
	result := make([]complex128, len(rho))
	if err := outBuf.CopyToHostPtr(unsafe.Pointer(unsafe.SliceData(result)), size); err != nil {
		fmt.Println("copy result:", err)
		return
	}
	fmt.Printf("-i[H,rho][0][0] = %.3f\n", result[0])
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var ScalarCallbackNone = WrappedScalarCallback{}

ScalarCallbackNone is the absent scalar coefficient callback. It is the Go spelling of the header's cudensitymatScalarCallbackNone.

View Source
var ScalarGradientCallbackNone = WrappedScalarGradientCallback{}

ScalarGradientCallbackNone is the absent scalar gradient callback. The header defines no constant for it; a zeroed wrapper is what the gradient arguments accept when no callback is supplied.

View Source
var TensorCallbackNone = WrappedTensorCallback{}

TensorCallbackNone is the absent tensor callback. It is the Go spelling of the header's cudensitymatTensorCallbackNone.

View Source
var TensorGradientCallbackNone = WrappedTensorGradientCallback{}

TensorGradientCallbackNone is the absent tensor gradient callback.

Functions

func Close

func Close() error

Close unloads the library and clears all bound function pointers.

The function pointers are package-level state, so Close must not be called concurrently with any other call into this package: doing so is a use-after-free. It is intended for test teardown, not for reclaiming a live library.

func GetVersion

func GetVersion() (uint, error)

GetVersion returns the semantic version number of the cuDensityMat library.

Wraps cudensitymatGetVersion. The error reports an unavailable library or symbol.

func Has

func Has(symbol string) bool

Has reports whether the named C symbol resolved in the loaded library, loading it first if necessary. It returns false if the library failed to load. Use it to gate on capabilities before calling into them.

func HasCreate

func HasCreate() bool

HasCreate reports whether cudensitymatCreate resolved in the loaded library.

func HasCreateElementaryOperator

func HasCreateElementaryOperator() bool

HasCreateElementaryOperator reports whether cudensitymatCreateElementaryOperator resolved in the loaded library.

func HasCreateExpectation

func HasCreateExpectation() bool

HasCreateExpectation reports whether cudensitymatCreateExpectation resolved in the loaded library.

func HasCreateOperator

func HasCreateOperator() bool

HasCreateOperator reports whether cudensitymatCreateOperator resolved in the loaded library.

func HasCreateOperatorTerm

func HasCreateOperatorTerm() bool

HasCreateOperatorTerm reports whether cudensitymatCreateOperatorTerm resolved in the loaded library.

func HasCreateState

func HasCreateState() bool

HasCreateState reports whether cudensitymatCreateState resolved in the loaded library.

func HasCreateWorkspace

func HasCreateWorkspace() bool

HasCreateWorkspace reports whether cudensitymatCreateWorkspace resolved in the loaded library.

func HasDestroy

func HasDestroy() bool

HasDestroy reports whether cudensitymatDestroy resolved in the loaded library.

func HasDestroyElementaryOperator

func HasDestroyElementaryOperator() bool

HasDestroyElementaryOperator reports whether cudensitymatDestroyElementaryOperator resolved in the loaded library.

func HasDestroyExpectation

func HasDestroyExpectation() bool

HasDestroyExpectation reports whether cudensitymatDestroyExpectation resolved in the loaded library.

func HasDestroyOperator

func HasDestroyOperator() bool

HasDestroyOperator reports whether cudensitymatDestroyOperator resolved in the loaded library.

func HasDestroyOperatorTerm

func HasDestroyOperatorTerm() bool

HasDestroyOperatorTerm reports whether cudensitymatDestroyOperatorTerm resolved in the loaded library.

func HasDestroyState

func HasDestroyState() bool

HasDestroyState reports whether cudensitymatDestroyState resolved in the loaded library.

func HasDestroyWorkspace

func HasDestroyWorkspace() bool

HasDestroyWorkspace reports whether cudensitymatDestroyWorkspace resolved in the loaded library.

func HasElementaryOperatorAttachBuffer

func HasElementaryOperatorAttachBuffer() bool

HasElementaryOperatorAttachBuffer reports whether cudensitymatElementaryOperatorAttachBuffer resolved in the loaded library.

func HasExpectationCompute

func HasExpectationCompute() bool

HasExpectationCompute reports whether cudensitymatExpectationCompute resolved in the loaded library.

func HasExpectationPrepare

func HasExpectationPrepare() bool

HasExpectationPrepare reports whether cudensitymatExpectationPrepare resolved in the loaded library.

func HasGetNumRanks

func HasGetNumRanks() bool

HasGetNumRanks reports whether cudensitymatGetNumRanks resolved in the loaded library.

func HasGetProcRank

func HasGetProcRank() bool

HasGetProcRank reports whether cudensitymatGetProcRank resolved in the loaded library.

func HasGetVersion

func HasGetVersion() bool

HasGetVersion reports whether cudensitymatGetVersion resolved in the loaded library.

func HasOperatorAppendTerm

func HasOperatorAppendTerm() bool

HasOperatorAppendTerm reports whether cudensitymatOperatorAppendTerm resolved in the loaded library.

func HasOperatorComputeAction

func HasOperatorComputeAction() bool

HasOperatorComputeAction reports whether cudensitymatOperatorComputeAction resolved in the loaded library.

func HasOperatorPrepareAction

func HasOperatorPrepareAction() bool

HasOperatorPrepareAction reports whether cudensitymatOperatorPrepareAction resolved in the loaded library.

func HasOperatorTermAppendElementaryProduct

func HasOperatorTermAppendElementaryProduct() bool

HasOperatorTermAppendElementaryProduct reports whether cudensitymatOperatorTermAppendElementaryProduct resolved in the loaded library.

func HasResetDistributedConfiguration

func HasResetDistributedConfiguration() bool

HasResetDistributedConfiguration reports whether cudensitymatResetDistributedConfiguration resolved in the loaded library.

func HasResetRandomSeed

func HasResetRandomSeed() bool

HasResetRandomSeed reports whether cudensitymatResetRandomSeed resolved in the loaded library.

func HasStateAttachComponentStorage

func HasStateAttachComponentStorage() bool

HasStateAttachComponentStorage reports whether cudensitymatStateAttachComponentStorage resolved in the loaded library.

func HasStateComputeAccumulation

func HasStateComputeAccumulation() bool

HasStateComputeAccumulation reports whether cudensitymatStateComputeAccumulation resolved in the loaded library.

func HasStateComputeInnerProduct

func HasStateComputeInnerProduct() bool

HasStateComputeInnerProduct reports whether cudensitymatStateComputeInnerProduct resolved in the loaded library.

func HasStateComputeNorm

func HasStateComputeNorm() bool

HasStateComputeNorm reports whether cudensitymatStateComputeNorm resolved in the loaded library.

func HasStateComputeScaling

func HasStateComputeScaling() bool

HasStateComputeScaling reports whether cudensitymatStateComputeScaling resolved in the loaded library.

func HasStateComputeTrace

func HasStateComputeTrace() bool

HasStateComputeTrace reports whether cudensitymatStateComputeTrace resolved in the loaded library.

func HasStateGetComponentInfo

func HasStateGetComponentInfo() bool

HasStateGetComponentInfo reports whether cudensitymatStateGetComponentInfo resolved in the loaded library.

func HasStateGetComponentNumModes

func HasStateGetComponentNumModes() bool

HasStateGetComponentNumModes reports whether cudensitymatStateGetComponentNumModes resolved in the loaded library.

func HasStateGetComponentStorageSize

func HasStateGetComponentStorageSize() bool

HasStateGetComponentStorageSize reports whether cudensitymatStateGetComponentStorageSize resolved in the loaded library.

func HasStateGetNumComponents

func HasStateGetNumComponents() bool

HasStateGetNumComponents reports whether cudensitymatStateGetNumComponents resolved in the loaded library.

func HasStateInitializeZero

func HasStateInitializeZero() bool

HasStateInitializeZero reports whether cudensitymatStateInitializeZero resolved in the loaded library.

func HasWorkspaceGetMemory

func HasWorkspaceGetMemory() bool

HasWorkspaceGetMemory reports whether cudensitymatWorkspaceGetMemory resolved in the loaded library.

func HasWorkspaceGetMemorySize

func HasWorkspaceGetMemorySize() bool

HasWorkspaceGetMemorySize reports whether cudensitymatWorkspaceGetMemorySize resolved in the loaded library.

func HasWorkspaceSetMemory

func HasWorkspaceSetMemory() bool

HasWorkspaceSetMemory reports whether cudensitymatWorkspaceSetMemory resolved in the loaded library.

func Load

func Load(path string) error

Load opens the shared library from path, or from the default search list when path is empty, and binds all symbols. Callers that need to direct loading should call Load before any other function; otherwise the first call loads from the default search list.

Load is idempotent: calling it again with the same path, or with an empty path, returns nil. Calling it with a different path after a successful load returns *LibraryConflictError rather than replacing the library. After a failed load, Load retries.

func Loaded

func Loaded() bool

Loaded reports whether the library is currently loaded. It does not trigger a load.

func Path

func Path() string

Path returns the path or name the loaded library was opened from, or the empty string if no library is loaded.

Types

type BindFailure

type BindFailure struct {
	Symbol string
	Err    error
}

BindFailure names a symbol the loaded library exports but that could not be bound, and why.

func BindFailures

func BindFailures() []BindFailure

BindFailures returns the symbols the loaded library exports that could not be bound, sorted by symbol name, or nil if every exported symbol bound. Calling one of these reports *SymbolError with the same Err.

A load that reports no error can still leave symbols unbound: the library is fine and the signatures are not representable here. Call this after Load to find that out at once rather than one call site at a time. It does not trigger a load, and returns nil if none has happened.

type CallError

type CallError struct {
	Func   string // the C symbol called
	Result Result
}

CallError reports that a library call returned a failure result.

Unwrap returns Result, so errors.Is(err, c) reports whether the call returned the Result constant c, and errors.As(err, &r) with r of type Result recovers the code.

func (*CallError) Error

func (e *CallError) Error() string

Error reports the C symbol called and the result it returned.

func (*CallError) Unwrap

func (e *CallError) Unwrap() error

Unwrap returns the result the call reported.

type CallbackDevice

type CallbackDevice int32

CallbackDevice represents supported target devices for user-defined callbacks.

const (
	CallbackDeviceCpu CallbackDevice = 0 // CPU-side callback function
	CallbackDeviceGpu CallbackDevice = 1 // GPU-side callback function
)

func (CallbackDevice) String

func (e CallbackDevice) String() string

String returns the constant name, or a numeric representation for unknown values.

type Complex128

type Complex128 struct {
	X float64
	Y float64
}

Complex128 is cuDoubleComplex: a real part X and an imaginary part Y.

type ComputeType

type ComputeType int32

ComputeType represents supported compute types.

const (
	Compute32F ComputeType = 1 << 2 // single-precision floating-point compute type
	Compute64F ComputeType = 1 << 4 // double-precision floating-point compute type
)

func (ComputeType) String

func (e ComputeType) String() string

String returns the constant name, or a numeric representation for unknown values.

type DataType

type DataType int32

DataType identifies a CUDA data representation.

const (
	// real as a half
	R16F DataType = 2
	// complex as a pair of half numbers
	C16F DataType = 6
	// real as a nv_bfloat16
	R16BF DataType = 14
	// complex as a pair of nv_bfloat16 numbers
	C16BF DataType = 15
	// real as a float
	R32F DataType = 0
	// complex as a pair of float numbers
	C32F DataType = 4
	// real as a double
	R64F DataType = 1
	// complex as a pair of double numbers
	C64F DataType = 5
	// real as a signed 4-bit int
	R4I DataType = 16
	// complex as a pair of signed 4-bit int numbers
	C4I DataType = 17
	// real as a unsigned 4-bit int
	R4U DataType = 18
	// complex as a pair of unsigned 4-bit int numbers
	C4U DataType = 19
	// real as a signed 8-bit int
	R8I DataType = 3
	// complex as a pair of signed 8-bit int numbers
	C8I DataType = 7
	// real as a unsigned 8-bit int
	R8U DataType = 8
	// complex as a pair of unsigned 8-bit int numbers
	C8U DataType = 9
	// real as a signed 16-bit int
	R16I DataType = 20
	// complex as a pair of signed 16-bit int numbers
	C16I DataType = 21
	// real as a unsigned 16-bit int
	R16U DataType = 22
	// complex as a pair of unsigned 16-bit int numbers
	C16U DataType = 23
	// real as a signed 32-bit int
	R32I DataType = 10
	// complex as a pair of signed 32-bit int numbers
	C32I DataType = 11
	// real as a unsigned 32-bit int
	R32U DataType = 12
	// complex as a pair of unsigned 32-bit int numbers
	C32U DataType = 13
	// real as a signed 64-bit int
	R64I DataType = 24
	// complex as a pair of signed 64-bit int numbers
	C64I DataType = 25
	// real as a unsigned 64-bit int
	R64U DataType = 26
	// complex as a pair of unsigned 64-bit int numbers
	C64U DataType = 27
	// real as a nv_fp8_e4m3
	R8F_E4M3 DataType = 28
	// real as an unsigned nv_fp8_e4m3
	R8F_UE4M3 DataType = R8F_E4M3
	// real as a nv_fp8_e5m2
	R8F_E5M2 DataType = 29
	// real as an exponent-only unsigned nv_fp8_e8m0
	R8F_UE8M0 DataType = 30
	// real as a nv_fp6_e2m3
	R6F_E2M3 DataType = 31
	// real as a nv_fp6_e3m2
	R6F_E3M2 DataType = 32
	// real as a nv_fp4_e2m1
	R4F_E2M1 DataType = 33
	// real as an unsigned nv_fp8_ue5m3
	R8FUe5m3 DataType = 34
)

DataType constants.

type DifferentiationDir

type DifferentiationDir int32

DifferentiationDir represents supported differentiation directions.

const (
	DifferentiationDirBackward DifferentiationDir = 1 // Backward differentiation
)

func (DifferentiationDir) String

func (e DifferentiationDir) String() string

String returns the constant name, or a numeric representation for unknown values.

type DistributedProvider

type DistributedProvider int32

DistributedProvider represents supported providers of the distributed communication service.

const (
	DistributedProviderNone DistributedProvider = 0 // No communication service provider (single-GPU execution)
	DistributedProviderMpi  DistributedProvider = 1 // MPI communication service
	DistributedProviderNccl DistributedProvider = 2 // NCCL communication service (experimental)
)

func (DistributedProvider) String

func (e DistributedProvider) String() string

String returns the constant name, or a numeric representation for unknown values.

type ElementaryOperator

type ElementaryOperator uintptr

ElementaryOperator is an opaque handle for cudensitymatElementaryOperator_t.

func (ElementaryOperator) AttachBuffer

func (e ElementaryOperator) AttachBuffer(handle Handle, buffer uintptr, bufferSize uint) error

AttachBuffer attaches a buffer to the elementary tensor operator (either batched or non-batched).

  • handle: in Library handle
  • buffer: in GPU-accessible pointer to the tensor operator elements storage
  • bufferSize: in Size of the memory buffer in bytes

Wraps cudensitymatElementaryOperatorAttachBuffer.

func (*ElementaryOperator) Close

func (e *ElementaryOperator) Close() error

Close destroys an elementary tensor operator (simple or batched).

If e is zero, Close returns nil. Otherwise Close sets e to zero when the call succeeds and leaves it unchanged when it fails. Only e is zeroed: a copy of it still refers to the released object.

Wraps cudensitymatDestroyElementaryOperator.

type ElementaryOperatorSparsity

type ElementaryOperatorSparsity int32

ElementaryOperatorSparsity represents elementary operator sparsity kind.

const (
	OperatorSparsityNone          ElementaryOperatorSparsity = 0 // No sparsity (dense tensor)
	OperatorSparsityMultidiagonal ElementaryOperatorSparsity = 1 // Multi-diagonal sparsity (one or multiple non-zero diagonals)
)

func (ElementaryOperatorSparsity) String

String returns the constant name, or a numeric representation for unknown values.

type Expectation

type Expectation uintptr

Expectation is an opaque handle for cudensitymatExpectation_t.

func (*Expectation) Close

func (e *Expectation) Close() error

Close destroys an expectation value computation object.

If e is zero, Close returns nil. Otherwise Close sets e to zero when the call succeeds and leaves it unchanged when it fails. Only e is zeroed: a copy of it still refers to the released object.

Wraps cudensitymatDestroyExpectation.

func (Expectation) Compute

func (e Expectation) Compute(handle Handle, time float64, batchSize int64, numParams int32, params *float64, state State, expectationValue uintptr, workspace WorkspaceDescriptor, stream driver.Stream) error

Compute computes the operator expectation value(s) with respect to the given quantum state(s).

The result is generally a vector of dimension equal to the state batch size.

  • handle: in Library handle
  • time: in Specified time
  • batchSize: in Batch size (>=1)
  • numParams: in Number of variable parameters defined by the user
  • params: in GPU-accessible pointer to an F-order 2d-array of user-defined real parameter values: params[numParams, batchSize]
  • state: in Quantum state (or a batch of quantum states)
  • expectationValue: out Pointer to the expectation value(s) vector storage in GPU-accessible RAM of the same data type as used by the state and operator
  • workspace: in Allocated workspace descriptor
  • stream: in CUDA stream

Wraps cudensitymatExpectationCompute.

func (Expectation) Prepare

func (e Expectation) Prepare(handle Handle, state State, computeType ComputeType, workspaceSizeLimit uint, workspace WorkspaceDescriptor, stream driver.Stream) error

Prepare prepares the expectation value object for computation.

In general, before the expectation value can be computed, it needs to be prepared for computation first, which is the purpose of this API function.

Note: The required size of the workspace buffer returned inside the workspace descriptor may sometimes be zero, in which case there is no need to allocate a workspace buffer.

  • handle: in Library handle
  • state: in Representative quantum state (or a batch of quantum states)
  • computeType: in Desired compute type
  • workspaceSizeLimit: in Workspace buffer size limit (bytes)
  • workspace: inout Empty workspace descriptor on entrance. The workspace size required for the computation will be set on exit
  • stream: in CUDA stream

Wraps cudensitymatExpectationPrepare.

type Handle

type Handle uintptr

Handle is an opaque handle for cudensitymatHandle_t.

func Create

func Create() (Handle, error)

Create creates and initializes the library context.

Wraps cudensitymatCreate.

func (*Handle) Close

func (h *Handle) Close() error

Close destroys the library context.

If h is zero, Close returns nil. Otherwise Close sets h to zero when the call succeeds and leaves it unchanged when it fails. Only h is zeroed: a copy of it still refers to the released object.

Wraps cudensitymatDestroy.

func (Handle) CreateElementaryOperator

func (h Handle) CreateElementaryOperator(numSpaceModes int32, spaceModeExtents *int64, sparsity ElementaryOperatorSparsity, numDiagonals int32, diagonalOffsets *int32, dataType DataType, tensorData uintptr, tensorCallback WrappedTensorCallback, tensorGradientCallback WrappedTensorGradientCallback) (ElementaryOperator, error)

CreateElementaryOperator creates an elementary tensor operator acting on a given number of quantum state modes (aka space modes).

An elementary tensor operator is a single tensor operator acting on a specific set of space modes (quantum degrees of freedom). A tensor operator is composed of a set of the ket modes and a set of the corresponding bra modes of matching extents, where both sets have the same number of modes and the ket modes precede the bra modes, both in the same order. For example, T[i0, i1, j0, j1] is a 2-body tensor operator in which modes {i0, i1} form a set of the ket modes while modes {j0, j1} form the corresponding set of the bra modes, where the ket mode i0 corresponds to the bra mode j0, and the ket mode i1 corresponds to the bra mode j1 (the modes are always paired this way). Only one mode in each pair of the corresponding modes is contracted with the quantum state tensor, either from the left or from the right. For example, either the bra mode j0 is contracted with a specific ket mode of the quantum state, representing an operator action from the left, or the ket mode i0 is contracted with a specific bra mode of the quantum state, representing an operator action from the right. Then, the corresponding remaining uncontracted mode replaces the contracted mode of the quantum state.

Storage of tensor elements in memory:

Dense tensor stored using the generalized column-wise layout.

The full non-zero diagonals are stored in a concatenated form, following the order how they appear in the `diagonalOffsets` argument. The length of each stored diagonal is equal to the full matrix dimension, padded with trailing zeros for non-main diagonals.

Note: Currently the multi-diagonal storage format is only supported by 1-body elementary tensor operators (restriction subject to lifting in future).

Warning: Different elementary tensor operators must not use the same or overlapping GPU storage buffers, otherwise it will cause an undefined behavior.

  • numSpaceModes: in Number of the (state) space modes acted on
  • spaceModeExtents: in Extents of the (state) space modes acted on
  • sparsity: in Tensor operator sparsity defining the storage scheme
  • numDiagonals: in For multi-diagonal tensor operator matrices, specifies the total number of non-zero diagonals (>= 1), otherwise ignored
  • diagonalOffsets: in For multi-diagonal tensor operator matrices, these are the offsets of the non-zero diagonals (for example, the main diagonal has offset 0, the diagonal right above the main diagonal has offset +1, the diagonal right below the main diagonal has offset -1, and so on)
  • dataType: in Tensor operator data type
  • tensorData: in GPU-accessible pointer to the tensor operator elements storage
  • tensorCallback: in Optional user-defined tensor callback function which can be called later to fill in the tensor elements in the provided storage, or NULL
  • tensorGradientCallback: in Optional user-defined tensor gradient callback function which can be called later to compute the Vector-Jacobian Product (VJP) for the tensor operator, to produce gradients with respect to the user-defined real parameters, or NULL

Wraps cudensitymatCreateElementaryOperator.

func (Handle) CreateExpectation

func (h Handle) CreateExpectation(superoperator Operator) (Expectation, error)

CreateExpectation creates the operator expectation value computation object.

Note: The unnormalized expectation value will be produced during the computation. If the quantum state is not normalized, one will need to additionally compute the state norm or trace in order to obtain the normalized operator expectation value.

Note: The operator must stay alive during the lifetime of the created expectation object.

  • superoperator: in Operator

Wraps cudensitymatCreateExpectation.

func (Handle) CreateOperator

func (h Handle) CreateOperator(numSpaceModes int32, spaceModeExtents *int64) (Operator, error)

CreateOperator creates an empty operator which is going to be a collection of operator terms with some coefficients.

If the operator is expected to act on a pure quantum state, it is just a regular operator that will act on the pure state vector from one side. If the operator is expected to act on a mixed quantum state, its action can become more complicated where it may act on both sides of the density matrix representing the mixed quantum state. In this case, the operator is specifically called the super-operator. However, one should note that in both cases this is still a mathematical operator, just acting on a different kind of mathematical vector.

Note: The created operator will only be able to act on the quantum states which reside in the same space where the operator is set to act.

  • numSpaceModes: in Number of modes (degrees of freedom) defining the primary/dual tensor product space in which the operator term will act
  • spaceModeExtents: in Extents of the modes (degrees of freedom) defining the primary/dual tensor product space in which the operator term will act

Wraps cudensitymatCreateOperator.

func (Handle) CreateOperatorTerm

func (h Handle) CreateOperatorTerm(numSpaceModes int32, spaceModeExtents *int64) (OperatorTerm, error)

CreateOperatorTerm creates an empty operator term which is going to be a sum of products of either elementary tensor operators or full matrix operators.

Each individual elementary tensor operator within a product acts on a subset of space modes, either from the left or from the right (for each mode). Each full matrix operator within a product acts on all space modes, either from the left or from the right (for all modes).

Note: The created operator term will only be able to act on the quantum states which reside in the same space where the operator term is set to act.

  • numSpaceModes: in Number of modes (quantum degrees of freedom) defining the primary/dual tensor product space in which the operator term will act
  • spaceModeExtents: in Extents of the modes (quantum degrees of freedom) defining the primary/dual tensor product space in which the operator term will act

Wraps cudensitymatCreateOperatorTerm.

func (Handle) CreateState

func (h Handle) CreateState(purity StatePurity, numSpaceModes int32, spaceModeExtents *int64, batchSize int64, dataType DataType) (State, error)

CreateState defines an empty dense quantum state of a given purity and shape, or a batch of such dense quantum states.

The number of space modes defining the state space is always the number of quantum degrees of freedom used to define the corresponding composite tensor-product space. With that, the number of modes in a pure-state tensor equals the number of the space modes (quantum degrees of freedom). The number of modes in a mixed-state tensor equals twice the number of the space modes, consisting of a set of the ket modes and a set of the bra modes, which are identical in terms of their extents between the two sets, with the ket modes preceding the bra modes, for example: S[i0, i1, j0, j1] tensor represents a mixed quantum state with two degrees of freedom, where modes {i0, i1} form the ket set, and modes {j0, j1} form the bra set such that ket mode i0 corresponds to the bra mode j0, and ket mode i1 corresponds to the bra mode j1. In contrast, a pure quantum state with two degrees of freedom is represented by the tensor S[i0, i1] with only the ket modes (no bra modes). Furthermore, batched pure/mixed states introduce one additional (batch) mode to their dense tensor representation, namely: S[i0, i1, b] for the batched pure state, and S[i0, i1, j0, j1, b] for the batched mixed state, where b is the size of the batch (batch size or extent of the batch mode).

  • purity: in Desired quantum state purity
  • numSpaceModes: in Number of space modes (number of quantum degrees of freedom)
  • spaceModeExtents: in Extents of the space modes (dimensions of the quantum degrees of freedom)
  • batchSize: in Batch size (number of equally-shaped quantum states in the batch). Note that setting the batch size to zero is the same as setting it to 1 (no batching)
  • dataType: in Numerical representation data type (type of tensor elements)

Wraps cudensitymatCreateState.

func (Handle) CreateWorkspace

func (h Handle) CreateWorkspace() (WorkspaceDescriptor, error)

CreateWorkspace creates a workspace descriptor.

Wraps cudensitymatCreateWorkspace.

func (Handle) NumRanks

func (h Handle) NumRanks() (int32, error)

NumRanks returns the total number of distributed processes associated with the given library context in its current distributed execution configuration.

Wraps cudensitymatGetNumRanks.

func (Handle) ProcRank

func (h Handle) ProcRank() (int32, error)

ProcRank returns the rank of the current process in the distributed execution configuration associated with the given library context.

Wraps cudensitymatGetProcRank.

func (Handle) ResetDistributedConfiguration

func (h Handle) ResetDistributedConfiguration(provider DistributedProvider, commPtr unsafe.Pointer, commSize uint) error

ResetDistributedConfiguration resets the current distributed execution configuration associated with the given library context by importing a user-provided inter-process communicator (e.g., MPI_Comm).

Accepts and stores a copy of the provided inter-process communicator which will be used for distributing numerical operations across all involved distributed processes.

  • provider: in Communication service provider
  • commPtr: in Pointer to the communicator in a type-erased form
  • commSize: in Size of the communicator in bytes

Wraps cudensitymatResetDistributedConfiguration.

func (Handle) ResetRandomSeed

func (h Handle) ResetRandomSeed(randomSeed int32) error

ResetRandomSeed resets the context-level random seed used by the random number generator inside the library context.

  • randomSeed: in Random seed value

Wraps cudensitymatResetRandomSeed.

func (Handle) WorkspaceGetMemory

func (h Handle) WorkspaceGetMemory(workspaceDescr WorkspaceDescriptor, memSpace Memspace, workspaceKind WorkspaceKind) (uintptr, uint, error)

WorkspaceGetMemory retrieves a workspace buffer.

  • workspaceDescr: in Workspace descriptor
  • memSpace: in Memory space
  • workspaceKind: in Workspace kind

Wraps cudensitymatWorkspaceGetMemory.

func (Handle) WorkspaceGetMemorySize

func (h Handle) WorkspaceGetMemorySize(workspaceDescr WorkspaceDescriptor, memSpace Memspace, workspaceKind WorkspaceKind) (uint, error)

WorkspaceGetMemorySize queries the required workspace buffer size.

  • workspaceDescr: in Workspace descriptor
  • memSpace: in Memory space
  • workspaceKind: in Workspace kind

Wraps cudensitymatWorkspaceGetMemorySize.

func (Handle) WorkspaceSetMemory

func (h Handle) WorkspaceSetMemory(workspaceDescr WorkspaceDescriptor, memSpace Memspace, workspaceKind WorkspaceKind, memoryBuffer uintptr, memoryBufferSize uint) error

WorkspaceSetMemory attaches memory to a workspace buffer.

  • workspaceDescr: inout Workspace descriptor
  • memSpace: in Memory space
  • workspaceKind: in Workspace kind
  • memoryBuffer: in Pointer to a user-owned memory buffer to be used by the specified workspace
  • memoryBufferSize: in Size of the provided memory buffer in bytes

Wraps cudensitymatWorkspaceSetMemory.

type LibraryAttempt

type LibraryAttempt struct {
	Name string // path or soname passed to dlopen
	Err  error
}

LibraryAttempt records one failed attempt to open the shared library.

type LibraryConflictError

type LibraryConflictError struct {
	Loaded    string
	Requested string

	// Implicit reports that the loaded library was opened lazily and no
	// successful Load has since acknowledged it. A
	// caller that sees this called some
	// other function first, and that call took the default search list.
	Implicit bool
}

LibraryConflictError reports a Load call naming a different library than the one already loaded. Only one library is loaded per process.

func (*LibraryConflictError) Error

func (e *LibraryConflictError) Error() string

Error reports the conflicting library paths, and whether the library that is already loaded got there without a Load call.

type LibraryError

type LibraryError struct {
	Library  string
	Env      string
	Path     string
	Attempts []LibraryAttempt
	Hint     string
}

LibraryError reports that libcudensitymat could not be opened. Attempts lists every name tried in order. Path is set when an explicit path, from Load or CUDENSITYMAT_LIB_PATH, was requested and failed. Hint reports pkg-config discovery results and query failures, when discovery ran.

func (*LibraryError) Error

func (e *LibraryError) Error() string

Error describes the library load attempts and their errors.

func (*LibraryError) Unwrap

func (e *LibraryError) Unwrap() []error

Unwrap returns the error from each attempt.

type Memspace

type Memspace int32

Memspace represents memory spaces for workspace buffer allocation.

const (
	MemspaceDevice Memspace = 0 // Device memory space (GPU)
	MemspaceHost   Memspace = 1 // Host memory space (CPU)
)

func (Memspace) String

func (e Memspace) String() string

String returns the constant name, or a numeric representation for unknown values.

type Operator

type Operator uintptr

Operator is an opaque handle for cudensitymatOperator_t.

func (Operator) AppendTerm

func (o Operator) AppendTerm(handle Handle, operatorTerm OperatorTerm, duality int32, coefficient Complex128, coefficientCallback WrappedScalarCallback, coefficientGradientCallback WrappedScalarGradientCallback) error

AppendTerm appends an operator term to the operator.

  • handle: in Library handle
  • operatorTerm: in Operator term
  • duality: in Duality status of the operator term action as a whole. If not zero, the duality status of each mode action inside the operator term will be flipped, that is, action from the left will be replaced by action from the right, and vice versa
  • coefficient: in Constant (static) complex scalar coefficient associated with the operator term
  • coefficientCallback: in Optional user-defined complex scalar callback function which can be called later to update the scalar coefficient associated with the operator term, or NULL. The total coefficient associated with the operator term is a product of the constant coefficient and the result of the scalar callback function, if defined
  • coefficientGradientCallback: in Optional user-defined scalar gradient callback function which can be called later to compute the gradients of the complex scalar coefficient with respect to the user-defined real parameters, or NULL

Wraps cudensitymatOperatorAppendTerm.

func (*Operator) Close

func (o *Operator) Close() error

Close destroys an operator.

If o is zero, Close returns nil. Otherwise Close sets o to zero when the call succeeds and leaves it unchanged when it fails. Only o is zeroed: a copy of it still refers to the released object.

Wraps cudensitymatDestroyOperator.

func (Operator) ComputeAction

func (o Operator) ComputeAction(handle Handle, time float64, batchSize int64, numParams int32, params *float64, stateIn State, stateOut State, workspace WorkspaceDescriptor, stream driver.Stream) error

ComputeAction computes the action of the operator on a given input quantum state, accumulating the result in the output quantum state (accumulative action).

Note: The provided input and output quantum states must be of the same kind, shape, and structure as the quantum states provided during the preceding preparation phase.

Warning: The output quantum state cannot coincide with the input quantum state.

  • handle: in Library handle
  • time: in Time value
  • batchSize: in Batch size (>=1)
  • numParams: in Number of variable parameters defined by the user
  • params: in GPU-accessible pointer to an F-order 2d-array of user-defined real parameter values: params[numParams, batchSize]
  • stateIn: in Input quantum state (or a batch of input quantum states)
  • stateOut: inout Updated resulting quantum state which accumulates operator action on the input quantum state
  • workspace: in Allocated workspace descriptor
  • stream: in CUDA stream

Wraps cudensitymatOperatorComputeAction.

func (Operator) PrepareAction

func (o Operator) PrepareAction(handle Handle, stateIn State, stateOut State, computeType ComputeType, workspaceSizeLimit uint, workspace WorkspaceDescriptor, stream driver.Stream) error

PrepareAction prepares the operator for an action on a quantum state.

In general, before the operator action on a specific quantum state(s) can be computed, it needs to be prepared for computation first, which is the purpose of this API function.

Note: The required size of the workspace buffer returned inside the workspace descriptor may sometimes be zero, in which case there is no need to allocate a workspace buffer.

  • handle: in Library handle
  • stateIn: in Representative input quantum state on which the operator is supposed to act. The actual quantum state acted on during computation may be different, but it has to be of the same shape, kind, and factorization structure (topology, bond dimensions, etc)
  • stateOut: in Representative output quantum state produced by the action of the operator on the input quantum state. The actual quantum state acted on during computation may be different, but it has to be of the same shape, kind, and factorization structure (topology, bond dimensions, etc)
  • computeType: in Desired compute type
  • workspaceSizeLimit: in Workspace buffer size limit (bytes)
  • workspace: inout Empty workspace descriptor on entrance. The workspace size required for the computation will be set on exit
  • stream: in CUDA stream

Wraps cudensitymatOperatorPrepareAction.

type OperatorTerm

type OperatorTerm uintptr

OperatorTerm is an opaque handle for cudensitymatOperatorTerm_t.

func (OperatorTerm) AppendElementaryProduct

func (o OperatorTerm) AppendElementaryProduct(handle Handle, numElemOperators int32, elemOperators *ElementaryOperator, stateModesActedOn *int32, modeActionDuality *int32, coefficient Complex128, coefficientCallback WrappedScalarCallback, coefficientGradientCallback WrappedScalarGradientCallback) error

AppendElementaryProduct appends a product of elementary tensor operators acting on quantum state modes to the operator term.

The elementary tensor operators constituting the provided tensor operator product are applied to the quantum state in-order, each elementary tensor operator acting on a quantum state mode either on the left or on the right, or both.

  • handle: in Library handle
  • numElemOperators: in Number of elementary tensor operators in the tensor operator product
  • elemOperators: in Elementary tensor operators constituting the tensor operator product
  • stateModesActedOn: in State modes acted on by the tensor operator product. This is a concatenated list of the state modes acted on by all constituting elementary tensor operators in the same order how they appear in the elemOperators argument
  • modeActionDuality: in Duality status of each mode action, that is, whether the action applies to a ket mode of the quantum state (value zero) or a bra mode of the quantum state (positive value)
  • coefficient: in Constant (static) complex scalar coefficient associated with the appended tensor operator product
  • coefficientCallback: in Optional user-defined complex scalar callback function which can be called later to update the scalar coefficient associated with the tensor operator product, or NULL. The total coefficient associated with the tensor operator product is a product of the constant coefficient and the result of the scalar callback function, if defined
  • coefficientGradientCallback: in Optional user-defined scalar gradient callback function which can be called later to compute the gradients of the complex scalar coefficient with respect to the user-defined real parameters, or NULL

Wraps cudensitymatOperatorTermAppendElementaryProduct.

func (*OperatorTerm) Close

func (o *OperatorTerm) Close() error

Close destroys an operator term.

If o is zero, Close returns nil. Otherwise Close sets o to zero when the call succeeds and leaves it unchanged when it fails. Only o is zeroed: a copy of it still refers to the released object.

Wraps cudensitymatDestroyOperatorTerm.

type Result

type Result int32

Result represents a cudensitymat API error code (cudensitymatStatus_t).

Example

ExampleResult shows how a failed call reports itself. Every bound function returns the library's cudensitymatStatus_t as an error, and the concrete type is Result, so a caller can compare against a specific code.

package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/cudensitymat"
)

func main() {
	err := error(cudensitymat.ErrInsufficientWorkspace)
	fmt.Println(err)
	fmt.Println(err == error(cudensitymat.ErrInsufficientWorkspace))
}
Output:
cudensitymat: ErrInsufficientWorkspace (19)
true
const (
	Success                    Result = 0
	ErrNotInitialized          Result = 1
	ErrAllocFailed             Result = 3
	ErrInvalidValue            Result = 7
	ErrArchMismatch            Result = 8
	ErrExecutionFailed         Result = 13
	ErrInternalError           Result = 14
	ErrNotSupported            Result = 15
	ErrCallbackError           Result = 16
	ErrCublasError             Result = 17
	ErrCudaError               Result = 18
	ErrInsufficientWorkspace   Result = 19
	ErrInsufficientDriver      Result = 20
	ErrIoError                 Result = 21
	ErrCutensorVersionMismatch Result = 22
	ErrNoDeviceAllocator       Result = 23
	ErrCutensorError           Result = 24
	ErrCusolverError           Result = 25
	ErrDeviceAllocatorError    Result = 26
	ErrDistributedFailure      Result = 27
	ErrInterrupted             Result = 28
	ErrCutensornetError        Result = 29
)

cudensitymat error codes from cudensitymat.h.

func (Result) Code

func (r Result) Code() int32

Code returns the underlying result code for programmatic error handling.

func (Result) Error

func (r Result) Error() string

Error implements the error interface.

func (Result) String

func (r Result) String() string

String returns the Go constant name of the result.

type State

type State uintptr

State is an opaque handle for cudensitymatState_t.

func (State) AttachComponentStorage

func (s State) AttachComponentStorage(handle Handle, numStateComponents int32, componentBuffer *uintptr, componentBufferSize *uint) error

AttachComponentStorage attaches a user-owned GPU-accessible storage buffer for each component (tensor) constituting the quantum state representation (on the current process in multi-process runs).

The provided user-owned GPU-accessible storage buffers will be used for storing components (tensors) constituting the quantum state representation (on the current process in multi-process runs). The initial value of the provided storage buffers will be respected by the library, thus providing a mechanism for specifying any initial value of the quantum state in its chosen representation form. In multi-process runs, API function `[State.ComponentInfo]` can be used for retrieving the information on which slice of the requested component (tensor) is stored on the current process.

Note: The sizes of the provided storage buffers must be equal or larger than the required sizes retrieved via `[State.ComponentStorageSize]`.

  • handle: in Library handle
  • numStateComponents: in Number of components (tensors) in the quantum state representation (on the current process). The number of components can be retrieved by calling the API function `[State.NumComponents]`
  • componentBuffer: in Pointers to user-owned GPU-accessible storage buffers for all components (tensors) constituting the quantum state representation (on the current process)
  • componentBufferSize: in Sizes of the provided storage buffers for all components (tensors) constituting the quantum state representation (on the current process)

Wraps cudensitymatStateAttachComponentStorage.

func (*State) Close

func (s *State) Close() error

Close destroys the quantum state.

If s is zero, Close returns nil. Otherwise Close sets s to zero when the call succeeds and leaves it unchanged when it fails. Only s is zeroed: a copy of it still refers to the released object.

Wraps cudensitymatDestroyState.

func (State) ComponentInfo

func (s State) ComponentInfo(handle Handle, stateComponentLocalId int32, stateComponentGlobalId *int32, stateComponentNumModes *int32, stateComponentModeExtents *int64, stateComponentModeOffsets *int64) error

ComponentInfo queries information for a locally stored component tensor which represents either the full component or its slice (on the current process in multi-process runs).

This API function queries the global component id (across all parallel processes), the number of tensor modes (including the batch mode, if present), the extents of all modes, and the base offsets for all modes which can be different from zero if the locally stored component tensor represents a slice of the full component tensor (a base offset of a sliced mode is the starting index value of that mode inside the full tensor mode).

  • handle: in Library handle
  • stateComponentLocalId: in Component local id (on the current parallel process)
  • stateComponentGlobalId: out Component global id (across all parallel processes)
  • stateComponentNumModes: out Number of modes in the queried component tensor
  • stateComponentModeExtents: out Component tensor mode extents (the size of the array must be sufficient, see `[State.ComponentNumModes]`)
  • stateComponentModeOffsets: out Component tensor mode offsets defining the locally stored slice (the size of the array must be sufficient, see `[State.ComponentNumModes]`)

Wraps cudensitymatStateGetComponentInfo.

func (State) ComponentNumModes

func (s State) ComponentNumModes(handle Handle, stateComponentLocalId int32) (int32, int32, int32, error)

ComponentNumModes queries the number of modes in a local component tensor (on the current process in multi-process runs).

  • handle: in Library handle
  • stateComponentLocalId: in Component local id (on the current parallel process)

Wraps cudensitymatStateGetComponentNumModes.

func (State) ComponentStorageSize

func (s State) ComponentStorageSize(handle Handle, numStateComponents int32, componentBufferSize *uint) error

ComponentStorageSize queries the storage size (in bytes) for each component (tensor) constituting the quantum state representation (on the current process in multi-process runs).

  • handle: in Library handle
  • numStateComponents: in Number of components (tensors) in the quantum state representation (on the current process)
  • componentBufferSize: out Storage size (bytes) for each component (tensor) constituting the quantum state representation (on the current process)

Wraps cudensitymatStateGetComponentStorageSize.

func (State) ComputeAccumulation

func (s State) ComputeAccumulation(handle Handle, stateOut State, scalingFactors uintptr, stream driver.Stream) error

ComputeAccumulation computes accumulation of a quantum state(s) into another quantum state(s) of compatible shape.

  • handle: in Library handle
  • stateOut: inout Accumulating quantum state (or a batch of quantum states)
  • scalingFactors: in Array of scaling factor(s) of dimension equal to the batch size in the GPU-accessible RAM (same data type as used by the quantum state)
  • stream: in CUDA stream

Wraps cudensitymatStateComputeAccumulation.

func (State) ComputeInnerProduct

func (s State) ComputeInnerProduct(handle Handle, stateRight State, innerProduct uintptr, stream driver.Stream) error

ComputeInnerProduct computes the inner product(s) between the left quantum state(s) and the right quantum state(s): < state(s)Left | state(s)Right >

For pure quantum states, this function computes the regular Hilbert-space inner product. For mixed quantum states, it computes the matrix inner product induced by the Frobenius matrix norm: The sum of regular Hilbert-space inner products for all columns of two density matrices.

The result is generally a vector of dimension equal to the batch size of both quantum states, which must be the same. The participating quantum states must have compatible shapes.

  • handle: in Library handle
  • stateRight: in Right quantum state (or a batch of quantum states)
  • innerProduct: out Pointer to the inner product(s) vector storage in the GPU-accessible RAM (same data type as the one used by the quantum states)
  • stream: in CUDA stream

Wraps cudensitymatStateComputeInnerProduct.

func (State) ComputeNorm

func (s State) ComputeNorm(handle Handle, norm uintptr, stream driver.Stream) error

ComputeNorm computes the squared Frobenius norm(s) of the quantum state(s).

The result is generally a vector of dimension equal to the quantum state batch size.

Note: For quantum states represented by complex data types, the actual data type of the returned norm is float for cuFloatComplex and double for cuDoubleComplex, respectively.

Note: For quantum states represented by FP32 complex numbers the norm type is float; For quantum states represented by FP64 complex numbers the norm type is double.

  • handle: in Library handle
  • norm: out Pointer to the squared Frobenius norm(s) vector storage in the GPU-accessible RAM (float or double real data type)
  • stream: in CUDA stream

Wraps cudensitymatStateComputeNorm.

func (State) ComputeScaling

func (s State) ComputeScaling(handle Handle, scalingFactors uintptr, stream driver.Stream) error

ComputeScaling multiplies the quantum state(s) by a scalar factor(s).

  • handle: in Library handle
  • scalingFactors: in Array of scaling factor(s) of dimension equal to the batch size in the GPU-accessible RAM (same data type as used by the quantum state)
  • stream: in CUDA stream

Wraps cudensitymatStateComputeScaling.

func (State) ComputeTrace

func (s State) ComputeTrace(handle Handle, trace uintptr, stream driver.Stream) error

ComputeTrace computes the trace(s) of the quantum state(s).

Trace of a pure quantum state is defined to be its squared norm. Trace of a mixed quantum state is equal to the trace of its density matrix. The result is generally a vector of dimension equal to the quantum state batch size.

  • handle: in Library handle
  • trace: out Pointer to the trace(s) vector storage in the GPU-accessible RAM (same data type as used by the quantum state)
  • stream: in CUDA stream

Wraps cudensitymatStateComputeTrace.

func (State) InitializeZero

func (s State) InitializeZero(handle Handle, stream driver.Stream) error

InitializeZero initializes the quantum state to zero (null state).

Note: This API function is typically used for initializing the output quantum state to true zero before accumulating in it the action of an operator on some input quantum state.

  • handle: in Library handle
  • stream: in CUDA stream

Wraps cudensitymatStateInitializeZero.

func (State) NumComponents

func (s State) NumComponents(handle Handle) (int32, error)

NumComponents queries the number of components (tensors) constituting the chosen quantum state representation (on the current process in multi-process runs).

Quantum state representation may include one or more components (tensors) distributed over one or more parallel processes (in distributed multi-GPU runs). The plain state vector or density matrix representations consist of only one component, the full state tensor, which can be sliced and distributed over all parallel processes (in distributed multi-GPU runs). Factorized quantum state representations include more than one component, and these components (tensors) are generally distributed over all parallel processes (in distributed multi-GPU runs).

Note: In multi-process runs, this function returns the number of locally stored components which, in general, can be smaller than the total number of components stored across all parallel processes. One can use API function `[State.ComponentInfo]` to obtain more information on a given local component by providing its local id.

Note: Batching does not add new components to the quantum state representation, it just makes all existing components batched. The corresponding tensors acquire one additional (most significant) mode which represents the batch dimension. Note, however, that the batch dimension of a locally stored component may have a smaller extent than the total batch size due to potential slicing.

  • handle: in Library handle

Wraps cudensitymatStateGetNumComponents.

type StatePurity

type StatePurity int32

StatePurity represents quantum state purity (pure or mixed state).

const (
	StatePurityPure  StatePurity = 0 // Pure quantum state (aka state-vector)
	StatePurityMixed StatePurity = 1 // Mixed quantum state (aka density matrix)
)

func (StatePurity) String

func (e StatePurity) String() string

String returns the constant name, or a numeric representation for unknown values.

type SymbolError

type SymbolError struct {
	Symbol string
	Err    error
}

SymbolError reports that a symbol is not callable.

Err distinguishes the two ways that happens. A nil Err means the loaded library does not export the symbol, which is what an installation older than the symbol looks like. A non-nil Err means the library does export it and the binding itself failed; the library is not at fault.

func (*SymbolError) Error

func (e *SymbolError) Error() string

Error reports the uncallable library symbol and, when the symbol was present but could not be bound, why.

func (*SymbolError) Unwrap

func (e *SymbolError) Unwrap() error

Unwrap returns the reason the symbol could not be bound, or nil when the loaded library does not export it.

type WorkspaceDescriptor

type WorkspaceDescriptor uintptr

WorkspaceDescriptor is an opaque handle for cudensitymatWorkspaceDescriptor_t.

func (*WorkspaceDescriptor) Close

func (w *WorkspaceDescriptor) Close() error

Close destroys a workspace descriptor.

If w is zero, Close returns nil. Otherwise Close sets w to zero when the call succeeds and leaves it unchanged when it fails. Only w is zeroed: a copy of it still refers to the released object.

Wraps cudensitymatDestroyWorkspace.

type WorkspaceKind

type WorkspaceKind int32

WorkspaceKind represents kinds of workspace memory buffers.

const (
	WorkspaceScratch WorkspaceKind = 0 // Scratch workspace memory
)

func (WorkspaceKind) String

func (e WorkspaceKind) String() string

String returns the constant name, or a numeric representation for unknown values.

type WrappedScalarCallback

type WrappedScalarCallback struct {
	Callback uintptr
	Device   CallbackDevice
	Wrapper  uintptr
}

WrappedScalarCallback represents scalar callback wrapper data structure.

A wrapped struct containing the scalar callback and the scalar callback wrapper. The callback wrapper is only used when the library is used from Python and stores a Python callback function. It should be set to `NULL` when the library is used from C and stores a C callback function.

type WrappedScalarGradientCallback

type WrappedScalarGradientCallback struct {
	Callback  uintptr
	Device    CallbackDevice
	Wrapper   uintptr
	Direction DifferentiationDir
}

WrappedScalarGradientCallback represents scalar gradient callback wrapper data structure.

A wrapped struct containing the scalar gradient callback and the scalar gradient callback wrapper. The callback `wrapper` is only used when the library is used from Python and stores a Python callback function. It should be set to `NULL` when the library is used from C and stores a C callback function.

type WrappedTensorCallback

type WrappedTensorCallback struct {
	Callback uintptr
	Device   CallbackDevice
	Wrapper  uintptr
}

WrappedTensorCallback represents tensor callback wrapper data structure.

A wrapped struct containing the tensor callback and the tensor callback wrapper. The callback wrapper is only used when the library is used from Python and stores a Python callback function. It should be set to `NULL` when the library is used from C and stores a C callback function.

type WrappedTensorGradientCallback

type WrappedTensorGradientCallback struct {
	Callback  uintptr
	Device    CallbackDevice
	Wrapper   uintptr
	Direction DifferentiationDir
}

WrappedTensorGradientCallback represents tensor gradient callback wrapper data structure.

A wrapped struct containing the tensor gradient callback and the tensor gradient callback wrapper. The callback `wrapper` is only used when the library is used from Python and stores a Python callback function. It should be set to `NULL` when the library is used from C and stores a C callback function.

Jump to

Keyboard shortcuts

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