Documentation
¶
Overview ¶
Package cublaslt provides an owning cuBLASLt matrix multiplication engine.
NewEngine allocates a handle and a default 32 MiB workspace on a CUDA device. The workspace allocation can be customized or supplied by the caller using WithWorkspaceBytes or WithWorkspace.
Engine.MatMul, Engine.MatMulF16, and Engine.MatMulBF16 compute D = A*B for column-major matrices. Engine.MatMulRowMajor, Engine.MatMulRowMajorF16, and Engine.MatMulRowMajorBF16 compute D = A*B for row-major matrices. Engine.LinearRowMajor, Engine.LinearRowMajorF16, Engine.LinearRowMajorBF16, and Engine.LinearRowMajorF16ToF32 compute transformer linear projections Y = X*W^T for row-major matrices without transposition overhead. Engine.MatMulRaw allows full control over compute type, scale type, data types, transposed operands, and per-operation workspace override via MatMulConfig.
Callers that manage their own cuBLASLt descriptors can choose a kernel deterministically or empirically: Heuristic lists the heuristic's candidates, AlgoConfigOf reads a candidate's AlgoConfig, and Pick selects the first candidate a predicate accepts, or else the first. Version reports the loaded library version, against which such a predicate is usually tuned. MatmulPlan wraps a persistent descriptor and layouts, queries top-N candidates via MatmulPlan.HeuristicCandidates, and empirically times them on a CUDA stream via MatmulPlan.Tune.
An Engine serializes host submissions, but matrix multiplications do not wait for GPU completion. When using the default shared workspace across multiple streams, host submission alone does not order work on the device. To run concurrent operations on separate streams safely, use Engine.WithWorkspace to derive a child Engine with dedicated workspace per stream, or provide a stream-local MatMulConfig.Workspace on each invocation. A nil stream selects the CUDA default stream. Keep buffers alive until work completes and synchronize before reading results on the host or calling Engine.Close. A closed Engine cannot be reused.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
Example multiplies two small column-major float32 matrices on the device. It reports the error and returns when no CUDA device is present.
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/cuda/cublaslt"
)
func main() {
if err := cuda.Init(); err != nil {
fmt.Println("CUDA unavailable:", err)
return
}
devs, err := cuda.Devices()
if err != nil || len(devs) == 0 {
fmt.Println("no CUDA devices")
return
}
dev := devs[0]
eng, err := cublaslt.NewEngine(dev)
if err != nil {
fmt.Println("engine:", err)
return
}
defer eng.Close()
const m, k, n = 2, 2, 2
a, err := cuda.Alloc[float32](dev, m*k)
if err != nil {
fmt.Println("alloc:", err)
return
}
defer a.Close()
b, err := cuda.Alloc[float32](dev, k*n)
if err != nil {
fmt.Println("alloc:", err)
return
}
defer b.Close()
d, err := cuda.Alloc[float32](dev, m*n)
if err != nil {
fmt.Println("alloc:", err)
return
}
defer d.Close()
if err := a.CopyFromHost([]float32{1, 2, 3, 4}); err != nil {
fmt.Println("copy:", err)
return
}
if err := b.CopyFromHost([]float32{1, 0, 0, 1}); err != nil {
fmt.Println("copy:", err)
return
}
s := dev.DefaultStream()
if err := eng.MatMul(s, a, m, k, b, n, d); err != nil {
fmt.Println("matmul:", err)
return
}
if err := s.Synchronize(context.Background()); err != nil {
fmt.Println("sync:", err)
return
}
out := make([]float32, m*n)
if err := d.CopyToHost(out); err != nil {
fmt.Println("copy:", err)
return
}
fmt.Println(out)
}
Output:
Index ¶
- func Heuristic(h rawcublaslt.Handle, desc rawcublaslt.MatmulDesc, ...) ([]rawcublaslt.MatmulHeuristicResult, error)
- func Pick(cands []rawcublaslt.MatmulHeuristicResult, match func(AlgoConfig) bool) (int, error)
- func Version() (major, minor, patch int, err error)
- type AlgoConfig
- type Engine
- func (e *Engine) Close() error
- func (e *Engine) LinearRowMajor(s *cuda.Stream, x cuda.Slice[float32], tokens, inFeatures int, ...) error
- func (e *Engine) LinearRowMajorBF16(s *cuda.Stream, x cuda.Slice[uint16], tokens, inFeatures int, ...) error
- func (e *Engine) LinearRowMajorF16(s *cuda.Stream, x cuda.Slice[uint16], tokens, inFeatures int, ...) error
- func (e *Engine) LinearRowMajorF16ToF32(s *cuda.Stream, x cuda.Slice[uint16], tokens, inFeatures int, ...) error
- func (e *Engine) MatMul(s *cuda.Stream, a cuda.Slice[float32], m, k int, b cuda.Slice[float32], n int, ...) error
- func (e *Engine) MatMulBF16(s *cuda.Stream, a cuda.Slice[uint16], m, k int, b cuda.Slice[uint16], n int, ...) error
- func (e *Engine) MatMulF16(s *cuda.Stream, a cuda.Slice[uint16], m, k int, b cuda.Slice[uint16], n int, ...) error
- func (e *Engine) MatMulRaw(s *cuda.Stream, cfg MatMulConfig, aPtr driver.DevicePtr, aRows, aCols, lda int, ...) error
- func (e *Engine) MatMulRowMajor(s *cuda.Stream, a cuda.Slice[float32], m, k int, b cuda.Slice[float32], n int, ...) error
- func (e *Engine) MatMulRowMajorBF16(s *cuda.Stream, a cuda.Slice[uint16], m, k int, b cuda.Slice[uint16], n int, ...) error
- func (e *Engine) MatMulRowMajorF16(s *cuda.Stream, a cuda.Slice[uint16], m, k int, b cuda.Slice[uint16], n int, ...) error
- func (e *Engine) MatMulWithGELUBias(s *cuda.Stream, a cuda.Slice[float32], m, k int, b cuda.Slice[float32], n int, ...) error
- func (e *Engine) WithWorkspace(ws cuda.Slice[byte]) (*Engine, error)
- func (e *Engine) Workspace() cuda.Slice[byte]
- func (e *Engine) WorkspaceSize() uint
- type MatMulConfig
- type MatmulPlan
- func (p *MatmulPlan) Algo() (rawcublaslt.MatmulAlgo, uint)
- func (p *MatmulPlan) Candidates() []rawcublaslt.MatmulHeuristicResult
- func (p *MatmulPlan) HeuristicCandidates(maxAlgos int, workspaceSize uint64) ([]rawcublaslt.MatmulHeuristicResult, error)
- func (p *MatmulPlan) Run(stream *cuda.Stream, a, b, c, d, workspace driver.DevicePtr) error
- func (p *MatmulPlan) SelectAlgo(algo rawcublaslt.MatmulAlgo, workspace uint)
- func (p *MatmulPlan) SetReductionSchemeMask(mask rawcublaslt.ReductionScheme)
- func (p *MatmulPlan) SetScalars(alpha, beta rawcublaslt.Scalar)
- func (p *MatmulPlan) SetWorkspaceSize(bytes uint64)
- func (p *MatmulPlan) Tune(stream *cuda.Stream, a, b, c, d, workspace driver.DevicePtr, ...) (time.Duration, error)
- type Option
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Heuristic ¶
func Heuristic(h rawcublaslt.Handle, desc rawcublaslt.MatmulDesc, a, b, c, d rawcublaslt.MatrixLayout, pref rawcublaslt.MatmulPreference, n int) ([]rawcublaslt.MatmulHeuristicResult, error)
Heuristic returns up to n candidate algorithms for the product described by desc and the layouts of A, B, C and D, in the order cuBLASLt's heuristic ranks them, fastest estimate first. It returns an empty slice if the heuristic lists none.
Heuristic does not make a CUDA context current; the caller must, as for any call on h.
func Pick ¶
func Pick(cands []rawcublaslt.MatmulHeuristicResult, match func(AlgoConfig) bool) (int, error)
Pick returns the index of the first of cands whose configuration match accepts, or 0 if none does or match is nil. A candidate whose configuration cannot be read never matches. The result depends only on cands, so a product planned twice on the same device and library runs the same kernel. Pick returns an error if cands is empty.
Example ¶
package main
import (
"log"
rawcublaslt "github.com/tmc/lib/nvidia/cublaslt"
"github.com/tmc/lib/nvidia/x/cuda/cublaslt"
)
func main() {
var (
h rawcublaslt.Handle
desc rawcublaslt.MatmulDesc
a, b rawcublaslt.MatrixLayout
d rawcublaslt.MatrixLayout
pref rawcublaslt.MatmulPreference
)
cands, err := cublaslt.Heuristic(h, desc, a, b, d, d, pref, 8)
if err != nil {
log.Fatal(err)
}
i, err := cublaslt.Pick(cands, func(c cublaslt.AlgoConfig) bool {
return c.ID == 21 && c.Tile == rawcublaslt.MatmulTile128x128
})
if err != nil {
log.Fatal(err)
}
algo := cands[i].Algo
_ = algo // pass &algo to h.Matmul
}
Output:
Types ¶
type AlgoConfig ¶
type AlgoConfig struct {
ID int32
Tile rawcublaslt.MatmulTile
Stages rawcublaslt.MatmulStages
CustomOption int32
SplitK int32 // number of split-k slices; 0 or 1 means none
ReductionScheme rawcublaslt.ReductionScheme
}
AlgoConfig is the configuration of a cuBLASLt algorithm: the fields that decide which kernel a product runs.
Example ¶
package main
import (
"fmt"
rawcublaslt "github.com/tmc/lib/nvidia/cublaslt"
"github.com/tmc/lib/nvidia/x/cuda/cublaslt"
)
func main() {
// A rule preferring a CUTLASS 128x128x64 kernel.
want := cublaslt.AlgoConfig{ID: 21, Tile: rawcublaslt.MatmulTile128x128, Stages: rawcublaslt.MatmulStages64x3}
fmt.Println(want.ID, want.Tile, want.Stages)
}
Output: 21 MatmulTile128x128 MatmulStages64x3
func AlgoConfigOf ¶
func AlgoConfigOf(algo *rawcublaslt.MatmulAlgo) (AlgoConfig, error)
AlgoConfigOf returns the configuration of algo.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine manages cuBLASLt contexts, matrix layouts, workspace buffers, and execution heuristics.
func NewEngine ¶
NewEngine initializes a cuBLASLt engine. By default, it allocates a 32MB workspace buffer owned by the engine. Optional functional options can customize workspace size or provide a caller-owned buffer. A non-nil engine must be closed even when an error is returned. It may retain a created handle or workspace after a later allocation or context error.
func (*Engine) Close ¶
Close destroys the underlying cuBLASLt handle (unless shared) and frees any workspace memory owned by the engine.
func (*Engine) LinearRowMajor ¶
func (e *Engine) LinearRowMajor( s *cuda.Stream, x cuda.Slice[float32], tokens, inFeatures int, w cuda.Slice[float32], outFeatures int, y cuda.Slice[float32], ) error
LinearRowMajor computes Y = X * W^T for row-major float32 matrices: X has shape tokens by inFeatures, W has shape outFeatures by inFeatures, and Y has shape tokens by outFeatures.
func (*Engine) LinearRowMajorBF16 ¶
func (e *Engine) LinearRowMajorBF16( s *cuda.Stream, x cuda.Slice[uint16], tokens, inFeatures int, w cuda.Slice[uint16], outFeatures int, y cuda.Slice[uint16], ) error
LinearRowMajorBF16 computes Y = X * W^T for row-major bfloat16 matrices (encoded as uint16 bits) using float32 compute precision: X has shape tokens by inFeatures, W has shape outFeatures by inFeatures, and Y has shape tokens by outFeatures.
func (*Engine) LinearRowMajorF16 ¶
func (e *Engine) LinearRowMajorF16( s *cuda.Stream, x cuda.Slice[uint16], tokens, inFeatures int, w cuda.Slice[uint16], outFeatures int, y cuda.Slice[uint16], ) error
LinearRowMajorF16 computes Y = X * W^T for row-major float16 matrices (encoded as uint16 bits) using float32 compute precision: X has shape tokens by inFeatures, W has shape outFeatures by inFeatures, and Y has shape tokens by outFeatures.
func (*Engine) LinearRowMajorF16ToF32 ¶
func (e *Engine) LinearRowMajorF16ToF32( s *cuda.Stream, x cuda.Slice[uint16], tokens, inFeatures int, w cuda.Slice[uint16], outFeatures int, y cuda.Slice[float32], ) error
LinearRowMajorF16ToF32 computes Y = X * W^T where X and W are row-major float16 matrices (encoded as uint16 bits) and Y is a row-major float32 matrix.
func (*Engine) MatMul ¶
func (e *Engine) MatMul( s *cuda.Stream, a cuda.Slice[float32], m, k int, b cuda.Slice[float32], n int, d cuda.Slice[float32], ) error
MatMul computes D = A*B for column-major float32 matrices: A has shape m by k, B has shape k by n, and D has shape m by n.
func (*Engine) MatMulBF16 ¶
func (e *Engine) MatMulBF16( s *cuda.Stream, a cuda.Slice[uint16], m, k int, b cuda.Slice[uint16], n int, d cuda.Slice[uint16], ) error
MatMulBF16 computes D = A*B for column-major bfloat16 matrices (encoded as uint16 bits) using float32 compute precision: A has shape m by k, B has shape k by n, and D has shape m by n.
func (*Engine) MatMulF16 ¶
func (e *Engine) MatMulF16( s *cuda.Stream, a cuda.Slice[uint16], m, k int, b cuda.Slice[uint16], n int, d cuda.Slice[uint16], ) error
MatMulF16 computes D = A*B for column-major float16 matrices (encoded as uint16 bits) using float32 compute precision: A has shape m by k, B has shape k by n, and D has shape m by n.
func (*Engine) MatMulRaw ¶
func (e *Engine) MatMulRaw( s *cuda.Stream, cfg MatMulConfig, aPtr driver.DevicePtr, aRows, aCols, lda int, bPtr driver.DevicePtr, bRows, bCols, ldb int, dPtr driver.DevicePtr, dRows, dCols, ldd int, ) error
MatMulRaw computes D = alpha*op(A)*op(B) + beta*D using raw device pointers and strides.
func (*Engine) MatMulRowMajor ¶
func (e *Engine) MatMulRowMajor( s *cuda.Stream, a cuda.Slice[float32], m, k int, b cuda.Slice[float32], n int, d cuda.Slice[float32], ) error
MatMulRowMajor computes D = A*B for row-major float32 matrices: A has shape m by k, B has shape k by n, and D has shape m by n.
func (*Engine) MatMulRowMajorBF16 ¶
func (e *Engine) MatMulRowMajorBF16( s *cuda.Stream, a cuda.Slice[uint16], m, k int, b cuda.Slice[uint16], n int, d cuda.Slice[uint16], ) error
MatMulRowMajorBF16 computes D = A*B for row-major bfloat16 matrices (encoded as uint16 bits) using float32 compute precision: A has shape m by k, B has shape k by n, and D has shape m by n.
func (*Engine) MatMulRowMajorF16 ¶
func (e *Engine) MatMulRowMajorF16( s *cuda.Stream, a cuda.Slice[uint16], m, k int, b cuda.Slice[uint16], n int, d cuda.Slice[uint16], ) error
MatMulRowMajorF16 computes D = A*B for row-major float16 matrices (encoded as uint16 bits) using float32 compute precision: A has shape m by k, B has shape k by n, and D has shape m by n.
func (*Engine) MatMulWithGELUBias ¶
func (e *Engine) MatMulWithGELUBias( s *cuda.Stream, a cuda.Slice[float32], m, k int, b cuda.Slice[float32], n int, bias cuda.Slice[float32], d cuda.Slice[float32], ) error
MatMulWithGELUBias computes D = GELU(A*B+bias) for column-major float32 matrices. Bias contains one value for each row of D.
func (*Engine) WithWorkspace ¶
WithWorkspace returns a child Engine sharing the cuBLASLt handle and device of e, but using ws as its workspace. This enables per-stream or per-operation execution without workspace collision hazards across concurrent streams.
The returned child Engine does not own ws and does not own the cuBLASLt handle. Closing the child Engine does not destroy the parent handle or free ws. The parent Engine must remain open while the child Engine is in use.
func (*Engine) Workspace ¶
Workspace returns the default workspace buffer configured for the engine.
func (*Engine) WorkspaceSize ¶
WorkspaceSize returns the size in bytes of the engine's default workspace.
type MatMulConfig ¶
type MatMulConfig struct {
ComputeType rawcublaslt.ComputeType // e.g. Compute32F, Compute32FFast16F, Compute16F
ScaleType rawcublaslt.DataType // e.g. R32F, R16F
AType rawcublaslt.DataType // e.g. R32F, R16F, R16BF
BType rawcublaslt.DataType // e.g. R32F, R16F, R16BF
DType rawcublaslt.DataType // e.g. R32F, R16F, R16BF
TransA bool // transpose op(A) = A^T
TransB bool // transpose op(B) = B^T
Alpha float32 // scalar multiplier for A*B (defaults to 1.0 if Alpha and Beta are 0)
Beta float32 // scalar multiplier for D (defaults to 0.0)
Workspace cuda.Slice[byte] // Optional per-operation workspace override.
WorkspaceSize uint // Optional workspace size limit in bytes (defaults to Workspace.Len() if Workspace is set).
Epilogue rawcublaslt.Epilogue // postprocessing applied to D; zero means none
Bias driver.DevicePtr // bias vector, one value per row of D, required by the bias and bgrad epilogues
BiasType rawcublaslt.DataType // element type of Bias (defaults to DType)
Aux driver.DevicePtr // auxiliary buffer the EpilogueGeluAux and EpilogueReluAux families write or read
AuxLd int // leading dimension of Aux, in elements (defaults to the leading dimension of D)
}
MatMulConfig specifies options for raw matrix multiplication.
Example ¶
package main
import (
"fmt"
rawcublaslt "github.com/tmc/lib/nvidia/cublaslt"
"github.com/tmc/lib/nvidia/x/cuda/cublaslt"
)
func main() {
cfg := cublaslt.MatMulConfig{
ComputeType: rawcublaslt.Compute32F,
ScaleType: rawcublaslt.R32F,
AType: rawcublaslt.R16F,
BType: rawcublaslt.R16F,
DType: rawcublaslt.R16F,
TransA: true,
Alpha: 1.0,
Beta: 0.0,
}
fmt.Println("ComputeType:", cfg.ComputeType)
fmt.Println("TransA:", cfg.TransA)
fmt.Println("Alpha:", cfg.Alpha)
}
Output: ComputeType: 68 TransA: true Alpha: 1
Example (Workspace) ¶
package main
import (
"fmt"
rawcublaslt "github.com/tmc/lib/nvidia/cublaslt"
"github.com/tmc/lib/nvidia/x/cuda/cublaslt"
)
func main() {
cfg := cublaslt.MatMulConfig{
ComputeType: rawcublaslt.Compute32F,
ScaleType: rawcublaslt.R32F,
AType: rawcublaslt.R32F,
BType: rawcublaslt.R32F,
DType: rawcublaslt.R32F,
WorkspaceSize: 1024 * 1024,
}
fmt.Println("WorkspaceSize:", cfg.WorkspaceSize)
}
Output: WorkspaceSize: 1048576
type MatmulPlan ¶
type MatmulPlan struct {
// contains filtered or unexported fields
}
MatmulPlan holds a reusable cuBLASLt matrix multiplication descriptor, operand layouts, and selected algorithm for D = alpha*op(A)*op(B) + beta*C.
A MatmulPlan does not own its Handle, MatmulDesc, or MatrixLayouts; the caller remains responsible for closing them.
func NewMatmulPlan ¶
func NewMatmulPlan(h rawcublaslt.Handle, desc rawcublaslt.MatmulDesc, a, b, c, d rawcublaslt.MatrixLayout) (*MatmulPlan, error)
NewMatmulPlan creates a MatmulPlan for D = alpha*op(A)*op(B) + beta*C. By default alpha is 1 and beta is 0 (float32 scalars).
Example ¶
package main
import (
"fmt"
"log"
rawcublaslt "github.com/tmc/lib/nvidia/cublaslt"
"github.com/tmc/lib/nvidia/x/cuda/cublaslt"
)
func main() {
plan, err := cublaslt.NewMatmulPlan(1, 2, 3, 4, 5, 5)
if err != nil {
log.Fatal(err)
}
plan.SetWorkspaceSize(32 << 20)
plan.SetReductionSchemeMask(rawcublaslt.ReductionSchemeNone)
_, ws := plan.Algo()
fmt.Println("initial workspace:", ws)
}
Output: initial workspace: 0
func (*MatmulPlan) Algo ¶
func (p *MatmulPlan) Algo() (rawcublaslt.MatmulAlgo, uint)
Algo returns the currently selected algorithm and its required workspace size in bytes.
func (*MatmulPlan) Candidates ¶
func (p *MatmulPlan) Candidates() []rawcublaslt.MatmulHeuristicResult
Candidates returns a copy of the usable heuristic candidates from the most recent HeuristicCandidates or Tune call.
func (*MatmulPlan) HeuristicCandidates ¶
func (p *MatmulPlan) HeuristicCandidates(maxAlgos int, workspaceSize uint64) ([]rawcublaslt.MatmulHeuristicResult, error)
HeuristicCandidates queries up to maxAlgos candidate algorithms from cuBLASLt that fit within workspaceSize bytes and have status Success.
HeuristicCandidates does not make a CUDA context current; the caller must, as for any call on Handle.
func (*MatmulPlan) Run ¶
Run executes the planned matrix multiplication on stream using the currently selected algorithm.
func (*MatmulPlan) SelectAlgo ¶
func (p *MatmulPlan) SelectAlgo(algo rawcublaslt.MatmulAlgo, workspace uint)
SelectAlgo sets the active algorithm and workspace size in bytes for subsequent Run calls.
func (*MatmulPlan) SetReductionSchemeMask ¶
func (p *MatmulPlan) SetReductionSchemeMask(mask rawcublaslt.ReductionScheme)
SetReductionSchemeMask restricts the reduction schemes considered by HeuristicCandidates.
func (*MatmulPlan) SetScalars ¶
func (p *MatmulPlan) SetScalars(alpha, beta rawcublaslt.Scalar)
SetScalars sets the alpha and beta host scalars used by Run and Tune.
func (*MatmulPlan) SetWorkspaceSize ¶
func (p *MatmulPlan) SetWorkspaceSize(bytes uint64)
SetWorkspaceSize sets the default maximum workspace size in bytes used when HeuristicCandidates or Tune is called.
func (*MatmulPlan) Tune ¶
func (p *MatmulPlan) Tune(stream *cuda.Stream, a, b, c, d, workspace driver.DevicePtr, maxAlgos, warmup, reps int) (time.Duration, error)
Tune empirically benchmarks up to maxAlgos heuristic candidates on stream using warmup untimed launches followed by reps CUDA-event-timed launches per candidate. Tune selects the fastest candidate in p and returns its per-launch duration.
Tune does not make a CUDA context current; the caller must hold the device context for stream.
type Option ¶
type Option func(*engineConfig) error
Option configures an Engine.
func WithWorkspace ¶
WithWorkspace configures the engine to use a caller-provided workspace buffer. The engine does not free the provided workspace upon Close. The workspace must belong to the same device as the engine and its address must be 256-byte aligned.
func WithWorkspaceBytes ¶
WithWorkspaceBytes configures the size of the engine-owned workspace buffer in bytes. Setting bytes to 0 disables engine workspace allocation. Negative sizes return an error.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/cublaslt"
)
func main() {
opt := cublaslt.WithWorkspaceBytes(0)
fmt.Println("configured option:", opt != nil)
}
Output: configured option: true