cutensor

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: 16 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 cutensor provides lazy-loaded bindings for NVIDIA cuTENSOR.

cuTENSOR creates tensor descriptors and plans for contractions, reductions, permutations, and elementwise operations.

Create a Handle, configure descriptors and a plan, then execute the selected operation.

Tensor Contractions

Descriptor and Plan Lifecycle

Elementwise Operations

Workspace Planning

Library Queries

  • GetCudartVersion: Returns version number of the CUDA runtime that cuTENSOR was compiled against.
  • GetVersion: Returns Version number of the CUTENSOR library.

Handle and Cache Management

Logging

Descriptor Attributes

Tensor Permutations

Tensor Reductions

Example

Example creates a cuTENSOR handle and describes a rank-2 tensor. It returns early when the cuTENSOR library is not available. It has no Output comment, so it is compiled but not run: what it prints depends on the host's cuTENSOR.

package main

import (
	"fmt"

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

func main() {
	h, err := cutensor.Create()
	if err != nil {
		fmt.Println("cuTENSOR unavailable:", err)
		return
	}
	defer h.Close()
	version, err := cutensor.GetVersion()
	if err != nil {
		fmt.Println("version:", err)
		return
	}
	cudart, err := cutensor.GetCudartVersion()
	if err != nil {
		fmt.Println("CUDA runtime version:", err)
		return
	}
	fmt.Println("cuTENSOR version:", version)
	fmt.Println("CUDA runtime version:", cudart)

	// A 64x32 float32 tensor with dense (nil) strides, 128-byte aligned.
	extent := []int64{64, 32}
	desc, err := h.CreateTensorDescriptor(extent, nil, cutensor.R32F, 128)
	if err != nil {
		fmt.Println("tensor descriptor:", err)
		return
	}
	defer desc.Close()
	fmt.Println("tensor descriptor ready")
}

Index

Examples

Constants

View Source
const (
	// Major is CUTENSOR_MAJOR. cuTensor major version.
	//
	// This is the version of the headers the bindings were generated from, not of the library loaded at run time. [GetVersion] reports that.
	Major = 2
	// Minor is CUTENSOR_MINOR. cuTensor minor version.
	//
	// This is the version of the headers the bindings were generated from, not of the library loaded at run time. [GetVersion] reports that.
	Minor = 7
	// Patch is CUTENSOR_PATCH. cuTensor patch version.
	//
	// This is the version of the headers the bindings were generated from, not of the library loaded at run time. [GetVersion] reports that.
	Patch = 0
	// Version is CUTENSOR_VERSION. This is the version of the headers the bindings were generated from, not of the library loaded at run time. [GetVersion] reports that.
	Version = 20700
)

Variables

This section is empty.

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 GetCudartVersion

func GetCudartVersion() (uint, error)

GetCudartVersion returns version number of the CUDA runtime that cuTENSOR was compiled against.

Can be compared against the CUDA runtime version from cudaRuntimeGetVersion().

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

func GetVersion

func GetVersion() (uint, error)

GetVersion returns Version number of the CUTENSOR library.

Wraps cutensorGetVersion. 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 HasComputeDesc3XTF32

func HasComputeDesc3XTF32() bool

HasComputeDesc3XTF32 reports whether CUTENSOR_COMPUTE_DESC_3XTF32 resolved in the loaded library.

func HasComputeDesc4X16F

func HasComputeDesc4X16F() bool

HasComputeDesc4X16F reports whether CUTENSOR_COMPUTE_DESC_4X16F resolved in the loaded library.

func HasComputeDesc8XInt8

func HasComputeDesc8XInt8() bool

HasComputeDesc8XInt8 reports whether CUTENSOR_COMPUTE_DESC_8XINT8 resolved in the loaded library.

func HasComputeDesc9X16BF

func HasComputeDesc9X16BF() bool

HasComputeDesc9X16BF reports whether CUTENSOR_COMPUTE_DESC_9X16BF resolved in the loaded library.

func HasComputeDesc16BF

func HasComputeDesc16BF() bool

HasComputeDesc16BF reports whether CUTENSOR_COMPUTE_DESC_16BF resolved in the loaded library.

func HasComputeDesc16F

func HasComputeDesc16F() bool

HasComputeDesc16F reports whether CUTENSOR_COMPUTE_DESC_16F resolved in the loaded library.

func HasComputeDesc32F

func HasComputeDesc32F() bool

HasComputeDesc32F reports whether CUTENSOR_COMPUTE_DESC_32F resolved in the loaded library.

func HasComputeDesc64F

func HasComputeDesc64F() bool

HasComputeDesc64F reports whether CUTENSOR_COMPUTE_DESC_64F resolved in the loaded library.

func HasComputeDescTF32

func HasComputeDescTF32() bool

HasComputeDescTF32 reports whether CUTENSOR_COMPUTE_DESC_TF32 resolved in the loaded library.

func HasContract

func HasContract() bool

HasContract reports whether cutensorContract resolved in the loaded library.

func HasContractTrinary

func HasContractTrinary() bool

HasContractTrinary reports whether cutensorContractTrinary resolved in the loaded library.

func HasCreate

func HasCreate() bool

HasCreate reports whether cutensorCreate resolved in the loaded library.

func HasCreateContraction

func HasCreateContraction() bool

HasCreateContraction reports whether cutensorCreateContraction resolved in the loaded library.

func HasCreateContractionTrinary

func HasCreateContractionTrinary() bool

HasCreateContractionTrinary reports whether cutensorCreateContractionTrinary resolved in the loaded library.

func HasCreateElementwiseBinary

func HasCreateElementwiseBinary() bool

HasCreateElementwiseBinary reports whether cutensorCreateElementwiseBinary resolved in the loaded library.

func HasCreateElementwiseTrinary

func HasCreateElementwiseTrinary() bool

HasCreateElementwiseTrinary reports whether cutensorCreateElementwiseTrinary resolved in the loaded library.

func HasCreatePermutation

func HasCreatePermutation() bool

HasCreatePermutation reports whether cutensorCreatePermutation resolved in the loaded library.

func HasCreatePlan

func HasCreatePlan() bool

HasCreatePlan reports whether cutensorCreatePlan resolved in the loaded library.

func HasCreatePlanPreference

func HasCreatePlanPreference() bool

HasCreatePlanPreference reports whether cutensorCreatePlanPreference resolved in the loaded library.

func HasCreateReduction

func HasCreateReduction() bool

HasCreateReduction reports whether cutensorCreateReduction resolved in the loaded library.

func HasCreateTensorDescriptor

func HasCreateTensorDescriptor() bool

HasCreateTensorDescriptor reports whether cutensorCreateTensorDescriptor resolved in the loaded library.

func HasDestroy

func HasDestroy() bool

HasDestroy reports whether cutensorDestroy resolved in the loaded library.

func HasDestroyOperationDescriptor

func HasDestroyOperationDescriptor() bool

HasDestroyOperationDescriptor reports whether cutensorDestroyOperationDescriptor resolved in the loaded library.

func HasDestroyPlan

func HasDestroyPlan() bool

HasDestroyPlan reports whether cutensorDestroyPlan resolved in the loaded library.

func HasDestroyPlanPreference

func HasDestroyPlanPreference() bool

HasDestroyPlanPreference reports whether cutensorDestroyPlanPreference resolved in the loaded library.

func HasDestroyTensorDescriptor

func HasDestroyTensorDescriptor() bool

HasDestroyTensorDescriptor reports whether cutensorDestroyTensorDescriptor resolved in the loaded library.

func HasElementwiseBinaryExecute

func HasElementwiseBinaryExecute() bool

HasElementwiseBinaryExecute reports whether cutensorElementwiseBinaryExecute resolved in the loaded library.

func HasElementwiseTrinaryExecute

func HasElementwiseTrinaryExecute() bool

HasElementwiseTrinaryExecute reports whether cutensorElementwiseTrinaryExecute resolved in the loaded library.

func HasEstimateWorkspaceSize

func HasEstimateWorkspaceSize() bool

HasEstimateWorkspaceSize reports whether cutensorEstimateWorkspaceSize resolved in the loaded library.

func HasGetCudartVersion

func HasGetCudartVersion() bool

HasGetCudartVersion reports whether cutensorGetCudartVersion resolved in the loaded library.

func HasGetErrorString

func HasGetErrorString() bool

HasGetErrorString reports whether cutensorGetErrorString resolved in the loaded library.

func HasGetVersion

func HasGetVersion() bool

HasGetVersion reports whether cutensorGetVersion resolved in the loaded library.

func HasHandleReadPlanCacheFromFile

func HasHandleReadPlanCacheFromFile() bool

HasHandleReadPlanCacheFromFile reports whether cutensorHandleReadPlanCacheFromFile resolved in the loaded library.

func HasHandleResizePlanCache

func HasHandleResizePlanCache() bool

HasHandleResizePlanCache reports whether cutensorHandleResizePlanCache resolved in the loaded library.

func HasHandleWritePlanCacheToFile

func HasHandleWritePlanCacheToFile() bool

HasHandleWritePlanCacheToFile reports whether cutensorHandleWritePlanCacheToFile resolved in the loaded library.

func HasLoggerForceDisable

func HasLoggerForceDisable() bool

HasLoggerForceDisable reports whether cutensorLoggerForceDisable resolved in the loaded library.

func HasLoggerOpenFile

func HasLoggerOpenFile() bool

HasLoggerOpenFile reports whether cutensorLoggerOpenFile resolved in the loaded library.

func HasLoggerSetCallback

func HasLoggerSetCallback() bool

HasLoggerSetCallback reports whether cutensorLoggerSetCallback resolved in the loaded library.

func HasLoggerSetFile

func HasLoggerSetFile() bool

HasLoggerSetFile reports whether cutensorLoggerSetFile resolved in the loaded library.

func HasLoggerSetLevel

func HasLoggerSetLevel() bool

HasLoggerSetLevel reports whether cutensorLoggerSetLevel resolved in the loaded library.

func HasLoggerSetMask

func HasLoggerSetMask() bool

HasLoggerSetMask reports whether cutensorLoggerSetMask resolved in the loaded library.

func HasOperationDescriptorGetAttribute

func HasOperationDescriptorGetAttribute() bool

HasOperationDescriptorGetAttribute reports whether cutensorOperationDescriptorGetAttribute resolved in the loaded library.

func HasOperationDescriptorSetAttribute

func HasOperationDescriptorSetAttribute() bool

HasOperationDescriptorSetAttribute reports whether cutensorOperationDescriptorSetAttribute resolved in the loaded library.

func HasPermute

func HasPermute() bool

HasPermute reports whether cutensorPermute resolved in the loaded library.

func HasPlanGetAttribute

func HasPlanGetAttribute() bool

HasPlanGetAttribute reports whether cutensorPlanGetAttribute resolved in the loaded library.

func HasPlanPreferenceGetAttribute

func HasPlanPreferenceGetAttribute() bool

HasPlanPreferenceGetAttribute reports whether cutensorPlanPreferenceGetAttribute resolved in the loaded library.

func HasPlanPreferenceSetAttribute

func HasPlanPreferenceSetAttribute() bool

HasPlanPreferenceSetAttribute reports whether cutensorPlanPreferenceSetAttribute resolved in the loaded library.

func HasReadKernelCacheFromFile

func HasReadKernelCacheFromFile() bool

HasReadKernelCacheFromFile reports whether cutensorReadKernelCacheFromFile resolved in the loaded library.

func HasReduce

func HasReduce() bool

HasReduce reports whether cutensorReduce resolved in the loaded library.

func HasWriteKernelCacheToFile

func HasWriteKernelCacheToFile() bool

HasWriteKernelCacheToFile reports whether cutensorWriteKernelCacheToFile 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 LoggerForceDisable

func LoggerForceDisable() error

LoggerForceDisable disables logging for the entire run.

previouscuTENSOR Data Types nextAPI Reference - cuTENSORMg

Wraps cutensorLoggerForceDisable.

func LoggerOpenFile

func LoggerOpenFile(logFile *byte) error

LoggerOpenFile opens a logging output file in the given path.

  • logFile: Path to the logging output file

Wraps cutensorLoggerOpenFile.

func LoggerSetCallback

func LoggerSetCallback(callback uintptr) error

LoggerSetCallback sets the logging callback routine.

  • callback: Pointer to a callback function. Check cutensorLoggerCallback_t

Wraps cutensorLoggerSetCallback.

func LoggerSetFile

func LoggerSetFile(file uintptr) error

LoggerSetFile sets the logging output file.

  • file: An open file with write permission

Wraps cutensorLoggerSetFile.

func LoggerSetLevel

func LoggerSetLevel(level int32) error

LoggerSetLevel sets the value of the logging level.

  • level: Log level, should be one of the following: 0. Off 1. Errors 2. Performance Trace 3. Performance Hints 4. Heuristics Trace 5. API Trace

Wraps cutensorLoggerSetLevel.

func LoggerSetMask

func LoggerSetMask(mask int32) error

LoggerSetMask sets the value of the log mask.

  • mask: Log mask, the bitwise OR of the following: 0. Off 1. Errors 2. Performance Trace 4. Performance Hints 8. Heuristics Trace 16. API Trace

Wraps cutensorLoggerSetMask.

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 AlgoT

type AlgoT int32

AlgoT represents allows users to specify the algorithm to be used for performing the desired tensor operation.

const (
	AlgoDefaultPatient AlgoT = -6 // More time-consuming than CUTENSOR_DEFAULT, but typically provides a more accurate kernel selection
	AlgoGett           AlgoT = -4 // Choose the GETT algorithm (only applicable to contractions)
	AlgoTgett          AlgoT = -3 // Transpose (A or B) + GETT (only applicable to contractions)
	AlgoTtgt           AlgoT = -2 // Transpose-Transpose-GEMM-Transpose (requires additional memory) (only applicable to contractions)
	AlgoDefault        AlgoT = -1 // A performance model chooses the appropriate algorithm and kernel
)

func (AlgoT) String

func (e AlgoT) String() string

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

type AutotunemodeT

type AutotunemodeT int32

AutotunemodeT determines the mode w.r.t. cuTENSOR's auto-tuning capability.

const (
	AutotuneModeNone        AutotunemodeT = 0 // Indicates no autotuning (default); in this case the cache will help to reduce the plan-creation overhead. In the case of a cachehit: the cached plan will be reused, otherwise the plancache will be neglected.
	AutotuneModeIncremental AutotunemodeT = 1 // Indicates an incremental autotuning (i.e., each invocation of corresponding [Handle.CreatePlan] will create a plan based on a different algorithm/kernel; the maximum number of kernels that will be tested is defined by the [PlanPreferenceIncrementalCount] of [PlanpreferenceattributeT]). WARNING: If this autotuning mode is selected, then we cannot guarantee bit-wise identical results (since different algorithms could be executed).
)

func (AutotunemodeT) String

func (e AutotunemodeT) String() string

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

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 CachemodeT

type CachemodeT int32

CachemodeT defines what is considered a cache hit.

const (
	CacheModeNone     CachemodeT = 0 // Plan will not be cached
	CacheModePedantic CachemodeT = 1 // All parameters of the corresponding descriptor must be identical to the cached plan (default).
)

func (CachemodeT) String

func (e CachemodeT) String() string

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

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 ComputeDescriptor

type ComputeDescriptor uintptr

ComputeDescriptor is an opaque handle for cutensorComputeDescriptor_t.

func ComputeDesc3XTF32

func ComputeDesc3XTF32() (ComputeDescriptor, error)

ComputeDesc3XTF32 returns the three-component tensor-float-32 compute descriptor.

func ComputeDesc4X16F

func ComputeDesc4X16F() (ComputeDescriptor, error)

ComputeDesc4X16F returns the two-component half-precision compute descriptor.

func ComputeDesc8XInt8

func ComputeDesc8XInt8() (ComputeDescriptor, error)

ComputeDesc8XInt8 returns the int8-based compute descriptor.

func ComputeDesc9X16BF

func ComputeDesc9X16BF() (ComputeDescriptor, error)

ComputeDesc9X16BF returns the three-component bfloat16 compute descriptor.

func ComputeDesc16BF

func ComputeDesc16BF() (ComputeDescriptor, error)

ComputeDesc16BF returns the bfloat16 compute descriptor.

func ComputeDesc16F

func ComputeDesc16F() (ComputeDescriptor, error)

ComputeDesc16F returns the half-precision compute descriptor.

func ComputeDesc32F

func ComputeDesc32F() (ComputeDescriptor, error)

ComputeDesc32F returns the single-precision compute descriptor.

func ComputeDesc64F

func ComputeDesc64F() (ComputeDescriptor, error)

ComputeDesc64F returns the double-precision compute descriptor.

func ComputeDescTF32

func ComputeDescTF32() (ComputeDescriptor, error)

ComputeDescTF32 returns the tensor-float-32 compute descriptor.

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 Handle

type Handle uintptr

Handle is an opaque handle for cutensorHandle_t.

func Create

func Create() (Handle, error)

Create initializes the cuTENSOR library and allocates the memory for the library context.

The device associated with a particular cuTENSOR handle is assumed to remain unchanged after the Create call. In order for the cuTENSOR library to use a different device, the application must set the new device to be used by calling cudaSetDevice and then create another cuTENSOR handle, which will be associated with the new device, by calling Create. Moreover, each handle by default has a plan cache that can store the least recently used Plan; its default capacity is 64, but it can be changed via Handle.ResizePlanCache if this is too little storage space. See the Plan Cache Guide for more information. The user is responsible for calling Handle.Close to free the resources associated with the handle. Remark: blocking, no reentrant, and thread-safe

Wraps cutensorCreate.

func (*Handle) Close

func (h *Handle) Close() error

Close frees all resources related to the provided library handle.

Remark: blocking, no reentrant, and thread-safe

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 cutensorDestroy.

func (Handle) Contract

func (h Handle) Contract(plan Plan, alpha Scalar, a driver.DevicePtr, b driver.DevicePtr, beta Scalar, c driver.DevicePtr, d driver.DevicePtr, workspace driver.DevicePtr, workspaceSize uint64, stream driver.Stream) error

Contract computes the tensor contraction D=alpha*A*B+beta*C.

D_(modes_(D))←α*A_(modes_(A))B_(modes_(B))+βC_(modes_(C)) The active CUDA device must match the CUDA device that was active at the time at which the plan was created. Example See NVIDIA/CUDALibrarySamples for a concrete example.

  • plan: Opaque handle holding the contraction execution plan (created by Handle.CreateContraction followed by Handle.CreatePlan)
  • alpha: Scaling for A*B. Its kind must match the scalar type of the operation descriptor plan was created from (OperationDescriptorScalarType).
  • a: Pointer to the data corresponding to A. Pointer to the GPU-accessible memory. The data accessed via this pointer must not overlap with the elements written to D
  • b: Pointer to the data corresponding to B. Pointer to the GPU-accessible memory. The data accessed via this pointer must not overlap with the elements written to D
  • beta: Scaling for C. Its kind must match the scalar type of the operation descriptor plan was created from (OperationDescriptorScalarType).
  • c: Pointer to the data corresponding to C. Pointer to the GPU-accessible memory
  • d: Pointer to the data corresponding to D. Pointer to the GPU-accessible memory
  • workspace: Optional parameter that may be NULL. This pointer provides additional workspace, in device memory, to the library for additional optimizations; the workspace must be aligned to 256 bytes (i.e., the default alignment of cudaMalloc)
  • workspaceSize: Size of the workspace array in bytes; please refer to Handle.EstimateWorkspaceSize to query the required workspace. While Handle.Contract does not strictly require a workspace for the contraction, it is still recommended to provided some small workspace (e.g., 128 MB)
  • stream: The CUDA stream in which all the computation is performed

Errors:

Wraps cutensorContract.

Example

ExampleHandle_Contract computes the tensor contraction C[m,n] = A[m,k] * B[k,n] in single precision. It returns early when the cuTENSOR library is not available. The device buffers dA, dB, and dC are CUDA device pointers, e.g. from the driver package's MemAlloc.

package main

import (
	"fmt"

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

func main() {
	h, err := cutensor.Create()
	if err != nil {
		fmt.Println("cuTENSOR unavailable:", err)
		return
	}
	defer h.Close()

	compute32f, err := cutensor.ComputeDesc32F()
	if err != nil {
		fmt.Println("compute descriptor:", err)
		return
	}

	const m, n, k = 64, 48, 32
	newDesc := func(extent ...int64) cutensor.TensorDescriptor {
		d, err := h.CreateTensorDescriptor(extent, nil, cutensor.R32F, 128)
		if err != nil {
			panic(err)
		}
		return d
	}
	descA := newDesc(m, k)
	descB := newDesc(k, n)
	descC := newDesc(m, n)
	defer descA.Close()
	defer descB.Close()
	defer descC.Close()

	modeA := []int32{'m', 'k'}
	modeB := []int32{'k', 'n'}
	modeC := []int32{'m', 'n'}
	op, err := h.CreateContraction(
		descA, modeA, cutensor.OpIdentity,
		descB, modeB, cutensor.OpIdentity,
		descC, modeC, cutensor.OpIdentity,
		descC, modeC, compute32f)
	if err != nil {
		fmt.Println("contraction:", err)
		return
	}
	defer op.Close()

	pref, err := h.CreatePlanPreference(cutensor.AlgoDefault, cutensor.JitModeNone)
	if err != nil {
		fmt.Println("plan preference:", err)
		return
	}
	defer pref.Close()

	wsSize, err := h.EstimateWorkspaceSize(op, pref, cutensor.WorkspaceDefault)
	if err != nil {
		fmt.Println("workspace:", err)
		return
	}
	plan, err := h.CreatePlan(op, pref, wsSize)
	if err != nil {
		fmt.Println("plan:", err)
		return
	}
	defer plan.Close()

	var dA, dB, dC, dWorkspace driver.DevicePtr // device allocations
	alpha, beta := float32(1), float32(0)
	err = h.Contract(plan,
		cutensor.Float32Scalar(alpha), dA, dB,
		cutensor.Float32Scalar(beta), dC, dC,
		dWorkspace, wsSize, driver.Stream(0))
	if err != nil {
		fmt.Println("contract:", err)
		return
	}
	fmt.Println("contraction enqueued")
}

func (Handle) ContractTrinary

func (h Handle) ContractTrinary(plan Plan, alpha Scalar, a driver.DevicePtr, b driver.DevicePtr, c driver.DevicePtr, beta Scalar, d driver.DevicePtr, e driver.DevicePtr, workspace driver.DevicePtr, workspaceSize uint64, stream driver.Stream) error

ContractTrinary computes the tensor contraction E=alpha*A*B*C+beta*D.

E_(modes_(E))←α*A_(modes_(A))B_(modes_(B))C_(modes_(C))+βD_(modes_(D)) The active CUDA device must match the CUDA device that was active at the time at which the plan was created. Example See NVIDIA/CUDALibrarySamples for a concrete example.

  • plan: Opaque handle holding the contraction execution plan (created by Handle.CreateContractionTrinary followed by Handle.CreatePlan)
  • alpha: Scaling for A*B*C. Its kind must match the scalar type of the operation descriptor plan was created from (OperationDescriptorScalarType).
  • a: Pointer to the data corresponding to A. Pointer to the GPU-accessible memory. The data accessed via this pointer must not overlap with the elements written to E
  • b: Pointer to the data corresponding to B. Pointer to the GPU-accessible memory. The data accessed via this pointer must not overlap with the elements written to E
  • c: Pointer to the data corresponding to C. Pointer to the GPU-accessible memory. The data accessed via this pointer must not overlap with the elements written to E
  • beta: Scaling for D. Its kind must match the scalar type of the operation descriptor plan was created from (OperationDescriptorScalarType).
  • d: Pointer to the data corresponding to D. Pointer to the GPU-accessible memory
  • e: Pointer to the data corresponding to E. Pointer to the GPU-accessible memory
  • workspace: Optional parameter that may be NULL. This pointer provides additional workspace, in device memory, to the library for additional optimizations; the workspace must be aligned to 256 bytes (i.e., the default alignment of cudaMalloc)
  • workspaceSize: Size of the workspace array in bytes; please refer to Handle.EstimateWorkspaceSize to query the required workspace. While Handle.Contract does not strictly require a workspace for the contraction, it is still recommended to provided some small workspace (e.g., 128 MB)
  • stream: The CUDA stream in which all the computation is performed

Errors:

Wraps cutensorContractTrinary.

func (Handle) CreateContraction

func (h Handle) CreateContraction(descA TensorDescriptor, modeA []int32, opA OperatorT, descB TensorDescriptor, modeB []int32, opB OperatorT, descC TensorDescriptor, modeC []int32, opC OperatorT, descD TensorDescriptor, modeD []int32, descCompute ComputeDescriptor) (OperationDescriptor, error)

CreateContraction allocates a OperationDescriptor object that encodes a tensor contraction of the form D=αAB+βC.

Allocates data for desc to be used to perform a tensor contraction of the form D_(modes_(D))←αop_(A)(A_(modes_(A)))op_(B)(B_(modes_(B)))+βop_(C)(C_(modes_(C))). See Handle.CreatePlan (or cutensorCreatePlanAutotuned) to create the plan (i.e., to select the kernel) followed by a call to Handle.Contract to perform the actual contraction. The user is responsible for calling OperationDescriptor.Close to free the resources associated with the descriptor. Supported data-type combinations are:

typeA        typeB        typeC        descCompute                   typeScalar  Tensor Core
CUDA_R_16F   CUDA_R_16F   CUDA_R_16F   CUTENSOR_COMPUTE_DESC_32F     CUDA_R_32F  Volta+
CUDA_R_16BF  CUDA_R_16BF  CUDA_R_16BF  CUTENSOR_COMPUTE_DESC_32F     CUDA_R_32F  Ampere+
CUDA_R_32F   CUDA_R_32F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_32F     CUDA_R_32F  No
CUDA_R_32F   CUDA_R_32F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_TF32    CUDA_R_32F  Ampere+
CUDA_R_32F   CUDA_R_32F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_3XTF32  CUDA_R_32F  Ampere+
CUDA_R_32F   CUDA_R_32F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_16BF    CUDA_R_32F  Ampere+
CUDA_R_32F   CUDA_R_32F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_16F     CUDA_R_32F  Volta+
CUDA_R_64F   CUDA_R_64F   CUDA_R_64F   CUTENSOR_COMPUTE_DESC_64F     CUDA_R_64F  Ampere+
CUDA_R_64F   CUDA_R_64F   CUDA_R_64F   CUTENSOR_COMPUTE_DESC_32F     CUDA_R_64F  No
CUDA_C_32F   CUDA_C_32F   CUDA_C_32F   CUTENSOR_COMPUTE_DESC_32F     CUDA_C_32F  No
CUDA_C_32F   CUDA_C_32F   CUDA_C_32F   CUTENSOR_COMPUTE_DESC_TF32    CUDA_C_32F  Ampere+
CUDA_C_32F   CUDA_C_32F   CUDA_C_32F   CUTENSOR_COMPUTE_DESC_3XTF32  CUDA_C_32F  Ampere+
CUDA_C_64F   CUDA_C_64F   CUDA_C_64F   CUTENSOR_COMPUTE_DESC_64F     CUDA_C_64F  Ampere+
CUDA_C_64F   CUDA_C_64F   CUDA_C_64F   CUTENSOR_COMPUTE_DESC_32F     CUDA_C_64F  No
CUDA_R_64F   CUDA_C_64F   CUDA_C_64F   CUTENSOR_COMPUTE_DESC_64F     CUDA_C_64F  No
CUDA_C_64F   CUDA_R_64F   CUDA_C_64F   CUTENSOR_COMPUTE_DESC_64F     CUDA_C_64F  No
CUDA_R_64F   CUDA_R_64F   CUDA_R_64F   CUTENSOR_COMPUTE_DESC_8XINT8  CUDA_R_64F  Hopper+
CUDA_C_64F   CUDA_C_64F   CUDA_C_64F   CUTENSOR_COMPUTE_DESC_8XINT8  CUDA_C_64F  Hopper+
CUDA_R_32F   CUDA_R_32F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_9X16BF  CUDA_R_32F  Hopper+
CUDA_C_32F   CUDA_C_32F   CUDA_C_32F   CUTENSOR_COMPUTE_DESC_9X16BF  CUDA_C_32F  Hopper+
CUDA_R_32F   CUDA_R_32F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_4X16F   CUDA_R_32F  Blackwell+
CUDA_C_32F   CUDA_C_32F   CUDA_C_32F   CUTENSOR_COMPUTE_DESC_4X16F   CUDA_C_32F  Blackwell+

Parameters:

  • desc: This opaque struct gets allocated and filled with the information that encodes the tensor contraction operation
  • descA: The descriptor that holds the information about the data type, modes and strides of A
  • modeA: Array with ‘nmodeA’ entries that represent the modes of A. The modeA[i] corresponds to extent[i] and stride[i] w.r.t. the arguments provided to cutensorInitTensorDescriptor
  • opA: Unary operator that will be applied to each element of A before it is further processed. The original data of this tensor remains unchanged
  • descB: The descriptor that holds information about the data type, modes, and strides of B
  • modeB: Array with ‘nmodeB’ entries that represent the modes of B. The modeB[i] corresponds to extent[i] and stride[i] w.r.t. the arguments provided to cutensorInitTensorDescriptor
  • opB: Unary operator that will be applied to each element of B before it is further processed. The original data of this tensor remains unchanged
  • descC: The descriptor that holds information about the data type, modes, and strides of C
  • modeC: Array with ‘nmodeC’ entries that represent the modes of C. The modeC[i] corresponds to extent[i] and stride[i] w.r.t. the arguments provided to cutensorInitTensorDescriptor
  • opC: Unary operator applied to each element of C before it is further processed. Currently only OpIdentity is supported. The original data of this tensor remains unchanged
  • descD: The descriptor that holds information about the data type, modes, and strides of D (must be identical to descC for now)
  • modeD: Array with ‘nmodeD’ entries that represent the modes of D (must be identical to modeC for now). The modeD[i] corresponds to extent[i] and stride[i] w.r.t. the arguments provided to cutensorInitTensorDescriptor
  • descCompute: Determines the precision in which this operations is performed

Errors:

len(modeA) must equal the number of modes of descA; nothing checks it. len(modeB) must equal the number of modes of descB; nothing checks it. len(modeC) must equal the number of modes of descC; nothing checks it. len(modeD) must equal the number of modes of descD; nothing checks it.

Wraps cutensorCreateContraction.

func (Handle) CreateContractionTrinary

func (h Handle) CreateContractionTrinary(descA TensorDescriptor, modeA []int32, opA OperatorT, descB TensorDescriptor, modeB []int32, opB OperatorT, descC TensorDescriptor, modeC []int32, opC OperatorT, descD TensorDescriptor, modeD []int32, opD OperatorT, descE TensorDescriptor, modeE []int32, descCompute ComputeDescriptor) (OperationDescriptor, error)

CreateContractionTrinary allocates a OperationDescriptor object that encodes a tensor contraction of the form E=αABC+βD.

Allocates data for desc to be used to perform a tensor contraction of the form E_(modes_(E))←αop_(A)(A_(modes_(A)))op_(B)(B_(modes_(B)))op_(C)(C_(modes_(C)))+βop_(D)(D_(modes_(D))). See Handle.CreatePlan (or cutensorCreatePlanAutotuned) to create the plan (i.e., to select the kernel) followed by a call to Handle.ContractTrinary to perform the actual contraction. The user is responsible for calling OperationDescriptor.Close to free the resources associated with the descriptor. The performance improvements due to this API are currently especially high if your data resides on the host (i.e. out-of-core), targeting Grace-based systems. Supported data-type combinations are:

  • desc: This opaque struct gets allocated and filled with the information that encodes the tensor contraction operation
  • descA: The descriptor that holds the information about the data type, modes and strides of A
  • modeA: Array with ‘nmodeA’ entries that represent the modes of A. The modeA[i] corresponds to extent[i] and stride[i] w.r.t. the arguments provided to cutensorInitTensorDescriptor
  • opA: Unary operator that will be applied to each element of A before it is further processed. The original data of this tensor remains unchanged
  • descB: The descriptor that holds information about the data type, modes, and strides of B
  • modeB: Array with ‘nmodeB’ entries that represent the modes of B. The modeB[i] corresponds to extent[i] and stride[i] w.r.t. the arguments provided to cutensorInitTensorDescriptor
  • opB: Unary operator that will be applied to each element of B before it is further processed. The original data of this tensor remains unchanged
  • descC: The escriptor that holds information about the data type, modes, and strides of C
  • modeC: Array with ‘nmodeC’ entries that represent the modes of C. The modeC[i] corresponds to extent[i] and stride[i] w.r.t. the arguments provided to cutensorInitTensorDescriptor
  • opC: Unary operator that will be applied to each element of C before it is further processed. The original data of this tensor remains unchanged
  • descD: The escriptor that holds information about the data type, modes, and strides of D
  • modeD: Array with ‘nmodeD’ entries that represent the modes of D. The modeD[i] corresponds to extent[i] and stride[i] w.r.t. the arguments provided to cutensorInitTensorDescriptor
  • opD: Unary operator that will be applied to each element of D before it is further processed. The original data of this tensor remains unchanged
  • descE: The descriptor that holds information about the data type, modes, and strides of E (must be identical to descD for now)
  • modeE: Array with ‘nmodeE’ entries that represent the modes of E (must be identical to modeD for now). The modeE[i] corresponds to extent[i] and stride[i] w.r.t. the arguments provided to cutensorInitTensorDescriptor
  • descCompute: Determines the precision in which this operations is performed

Errors:

len(modeA) must equal the number of modes of descA; nothing checks it. len(modeB) must equal the number of modes of descB; nothing checks it. len(modeC) must equal the number of modes of descC; nothing checks it. len(modeD) must equal the number of modes of descD; nothing checks it. len(modeE) must equal the number of modes of descE; nothing checks it.

Wraps cutensorCreateContractionTrinary.

func (Handle) CreateElementwiseBinary

func (h Handle) CreateElementwiseBinary(descA TensorDescriptor, modeA []int32, opA OperatorT, descC TensorDescriptor, modeC []int32, opC OperatorT, descD TensorDescriptor, modeD []int32, opAC OperatorT, descCompute ComputeDescriptor) (OperationDescriptor, error)

CreateElementwiseBinary creates an operation descriptor for an elementwise binary operation.

The binary operation has the following general form: D_(Π^(C)(i₀,i₁,...,iₙ))=Φ_(AC)(αop_(A)(A_(Π^(A)(i₀,i₁,...,iₙ))),γop_(C)(C_(Π^(C)(i₀,i₁,...,iₙ)))) Call Handle.ElementwiseBinaryExecute to perform the actual operation. Supported data-type combinations are:

typeA        typeC        descCompute
CUDA_R_16F   CUDA_R_16F   CUTENSOR_COMPUTE_DESC_16F
CUDA_R_16F   CUDA_R_16F   CUTENSOR_COMPUTE_DESC_32F
CUDA_R_16BF  CUDA_R_16BF  CUTENSOR_COMPUTE_DESC_16BF
CUDA_R_16BF  CUDA_R_16BF  CUTENSOR_COMPUTE_DESC_32F
CUDA_R_32F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_32F
CUDA_R_64F   CUDA_R_64F   CUTENSOR_COMPUTE_DESC_64F
CUDA_C_32F   CUDA_C_32F   CUTENSOR_COMPUTE_DESC_32F
CUDA_C_64F   CUDA_C_64F   CUTENSOR_COMPUTE_DESC_64F
CUDA_R_32F   CUDA_R_16F   CUTENSOR_COMPUTE_DESC_32F
CUDA_R_64F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_64F
CUDA_C_64F   CUDA_C_32F   CUTENSOR_COMPUTE_DESC_64F

Remark: calls asynchronous functions, no reentrant, and thread-safe

  • desc: This opaque struct gets allocated and filled with the information that encodes the requested elementwise operation
  • descA: The descriptor that holds the information about the data type, modes, and strides of A
  • modeA: Array (in host memory) of size descA->numModes that holds the names of the modes of A (e.g., if A_{a,b,c} => modeA = {‘a’,’b’,’c’}). The modeA[i] corresponds to extent[i] and stride[i] w.r.t. the arguments provided to Handle.CreateTensorDescriptor
  • opA: Unary operator that will be applied to each element of A before it is further processed. The original data of this tensor remains unchanged
  • descC: The descriptor that holds information about the data type, modes, and strides of C
  • modeC: Array (in host memory) of size descC->numModes that holds the names of the modes of C. The modeC[i] corresponds to extent[i] and stride[i] of the Handle.CreateTensorDescriptor
  • opC: Unary operator that will be applied to each element of C before it is further processed. The original data of this tensor remains unchanged
  • descD: The descriptor that holds information about the data type, modes, and strides of D. Notice that we currently request descD and descC to be identical
  • modeD: Array (in host memory) of size descD->numModes that holds the names of the modes of D. The modeD[i] corresponds to extent[i] and stride[i] of the Handle.CreateTensorDescriptor
  • opAC: Element-wise binary operator (corresponding to Φ_(AC) above)
  • descCompute: Determines the precision in which this operations is performed

Errors:

len(modeA) must equal the number of modes of descA; nothing checks it. len(modeC) must equal the number of modes of descC; nothing checks it. len(modeD) must equal the number of modes of descD; nothing checks it.

Wraps cutensorCreateElementwiseBinary.

func (Handle) CreateElementwiseTrinary

func (h Handle) CreateElementwiseTrinary(descA TensorDescriptor, modeA []int32, opA OperatorT, descB TensorDescriptor, modeB []int32, opB OperatorT, descC TensorDescriptor, modeC []int32, opC OperatorT, descD TensorDescriptor, modeD []int32, opAB OperatorT, opABC OperatorT, descCompute ComputeDescriptor) (OperationDescriptor, error)

CreateElementwiseTrinary creates an operation descriptor that encodes an elementwise trinary operation.

Said trinary operation has the following general form: D_(Π^(C)(i₀,i₁,...,iₙ))=Φ_(ABC)(Φ_(AB)(αop_(A)(A_(Π^(A)(i₀,i₁,...,iₙ))),βop_(B)(B_(Π^(B)(i₀,i₁,...,iₙ)))),γop_(C)(C_(Π^(C)(i₀,i₁,...,iₙ)))) Where

  • A,B,C,D are multi-mode tensors (of arbitrary data types).
  • Π^(A),Π^(B),Π^(C) are permutation operators that permute the modes of A, B, and C respectively.
  • op_(A),op_(B),op_(C) are unary element-wise operators (e.g., IDENTITY, CONJUGATE).
  • Φ_(ABC),Φ_(AB) are binary element-wise operators (e.g., ADD, MUL, MAX, MIN).

Notice that the broadcasting (of a mode) can be achieved by simply omitting that mode from the respective tensor. Moreover, modes may appear in any order, giving users a greater flexibility. The only restrictions are:

  • modes that appear in A or B must also appear in the output tensor; a mode that only appears in the input would be contracted and such an operation would be covered by either Handle.Contract or Handle.Reduce.
  • each mode may appear in each tensor at most once.

Input tensors may be read even if the value of the corresponding scalar is zero. Examples:

  • D_(a,b,c,d)=A_(b,d,a,c)
  • D_(a,b,c,d)=2.2*A_(b,d,a,c)+1.3*B_(c,b,d,a)
  • D_(a,b,c,d)=2.2*A_(b,d,a,c)+1.3*B_(c,b,d,a)+C_(a,b,c,d)
  • D_(a,b,c,d)=min((2.2*A_(b,d,a,c)+1.3*B_(c,b,d,a)),C_(a,b,c,d))

Call Handle.ElementwiseTrinaryExecute to perform the actual operation. Please use OperationDescriptor.Close to deallocated the descriptor once it is no longer used. Supported data-type combinations are:

typeA        typeB        typeC        descCompute
CUDA_R_16F   CUDA_R_16F   CUDA_R_16F   CUTENSOR_COMPUTE_DESC_16F
CUDA_R_16F   CUDA_R_16F   CUDA_R_16F   CUTENSOR_COMPUTE_DESC_32F
CUDA_R_16BF  CUDA_R_16BF  CUDA_R_16BF  CUTENSOR_COMPUTE_DESC_16BF
CUDA_R_16BF  CUDA_R_16BF  CUDA_R_16BF  CUTENSOR_COMPUTE_DESC_32F
CUDA_R_32F   CUDA_R_32F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_32F
CUDA_R_64F   CUDA_R_64F   CUDA_R_64F   CUTENSOR_COMPUTE_DESC_64F
CUDA_C_32F   CUDA_C_32F   CUDA_C_32F   CUTENSOR_COMPUTE_DESC_32F
CUDA_C_64F   CUDA_C_64F   CUDA_C_64F   CUTENSOR_COMPUTE_DESC_64F
CUDA_R_32F   CUDA_R_32F   CUDA_R_16F   CUTENSOR_COMPUTE_DESC_32F
CUDA_R_64F   CUDA_R_64F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_64F
CUDA_C_64F   CUDA_C_64F   CUDA_C_32F   CUTENSOR_COMPUTE_DESC_64F

Remark: calls asynchronous functions, no reentrant, and thread-safe

  • desc: This opaque struct gets allocated and filled with the information that encodes the requested elementwise operation
  • descA: A descriptor that holds the information about the data type, modes, and strides of A
  • modeA: Array (in host memory) of size descA->numModes that holds the names of the modes of A (e.g., if A_(a,b,c) then modeA = {‘a’,’b’,’c’}). The modeA[i] corresponds to extent[i] and stride[i] w.r.t. the arguments provided to Handle.CreateTensorDescriptor
  • opA: Unary operator that will be applied to each element of A before it is further processed. The original data of this tensor remains unchanged
  • descB: A descriptor that holds information about the data type, modes, and strides of B
  • modeB: Array (in host memory) of size descB->numModes that holds the names of the modes of B. modeB[i] corresponds to extent[i] and stride[i] of the Handle.CreateTensorDescriptor
  • opB: Unary operator that will be applied to each element of B before it is further processed. The original data of this tensor remains unchanged
  • descC: A descriptor that holds information about the data type, modes, and strides of C
  • modeC: Array (in host memory) of size descC->numModes that holds the names of the modes of C. The modeC[i] corresponds to extent[i] and stride[i] of the Handle.CreateTensorDescriptor
  • opC: Unary operator that will be applied to each element of C before it is further processed. The original data of this tensor remains unchanged
  • descD: A descriptor that holds information about the data type, modes, and strides of D. Notice that we currently request descD and descC to be identical
  • modeD: Array (in host memory) of size descD->numModes that holds the names of the modes of D. The modeD[i] corresponds to extent[i] and stride[i] of the Handle.CreateTensorDescriptor
  • opAB: Element-wise binary operator (see Φ_(AB) above)
  • opABC: Element-wise binary operator (see Φ_(ABC) above)
  • descCompute: Determines the precision in which this operations is performed

Errors:

  • ErrArchMismatch: if the device is either not ready, or the target architecture is not supported.
  • ErrInvalidValue: if some input data is invalid (this typically indicates an user error).
  • ErrNotInitialized: if the handle is not initialized.

len(modeA) must equal the number of modes of descA; nothing checks it. len(modeB) must equal the number of modes of descB; nothing checks it. len(modeC) must equal the number of modes of descC; nothing checks it. len(modeD) must equal the number of modes of descD; nothing checks it.

Wraps cutensorCreateElementwiseTrinary.

func (Handle) CreatePermutation

func (h Handle) CreatePermutation(descA TensorDescriptor, modeA []int32, opA OperatorT, descB TensorDescriptor, modeB []int32, descCompute ComputeDescriptor) (OperationDescriptor, error)

CreatePermutation creates an operation descriptor for a tensor permutation.

The tensor permutation has the following general form: B_(Π^(B)(i₀,i₁,...,iₙ))=αop_(A)(A_(Π^(A)(i₀,i₁,...,iₙ))) Consequently, this function performs an out-of-place tensor permutation and is a specialization of Handle.CreateElementwiseBinary. Where

  • A and B are multi-mode tensors (of arbitrary data types),
  • Π^(A),Π^(B) are permutation operators that permute the modes of A, B respectively,
  • op_(A) is an unary element-wise operators (e.g., IDENTITY, SQR, CONJUGATE), and

Broadcasting (of a mode) can be achieved by simply omitting that mode from the respective tensor. Modes may appear in any order. The only restrictions are:

  • modes that appear in A must also appear in the output tensor.
  • each mode may appear in each tensor at most once.

Supported data-type combinations are:

typeA        typeB        descCompute
CUDA_R_16F   CUDA_R_16F   CUTENSOR_COMPUTE_DESC_16F
CUDA_R_16F   CUDA_R_16F   CUTENSOR_COMPUTE_DESC_32F
CUDA_R_16F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_32F
CUDA_R_32F   CUDA_R_16F   CUTENSOR_COMPUTE_DESC_32F
CUDA_R_16BF  CUDA_R_16BF  CUTENSOR_COMPUTE_DESC_16BF
CUDA_R_16BF  CUDA_R_16BF  CUTENSOR_COMPUTE_DESC_32F
CUDA_R_32F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_32F
CUDA_R_64F   CUDA_R_64F   CUTENSOR_COMPUTE_DESC_64F
CUDA_R_32F   CUDA_R_64F   CUTENSOR_COMPUTE_DESC_64F
CUDA_R_64F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_64F
CUDA_C_32F   CUDA_C_32F   CUTENSOR_COMPUTE_DESC_32F
CUDA_C_64F   CUDA_C_64F   CUTENSOR_COMPUTE_DESC_64F
CUDA_C_32F   CUDA_C_64F   CUTENSOR_COMPUTE_DESC_64F
CUDA_C_64F   CUDA_C_32F   CUTENSOR_COMPUTE_DESC_64F

Remark: calls asynchronous functions, no reentrant, and thread-safe

  • desc: This opaque struct gets allocated and filled with the information that encodes the requested permutation
  • descA: The descriptor that holds information about the data type, modes, and strides of A
  • modeA: Array of size descA->numModes that holds the names of the modes of A (e.g., if A_{a,b,c} => modeA = {‘a’,’b’,’c’})
  • opA: Unary operator that will be applied to each element of A before it is further processed. The original data of this tensor remains unchanged
  • descB: The descriptor that holds information about the data type, modes, and strides of B
  • modeB: Array of size descB->numModes that holds the names of the modes of B
  • descCompute: Determines the precision in which this operations is performed

Errors:

len(modeA) must equal the number of modes of descA; nothing checks it. len(modeB) must equal the number of modes of descB; nothing checks it.

Wraps cutensorCreatePermutation.

func (Handle) CreatePlan

func (h Handle) CreatePlan(desc OperationDescriptor, pref PlanPreference, workspaceSizeLimit uint64) (Plan, error)

CreatePlan allocates a Plan object, selects an appropriate kernel for a given operation (encoded by desc) and prepares a plan that encodes the execution.

This function applies cuTENSOR’s heuristic to select a candidate/kernel for a given operation (created by either Handle.CreateContraction, Handle.CreateReduction, Handle.CreatePermutation, * Handle.CreateElementwiseBinary, Handle.CreateElementwiseTrinary, Handle.CreateContractionTrinary, or cutensorCreateBlockSparseContraction). The created plan can then be be passed to either Handle.Contract, Handle.Reduce, Handle.Permute, Handle.ElementwiseBinaryExecute, Handle.ElementwiseTrinaryExecute, or Handle.ContractTrinary to perform the actual operation. The plan is created for the active CUDA device.

Note: Handle.CreatePlan must not be captured via CUDA graphs if Just-In-Time compilation is enabled (i.e., JitmodeT is not JitModeNone).

A nil error means a viable candidate has been found.

Errors:

Wraps cutensorCreatePlan.

func (Handle) CreatePlanPreference

func (h Handle) CreatePlanPreference(algo AlgoT, jitMode JitmodeT) (PlanPreference, error)

CreatePlanPreference allocates the PlanPreference, enabling users to limit the applicable kernels for a given plan/operation.

  • pref: Pointer to the structure holding the PlanPreference allocated by this function. See PlanPreference
  • algo: Allows users to select a specific algorithm. AlgoDefault lets the heuristic choose the algorithm. Any value >= 0 selects a specific GEMM-like algorithm and deactivates the heuristic. If a specified algorithm is not supported ErrNotSupported is returned. See AlgoT for additional choices
  • jitMode: Determines if cuTENSOR is allowed to use JIT-compiled kernels (leading to a longer plan-creation phase); see JitmodeT

Wraps cutensorCreatePlanPreference.

func (Handle) CreateReduction

func (h Handle) CreateReduction(descA TensorDescriptor, modeA []int32, opA OperatorT, descC TensorDescriptor, modeC []int32, opC OperatorT, descD TensorDescriptor, modeD []int32, opReduce OperatorT, descCompute ComputeDescriptor) (OperationDescriptor, error)

CreateReduction creates a cutensorOperatorDescriptor_t object that encodes a tensor reduction of the form D=alpha*opReduce(opA(A))+beta*opC(C).

For example this function enables users to reduce an entire tensor to a scalar: C[] = alpha * A[i,j,k]; This function is also able to perform partial reductions; for instance: C[i,j] = alpha * A[k,j,i]; in this case only elements along the k-mode are contracted. The binary opReduce operator provides extra control over what kind of a reduction ought to be performed. For instance, setting opReduce to OpAdd reduces element of A via a summation while OpMax would find the largest element in A. Supported data-type combinations are:

typeA        typeB        typeC        typeCompute
CUDA_R_16F   CUDA_R_16F   CUDA_R_16F   CUTENSOR_COMPUTE_DESC_16F
CUDA_R_16F   CUDA_R_16F   CUDA_R_16F   CUTENSOR_COMPUTE_DESC_32F
CUDA_R_16BF  CUDA_R_16BF  CUDA_R_16BF  CUTENSOR_COMPUTE_DESC_16BF
CUDA_R_16BF  CUDA_R_16BF  CUDA_R_16BF  CUTENSOR_COMPUTE_DESC_32F
CUDA_R_32F   CUDA_R_32F   CUDA_R_32F   CUTENSOR_COMPUTE_DESC_32F
CUDA_R_64F   CUDA_R_64F   CUDA_R_64F   CUTENSOR_COMPUTE_DESC_64F
CUDA_C_32F   CUDA_C_32F   CUDA_C_32F   CUTENSOR_COMPUTE_DESC_32F
CUDA_C_64F   CUDA_C_64F   CUDA_C_64F   CUTENSOR_COMPUTE_DESC_64F

Parameters:

  • desc: This opaque struct gets allocated and filled with the information that encodes the requested tensor reduction operation
  • descA: The descriptor that holds the information about the data type, modes and strides of A
  • modeA: Array with ‘nmodeA’ entries that represent the modes of A. modeA[i] corresponds to extent[i] and stride[i] w.r.t. the arguments provided to Handle.CreateTensorDescriptor. Modes that only appear in modeA but not in modeC are reduced (contracted)
  • opA: Unary operator that will be applied to each element of A before it is further processed. The original data of this tensor remains unchanged
  • descC: The descriptor that holds the information about the data type, modes and strides of C
  • modeC: Array with ‘nmodeC’ entries that represent the modes of C. modeC[i] corresponds to extent[i] and stride[i] w.r.t. the arguments provided to Handle.CreateTensorDescriptor
  • opC: Unary operator that will be applied to each element of C before it is further processed. The original data of this tensor remains unchanged
  • descD: Must be identical to descC for now
  • modeD: Must be identical to modeC for now
  • opReduce: binary operator used to reduce elements of A

Errors:

len(modeA) must equal the number of modes of descA; nothing checks it. len(modeC) must equal the number of modes of descC; nothing checks it. len(modeD) must equal the number of modes of descD; nothing checks it.

Wraps cutensorCreateReduction.

func (Handle) CreateTensorDescriptor

func (h Handle) CreateTensorDescriptor(extent []int64, stride []int64, dataType DataType, alignmentRequirement uint32) (TensorDescriptor, error)

CreateTensorDescriptor creates a tensor descriptor.

This allocates a small amount of host-memory. The user is responsible for calling TensorDescriptor.Close to free the associated resources once the tensor descriptor is no longer used.

  • desc: Pointer to the address where the allocated tensor descriptor object will be stored
  • extent: Extent of each mode (must be larger than zero)
  • stride: stride[i] denotes the displacement (a.k.a. stride)—in elements of the base type—between two consecutive elements in the ith-mode. If stride is NULL, a packed generalized column-major memory layout is assumed (i.e., the strides increase monotonically from left to right). Each stride must be larger than zero; to be precise, a stride of zero can be achieved by omitting this mode entirely; for instance instead of writing C[a,b] = A[b,a] with strideA(a) = 0, you can write C[a,b] = A[b] directly; cuTENSOR will then automatically infer that the a-mode in A should be broadcasted
  • dataType: Data type of the stored entries
  • alignmentRequirement: Alignment (in bytes) to the base pointer that will be used in conjunction with this tensor descriptor (e.g., cudaMalloc has a default alignment of 256 bytes)

Errors:

  • ErrInvalidValue: if some input data is invalid (this typically indicates an user error).
  • ErrNotInitialized: if the handle is not initialized.
  • ErrNotSupported: if the requested descriptor is not supported (e.g., due to non-supported data type).

Wraps cutensorCreateTensorDescriptor.

func (Handle) ElementwiseBinaryExecute

func (h Handle) ElementwiseBinaryExecute(plan Plan, alpha Scalar, a driver.DevicePtr, gamma Scalar, c driver.DevicePtr, d driver.DevicePtr, stream driver.Stream) error

ElementwiseBinaryExecute performs an element-wise tensor operation for two input tensors (see Handle.CreateElementwiseBinary)

This function performs a element-wise tensor operation of the form: D_(Π^(C)(i₀,i₁,...,iₙ))=Φ_(AC)(αop_(A)(A_(Π^(A)(i₀,i₁,...,iₙ))),γop_(C)(C_(Π^(C)(i₀,i₁,...,iₙ)))) See Handle.CreateElementwiseBinary for details. Remark: calls asynchronous functions, no reentrant, and thread-safe

  • plan: Opaque handle holding all information about the desired elementwise operation (created by Handle.CreateElementwiseBinary followed by Handle.CreatePlan)
  • alpha: Scaling factor for A (see OperationDescriptor.Attribute(desc, CUTENSOR_OPERATION_SCALAR_TYPE) to query the expected data type). If alpha is zero, A is not read and the corresponding unary operator is not applied. Its kind must match the scalar type of the operation descriptor plan was created from (OperationDescriptorScalarType).
  • a: Multi-mode tensor (described by descA as part of Handle.CreateElementwiseBinary). Pointer to the GPU-accessible memory. The data accessed via this pointer must not overlap with the elements written to D
  • gamma: Scaling factor for C (see OperationDescriptor.Attribute(desc, CUTENSOR_OPERATION_SCALAR_TYPE) to query the expected data type). If gamma is zero, C is not read and the corresponding unary operator is not applied. Its kind must match the scalar type of the operation descriptor plan was created from (OperationDescriptorScalarType).
  • c: Multi-mode tensor (described by descC as part of Handle.CreateElementwiseBinary). Pointer to the GPU-accessible memory. The data accessed via this pointer must not overlap with the elements written to D
  • d: Multi-mode tensor (described by descD as part of Handle.CreateElementwiseBinary). Pointer to the GPU-accessible memory ( C and D may be identical, if and only if descC == descD)
  • stream: The CUDA stream used to perform the operation

Errors:

Wraps cutensorElementwiseBinaryExecute.

func (Handle) ElementwiseTrinaryExecute

func (h Handle) ElementwiseTrinaryExecute(plan Plan, alpha Scalar, a driver.DevicePtr, beta Scalar, b driver.DevicePtr, gamma Scalar, c driver.DevicePtr, d driver.DevicePtr, stream driver.Stream) error

ElementwiseTrinaryExecute performs an element-wise tensor operation for three input tensors (see Handle.CreateElementwiseTrinary)

This function performs a element-wise tensor operation of the form: D_(Π^(C)(i₀,i₁,...,iₙ))=Φ_(ABC)(Φ_(AB)(αop_(A)(A_(Π^(A)(i₀,i₁,...,iₙ))),βop_(B)(B_(Π^(B)(i₀,i₁,...,iₙ)))),γop_(C)(C_(Π^(C)(i₀,i₁,...,iₙ)))) See Handle.CreateElementwiseTrinary for details. Remark: calls asynchronous functions, no reentrant, and thread-safe

  • plan: Opaque handle holding all information about the desired elementwise operation (created by Handle.CreateElementwiseTrinary followed by Handle.CreatePlan)
  • alpha: Scaling factor for A (see OperationDescriptor.Attribute(desc, CUTENSOR_OPERATION_SCALAR_TYPE) to query the expected data type). If alpha is zero, A is not read and the corresponding unary operator is not applied. Its kind must match the scalar type of the operation descriptor plan was created from (OperationDescriptorScalarType).
  • a: Multi-mode tensor (described by descA as part of Handle.CreateElementwiseTrinary). Pointer to the GPU-accessible memory. The data accessed via this pointer must not overlap with the elements written to D
  • beta: Scaling factor for B (see OperationDescriptor.Attribute(desc, CUTENSOR_OPERATION_SCALAR_TYPE) to query the expected data type). If beta is zero, B is not read and the corresponding unary operator is not applied. Its kind must match the scalar type of the operation descriptor plan was created from (OperationDescriptorScalarType).
  • b: Multi-mode tensor (described by descB as part of Handle.CreateElementwiseTrinary). Pointer to the GPU-accessible memory. The data accessed via this pointer must not overlap with the elements written to D
  • gamma: Scaling factor for C (see OperationDescriptor.Attribute(desc, CUTENSOR_OPERATION_SCALAR_TYPE) to query the expected data type). If gamma is zero, C is not read and the corresponding unary operator is not applied. Its kind must match the scalar type of the operation descriptor plan was created from (OperationDescriptorScalarType).
  • c: Multi-mode tensor (described by descC as part of Handle.CreateElementwiseTrinary). Pointer to the GPU-accessible memory. The data accessed via this pointer must not overlap with the elements written to D
  • d: Multi-mode tensor (described by descD as part of Handle.CreateElementwiseTrinary). Pointer to the GPU-accessible memory ( C and D may be identical, if and only if descC == descD)
  • stream: The CUDA stream used to perform the operation

Errors:

Wraps cutensorElementwiseTrinaryExecute.

func (Handle) EstimateWorkspaceSize

func (h Handle) EstimateWorkspaceSize(desc OperationDescriptor, planPref PlanPreference, workspacePref WorksizepreferenceT) (uint64, error)

EstimateWorkspaceSize determines the required workspaceSize for the given operation encoded by desc.

  • desc: This opaque struct encodes the operation
  • planPref: This opaque struct restricts the space of viable candidates
  • workspacePref: This parameter influences the size of the workspace; see WorksizepreferenceT for details
  • workspaceSizeEstimate: The workspace size (in bytes) that is required for the given operation

Errors:

Wraps cutensorEstimateWorkspaceSize.

func (Handle) Permute

func (h Handle) Permute(plan Plan, alpha Scalar, a driver.DevicePtr, b driver.DevicePtr, stream driver.Stream) error

Permute performs the tensor permutation that is encoded by plan (see Handle.CreatePermutation).

This function performs an elementwise tensor operation of the form: B_(Π^(B)(i₀,i₁,...,iₙ))=αop_(A)(A_(Π^(A)(i₀,i₁,...,iₙ))) Consequently, this function performs an out-of-place tensor permutation. Where

  • A and B are multi-mode tensors (of arbitrary data types),
  • Π^(A),Π^(B) are permutation operators that permute the modes of A, B respectively,
  • op_(A) is an unary element-wise operators (e.g., IDENTITY, SQR, CONJUGATE), and is specified when creating the operation descriptor using Handle.CreatePermutation

Remark: calls asynchronous functions, no reentrant, and thread-safe

  • plan: Opaque handle holding all information about the desired tensor reduction (created by Handle.CreatePermutation followed by Handle.CreatePlan)
  • alpha: Scaling factor for A (see OperationDescriptor.Attribute(desc, CUTENSOR_OPERATION_SCALAR_TYPE)). If alpha is zero, A is not read and the corresponding unary operator is not applied. Its kind must match the scalar type of the operation descriptor plan was created from (OperationDescriptorScalarType).
  • a: Multi-mode tensor of type typeA with nmodeA modes. Pointer to the GPU-accessible memory. The data accessed via this pointer must not overlap with the elements written to D
  • b: Multi-mode tensor of type typeB with nmodeB modes. Pointer to the GPU-accessible memory
  • stream: The CUDA stream

Errors:

Wraps cutensorPermute.

func (Handle) ReadKernelCacheFromFile

func (h Handle) ReadKernelCacheFromFile(filename *byte) error

ReadKernelCacheFromFile reads a kernel cache from file and adds all non-existing JIT compiled kernels to the kernel cache.

A cache is only valid for the same cuTENSOR version and CUDA version; moreover, the GPU architecture (incl. multiprocessor count) must match, otherwise ErrInvalidValue will be returned. Remark: non-blocking, no reentrant, and thread-safe

  • filename: Specifies the filename (including the absolute path) to the file that holds all the cache information that have previously been written by Handle.WriteKernelCacheToFile

A nil error means the operation completed successfully, or the file pointed to by filename was empty.

Errors:

  • ErrInvalidValue: if the stored cache was created by a different cuTENSOR- or CUDA-version or if the GPU architecture (incl. multiprocessor count) doesn’t match.
  • ErrIoError: if the file cannot be read.
  • ErrNotInitialized: if the handle is not initialized.
  • ErrNotSupported: if the function is not available for the operating system, CUDA Toolkit, or compute capability of the device.

Wraps cutensorReadKernelCacheFromFile.

func (Handle) ReadPlanCacheFromFile

func (h Handle) ReadPlanCacheFromFile(filename *byte) (uint32, error)

ReadPlanCacheFromFile reads a Plan-Cache from file and overwrites the cachelines of the provided handle.

A cache is only valid for the same cuTENSOR version and CUDA version; moreover, the GPU architecture (incl. multiprocessor count) must match, otherwise ErrInvalidValue will be returned. Remark: non-blocking, no reentrant, and thread-safe

  • filename: Specifies the filename (including the absolute path) to the file that holds all the cache information that have previously been written by Handle.WritePlanCacheToFile
  • numCachelinesRead: On exit, this variable will hold the number of successfully-read cachelines, if Success is returned. Otherwise, this variable will hold the number of cachelines that are required to read all cachelines associated to the cache pointed to by filename; in that case ErrInsufficientWorkspace is returned

Errors:

  • ErrInsufficientWorkspace: if the stored cache requires more cachelines than those that are currently attached to the handle
  • ErrInvalidValue: if the stored cache was created by a different cuTENSOR- or CUDA-version or if the GPU architecture (incl. multiprocessor count) doesn’t match
  • ErrIoError: if the file cannot be read
  • ErrNotInitialized: if the handle is not initialized.

Wraps cutensorHandleReadPlanCacheFromFile.

func (Handle) Reduce

func (h Handle) Reduce(plan Plan, alpha Scalar, a driver.DevicePtr, beta Scalar, c driver.DevicePtr, d driver.DevicePtr, workspace driver.DevicePtr, workspaceSize uint64, stream driver.Stream) error

Reduce performs the tensor reduction that is encoded by plan (see Handle.CreateReduction).

  • plan: Opaque handle holding the reduction execution plan (created by Handle.CreateReduction followed by Handle.CreatePlan)
  • alpha: Scaling for A. Its kind must match the scalar type of the operation descriptor plan was created from (OperationDescriptorScalarType).
  • a: Pointer to the data corresponding to A in device memory. Pointer to the GPU-accessible memory. The data accessed via this pointer must not overlap with the elements written to D
  • beta: Scaling for C. Its kind must match the scalar type of the operation descriptor plan was created from (OperationDescriptorScalarType).
  • c: Pointer to the data corresponding to C in device memory. Pointer to the GPU-accessible memory
  • d: Pointer to the data corresponding to C in device memory. Pointer to the GPU-accessible memory
  • workspace: Scratchpad (device) memory of size —at least— workspaceSize bytes; the workspace must be aligned to 256 bytes (i.e., the default alignment of cudaMalloc)
  • workspaceSize: Please use Handle.EstimateWorkspaceSize to query the required workspace
  • stream: The CUDA stream in which all the computation is performed

Wraps cutensorReduce.

func (Handle) ResizePlanCache

func (h Handle) ResizePlanCache(numEntries uint32) error

ResizePlanCache Resizes the plan cache.

This function changes the number of plans that can be stored in the plan cache of the handle. Resizing invalidates the cache. While this function is not thread-safe, the resulting cache can be shared across different threads in a thread-safe manner. Remark: non-blocking, no reentrant, and not thread-safe

  • numEntries: Number of entries the cache will support

Errors:

Wraps cutensorHandleResizePlanCache.

func (Handle) WriteKernelCacheToFile

func (h Handle) WriteKernelCacheToFile(filename *byte) error

WriteKernelCacheToFile writes the —per library— kernel cache to file.

Writes the just-in-time compiled kernels to the provided file (those kernels belong to the library—not to the handle). Remark: non-blocking, no reentrant, and thread-safe

  • filename: Specifies the filename (including the absolute path) to the file that should hold all the cache information. Warning: an existing file will be overwritten

A nil error means the operation completed successfully or there were no kernels in the cache.

Errors:

  • ErrIoError: if the file cannot be written to.
  • ErrNotInitialized: if the handle is not initialized.
  • ErrNotSupported: if the function is not available for the operating system, CUDA Toolkit, or compute capability of the device.

Wraps cutensorWriteKernelCacheToFile.

func (Handle) WritePlanCacheToFile

func (h Handle) WritePlanCacheToFile(filename *byte) error

WritePlanCacheToFile writes the Plan-Cache (that belongs to the provided handle) to file.

Remark: non-blocking, no reentrant, and thread-safe

  • filename: Specifies the filename (including the absolute path) to the file that should hold all the cache information. Warning: an existing file will be overwritten

Errors:

Wraps cutensorHandleWritePlanCacheToFile.

type JitmodeT

type JitmodeT int32

JitmodeT determines the mode w.r.t. cuTENSOR's just-in-time compilation capability.

const (
	JitModeNone    JitmodeT = 0 // Indicates that no kernel will be just-in-time compiled.
	JitModeDefault JitmodeT = 1 // Indicates that the corresponding plan will try to compile a dedicated kernel for the given operation. Only supported for GPUs with compute capability >= 8.0 (Ampere or newer).
)

func (JitmodeT) String

func (e JitmodeT) String() string

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

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 libcutensor could not be opened. Attempts lists every name tried in order. Path is set when an explicit path, from Load or CUTENSOR_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 OperationDescriptor

type OperationDescriptor uintptr

OperationDescriptor is an opaque handle for cutensorOperationDescriptor_t.

func (OperationDescriptor) Attribute

func (o OperationDescriptor) Attribute(handle Handle, attr OperationdescriptorattributeT, buf unsafe.Pointer, sizeInBytes uint) error

Attribute retrieves an attribute of the provided OperationDescriptor object (see OperationdescriptorattributeT).

Block-sparse contraction descriptors only support the attributes OperationDescriptorScalarType, OperationDescriptorMovedBytes, and OperationDescriptorBlocksparseReproducible.

  • handle: Opaque handle holding cuTENSOR’s library context
  • attr: Specifies the attribute that will be retrieved
  • buf: This buffer (of size sizeInBytes) will hold the requested attribute of the provided OperationDescriptor object
  • sizeInBytes: Size of buf (in bytes); see OperationdescriptorattributeT for the exact size

Errors:

Wraps cutensorOperationDescriptorGetAttribute.

func (*OperationDescriptor) Close

func (o *OperationDescriptor) Close() error

Close frees all resources related to the provided descriptor.

Remark: blocking, no reentrant, and thread-safe

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 cutensorDestroyOperationDescriptor.

func (OperationDescriptor) SetAttribute

func (o OperationDescriptor) SetAttribute(handle Handle, attr OperationdescriptorattributeT, buf unsafe.Pointer, sizeInBytes uint) error

SetAttribute sets attribute of a OperationDescriptor object.

Block-sparse contraction descriptors only support the attribute OperationDescriptorBlocksparseReproducible.

  • handle: Opaque handle holding cuTENSOR’s library context
  • attr: Specifies the attribute that will be set
  • buf: This buffer (of size sizeInBytes) determines the value to which attr will be set
  • sizeInBytes: Size of buf (in bytes)

Errors:

Wraps cutensorOperationDescriptorSetAttribute.

type OperationdescriptorattributeT

type OperationdescriptorattributeT int32

OperationdescriptorattributeT lists all attributes of a OperationDescriptor that can be modified (see OperationDescriptor.SetAttribute and OperationDescriptor.Attribute).

const (
	OperationDescriptorTag                     OperationdescriptorattributeT = 0  // int32_t: enables users to distinguish two identical problems w.r.t. the sw-managed plan-cache. (default value: 0)
	OperationDescriptorScalarType              OperationdescriptorattributeT = 1  // cudaDataType_t: data type of the scaling factors
	OperationDescriptorFlops                   OperationdescriptorattributeT = 2  // float: number of floating-point operations necessary to perform this operation (assuming all scalar are not equal to zero, unless otherwise specified)
	OperationDescriptorMovedBytes              OperationdescriptorattributeT = 3  // float: minimal number of bytes transferred from/to global-memory (assuming all scalar are not equal to zero, unless otherwise specified)
	OperationDescriptorPaddingLeft             OperationdescriptorattributeT = 4  // uint32_t[] (of size descOut->numModes): Each entry i holds the number of padded values that should be padded to the left of the ith dimension
	OperationDescriptorPaddingRight            OperationdescriptorattributeT = 5  // uint32_t[] (of size descOut->numModes): Each entry i holds the number of padded values that should be padded to the right of the ith dimension
	OperationDescriptorPaddingValue            OperationdescriptorattributeT = 6  // host-side pointer to element of the same type as the output tensor: Constant padding value
	OperationDescriptorBlocksparseReproducible OperationdescriptorattributeT = 14 // int32_t: if non-zero, request bitwise-reproducible results from a block-sparse contraction at a performance cost. See cutensorCreateBlockSparseContraction for details. (default: 0)
)

func (OperationdescriptorattributeT) String

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

type OperatorT

type OperatorT int32

OperatorT captures all unary and binary element-wise operations supported by the cuTENSOR library.

const (
	OpIdentity OperatorT = 1   // Identity operator (i.e., elements are not changed)
	OpSqrt     OperatorT = 2   // Square root
	OpRelu     OperatorT = 8   // Rectified linear unit
	OpConj     OperatorT = 9   // Complex conjugate
	OpRcp      OperatorT = 10  // Reciprocal
	OpSigmoid  OperatorT = 11  // y=1/(1+exp(-x))
	OpTanh     OperatorT = 12  // y=tanh(x)
	OpExp      OperatorT = 22  // Exponentiation.
	OpLog      OperatorT = 23  // Log (base e).
	OpAbs      OperatorT = 24  // Absolute value.
	OpNeg      OperatorT = 25  // Negation.
	OpSin      OperatorT = 26  // Sine.
	OpCos      OperatorT = 27  // Cosine.
	OpTan      OperatorT = 28  // Tangent.
	OpSinh     OperatorT = 29  // Hyperbolic sine.
	OpCosh     OperatorT = 30  // Hyperbolic cosine.
	OpAsin     OperatorT = 31  // Inverse sine.
	OpAcos     OperatorT = 32  // Inverse cosine.
	OpAtan     OperatorT = 33  // Inverse tangent.
	OpAsinh    OperatorT = 34  // Inverse hyperbolic sine.
	OpAcosh    OperatorT = 35  // Inverse hyperbolic cosine.
	OpAtanh    OperatorT = 36  // Inverse hyperbolic tangent.
	OpCeil     OperatorT = 37  // Ceiling.
	OpFloor    OperatorT = 38  // Floor.
	OpMish     OperatorT = 39  // Mish y=x*tanh(softplus(x)).
	OpSwish    OperatorT = 40  // Swish y=x*sigmoid(x).
	OpSoftPlus OperatorT = 41  // Softplus y=log(exp(x)+1).
	OpSoftSign OperatorT = 42  // Softsign y=x/(abs(x)+1).
	OpAdd      OperatorT = 3   // Addition of two elements
	OpMul      OperatorT = 5   // Multiplication of two elements
	OpMax      OperatorT = 6   // Maximum of two elements
	OpMin      OperatorT = 7   // Minimum of two elements
	OpUnknown  OperatorT = 126 // reserved for internal use only
)

func (OperatorT) String

func (e OperatorT) String() string

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

type Plan

type Plan uintptr

Plan is an opaque handle for cutensorPlan_t.

func (Plan) Attribute

func (p Plan) Attribute(handle Handle, attr PlanattributeT, buf unsafe.Pointer, sizeInBytes uint) error

Attribute retrieves information about an already-created plan (see PlanattributeT)

Block-sparse contraction plans only support PlanRequiredWorkspace.

  • attr: Requested attribute
  • buf: On successful exit: Holds the information of the requested attribute
  • sizeInBytes: size of buf in bytes

Errors:

  • ErrInvalidValue: if some input data is invalid (this typically indicates an user error).

Wraps cutensorPlanGetAttribute.

func (*Plan) Close

func (p *Plan) Close() error

Close frees all resources related to the provided plan.

Remark: blocking, no reentrant, and thread-safe

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

Wraps cutensorDestroyPlan.

type PlanPreference

type PlanPreference uintptr

PlanPreference is an opaque handle for cutensorPlanPreference_t.

func (PlanPreference) Attribute

func (p PlanPreference) Attribute(handle Handle, attr PlanpreferenceattributeT, buf unsafe.Pointer, sizeInBytes uint) error

Attribute gets attribute of a PlanPreference object.

  • handle: Opaque handle holding cuTENSOR’s library context
  • attr: Requested attribute
  • buf: On successful exit: Holds the information of the requested attribute
  • sizeInBytes: Size of buf (in bytes); see PlanpreferenceattributeT for the exact size

Errors:

Wraps cutensorPlanPreferenceGetAttribute.

func (*PlanPreference) Close

func (p *PlanPreference) Close() error

Close frees all resources related to the provided preference.

Remark: blocking, no reentrant, and thread-safe

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

Wraps cutensorDestroyPlanPreference.

func (PlanPreference) SetAttribute

func (p PlanPreference) SetAttribute(handle Handle, attr PlanpreferenceattributeT, buf unsafe.Pointer, sizeInBytes uint) error

SetAttribute sets attribute of a PlanPreference object.

  • handle: Opaque handle holding cuTENSOR’s library context
  • attr: Specifies the attribute that will be set
  • buf: This buffer (of size sizeInBytes) determines the value to which attr will be set
  • sizeInBytes: Size of buf (in bytes); see PlanpreferenceattributeT for the exact size

Errors:

Wraps cutensorPlanPreferenceSetAttribute.

type PlanattributeT

type PlanattributeT int32

PlanattributeT lists all attributes of a Plan object that can be retrieved via Plan.Attribute.

const (
	PlanRequiredWorkspace PlanattributeT = 0 // uint64_t: exact required workspace in bytes that is needed to execute the plan
)

func (PlanattributeT) String

func (e PlanattributeT) String() string

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

type PlanpreferenceattributeT

type PlanpreferenceattributeT int32

PlanpreferenceattributeT lists all attributes of a PlanPreference object that can be modified.

const (
	PlanPreferenceAutotuneMode     PlanpreferenceattributeT = 0 // [AutotunemodeT]: Determines if recurrent executions of the plan (e.g., via [Handle.Contract], [Handle.Permute]) should autotune (i.e., try different kernels); see section "Plan Cache" for details.
	PlanPreferenceCacheMode        PlanpreferenceattributeT = 1 // [CachemodeT]: Determines if the corresponding algorithm/kernel for this plan should be cached and it gives fine control over what is considered a cachehit.
	PlanPreferenceIncrementalCount PlanpreferenceattributeT = 2 // int32_t: Only applicable if [PlanPreferenceCacheMode] is set to [AutotuneModeIncremental]
	PlanPreferenceAlgo             PlanpreferenceattributeT = 3 // [AlgoT]: Fixes a certain [AlgoT]
	PlanPreferenceKernelRank       PlanpreferenceattributeT = 4 // int32_t: Fixes a kernel (a sub variant of an algo; e.g., kernel_rank==1 while algo == [AlgoTgett] would select the second-best GETT kernel/variant according to cuTENSOR's performance model; kernel_rank==2 would select the third-best)
	PlanPreferenceJit              PlanpreferenceattributeT = 5 // [JitmodeT]: determines if just-in-time compilation is enabled or disabled (default: [JitModeNone])
	PlanPreferenceGpuArch          PlanpreferenceattributeT = 6 // int32_t: Plan for a specific GPU architecture and not one associated with the context. Value should encode SM version via `10 * SM.major + SM.minor`. Currently only SM versions 80, 90 and 100 are supported.
)

func (PlanpreferenceattributeT) String

func (e PlanpreferenceattributeT) String() string

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

type Result

type Result int32

Result represents a cutensor API error code (cutensorStatus_t).

When the library is loaded, Result.Error returns rich messages from GetErrorString. When the library is not loaded, it falls back to the numeric error code and Go-defined name.

const (
	Success                  Result = 0
	ErrNotInitialized        Result = 1
	ErrAllocFailed           Result = 3
	ErrInvalidValue          Result = 7
	ErrArchMismatch          Result = 8
	ErrMappingError          Result = 11
	ErrExecutionFailed       Result = 13
	ErrInternalError         Result = 14
	ErrNotSupported          Result = 15
	ErrLicenseError          Result = 16
	ErrCublasError           Result = 17
	ErrCudaError             Result = 18
	ErrInsufficientWorkspace Result = 19
	ErrInsufficientDriver    Result = 20
	ErrIoError               Result = 21
)

cutensor error codes from cutensor.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. When the library is loaded, it returns the error description from GetErrorString. Otherwise it returns a fallback string with the Go constant name and numeric code.

func (Result) String

func (r Result) String() string

String returns the Go constant name of the result.

type Scalar

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

A Scalar is a value, such as the alpha and beta of a matrix product, that the library reads through a pointer. Make one for a value in host memory with Float32Scalar, Float64Scalar, Complex64Scalar, Complex128Scalar, or Int32Scalar.

A call copies a host value into memory of its own, passes the library a pointer to the copy, and reuses that memory once the call returns, so a Scalar never reaches the library and can live anywhere.

The cuTENSOR documentation says a scalar is a "pointer to the host memory" and that operations can be captured into CUDA graphs, but not when a host scalar is read. The call assumes what cuBLAS documents for itself: that the library reads it before the call returns, and that capture into a CUDA graph keeps the value (cuBLAS documentation, sections 2.1.5 and 2.1.12).

The kind of a host Scalar must be the type the library reads. Where a call names that type in another parameter, a Scalar of another kind is a *ScalarError; where the type is in a descriptor, the call cannot check it. The zero Scalar is a host zero of every kind.

func Complex64Scalar

func Complex64Scalar(x complex64) Scalar

Complex64Scalar returns a host Scalar holding the complex64 x.

func Complex128Scalar

func Complex128Scalar(x complex128) Scalar

Complex128Scalar returns a host Scalar holding the complex128 x.

func Float32Scalar

func Float32Scalar(x float32) Scalar

Float32Scalar returns a host Scalar holding the float32 x.

func Float64Scalar

func Float64Scalar(x float64) Scalar

Float64Scalar returns a host Scalar holding the float64 x.

func Int32Scalar

func Int32Scalar(x int32) Scalar

Int32Scalar returns a host Scalar holding the int32 x.

type ScalarError

type ScalarError struct {
	Func  string // the C symbol called
	Param string // the scalar parameter
	Kind  string // the Scalar's kind, such as "float32"
	Want  string // the kinds the call allows, such as "float64 or complex128"
}

A ScalarError reports a host Scalar whose kind is not the type the call names for it in another parameter.

func (*ScalarError) Error

func (e *ScalarError) Error() string

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 TensorDescriptor

type TensorDescriptor uintptr

TensorDescriptor is an opaque handle for cutensorTensorDescriptor_t.

func (*TensorDescriptor) Close

func (t *TensorDescriptor) Close() error

Close frees all resources related to the provided tensor descriptor.

Remark: blocking, no reentrant, and thread-safe

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

Wraps cutensorDestroyTensorDescriptor.

type WorksizepreferenceT

type WorksizepreferenceT int32

WorksizepreferenceT gives users finer control over the suggested workspace.

This enum gives users finer control over the amount of workspace that is suggested by Handle.EstimateWorkspaceSize

const (
	WorkspaceMin     WorksizepreferenceT = 1 // Least memory requirement; at least one algorithm will be available
	WorkspaceDefault WorksizepreferenceT = 2 // Aims to attain high performance while also reducing the workspace requirement.
	WorkspaceMax     WorksizepreferenceT = 3 // Highest memory requirement; all algorithms will be available (choose this option if memory footprint is not a concern)
)

func (WorksizepreferenceT) String

func (e WorksizepreferenceT) String() string

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

Jump to

Keyboard shortcuts

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