Documentation
¶
Overview ¶
Package cudashape provides checked multi-dimensional tensor shapes, overflow-checked byte size calculation, stride and layout analysis, and bounded symbolic dimension binding with equality and divisibility constraints.
Extent and Overflow Validation ¶
Concrete shapes are validated upon creation using New. Element counts and byte sizes are computed using overflow-checked arithmetic against host and device addressable memory limits (MaxByteLimit).
Symbolic Shapes and Constraints ¶
Dimensions may be symbolic (NamedDim) or constant (ConstDim). An Environment holds concrete bindings and constraints (EqualSymbols, EqualConst, DivisibleBy, RangeBound). Bounded symbolic binding via SymbolicShape.Bind returns explicit errors on unbound symbols, contradictory bindings, or constraint violations. ParseDimTokens parses the dimension labels used in einsum equations.
Layouts and Strides ¶
Tensor layouts (LayoutRowMajor, LayoutColumnMajor, LayoutStrided) and their corresponding strides are computed and validated with overflow safety.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Launch Grid Inference ¶
Launch grid extents (Grid3D) are computed from tensor and tile shapes via InferGrid, applying overflow-checked ceiling division across ranks 1 to 3.
Index ¶
- Constants
- Variables
- func ByteStrides(elementSizeBytes int, strides []int) ([]int64, error)
- func ColumnMajorStrides(dims []int) ([]int, error)
- func IsContiguousColumnMajor(dims, strides []int) bool
- func IsContiguousRowMajor(dims, strides []int) bool
- func RowMajorStrides(dims []int) ([]int, error)
- func SafeMul(a, b uint64) (uint64, bool)
- func ValidateStrides(dims, strides []int) error
- type Constraint
- type Dim
- type DimToken
- type Environment
- type Grid3D
- type Layout
- type Shape
- func (s Shape) Dim(i int) int
- func (s Shape) Dims() []int
- func (s Shape) Equal(other Shape) bool
- func (s Shape) NumElements() (int64, error)
- func (s Shape) NumElementsSafe() (uint64, error)
- func (s Shape) Rank() int
- func (s Shape) SizeBytes(elementSizeBytes int) (uint64, error)
- func (s Shape) String() string
- type SymbolicShape
Examples ¶
Constants ¶
const MaxByteLimit uint64 = 1 << 48
MaxByteLimit is the maximum addressable memory limit for device/host allocations (256 TiB, 48-bit address space).
Variables ¶
var ( // ErrRepeatedRank reports a dimension rank repeated within one tensor. ErrRepeatedRank = errors.New("cudashape: repeated einsum rank") // ErrMultiLetterPrefix reports a token whose prefix has more than one letter. ErrMultiLetterPrefix = errors.New("cudashape: einsum rank prefix must be one letter") // ErrUnbalancedGroup reports unmatched parentheses in a dimension string. ErrUnbalancedGroup = errors.New("cudashape: unbalanced einsum rank group") // ErrInvalidEquation reports a malformed einsum equation. ErrInvalidEquation = errors.New("cudashape: invalid einsum equation") )
var ( // ErrNegativeDimension is returned when a shape dimension is negative. ErrNegativeDimension = errors.New("cudashape: negative dimension") // ErrShapeOverflow is returned when total elements or byte count overflows uint64 or memory limit. ErrShapeOverflow = errors.New("cudashape: shape byte count overflow") // ErrInvalidStride is returned when a stride configuration is incompatible with dimensions. ErrInvalidStride = errors.New("cudashape: invalid stride") // ErrRankMismatch is returned when operations require matching ranks but find differences. ErrRankMismatch = errors.New("cudashape: rank mismatch") )
var ( // ErrUnboundSymbol indicates that a symbolic dimension is missing a concrete binding. ErrUnboundSymbol = errors.New("cudashape: unbound symbol") // ErrContradictoryBinding indicates an attempt to bind a symbol to conflicting values. ErrContradictoryBinding = errors.New("cudashape: contradictory symbol binding") // ErrConstraintViolation indicates that dimension bindings violate an explicit constraint. ErrConstraintViolation = errors.New("cudashape: constraint violation") )
Functions ¶
func ByteStrides ¶
ByteStrides converts element strides to byte strides.
func ColumnMajorStrides ¶
ColumnMajorStrides computes standard column-major strides for the given extents.
func IsContiguousColumnMajor ¶
IsContiguousColumnMajor checks if the given strides match contiguous column-major order for dims.
func IsContiguousRowMajor ¶
IsContiguousRowMajor checks if the given strides match contiguous row-major order for dims.
func RowMajorStrides ¶
RowMajorStrides computes standard contiguous row-major strides for the given extents.
Example ¶
package main
import (
"fmt"
cudashape "github.com/tmc/lib/nvidia/x/host/shape"
)
func main() {
strides, err := cudashape.RowMajorStrides([]int{2, 3, 4})
if err != nil {
panic(err)
}
fmt.Printf("strides: %v\n", strides)
}
Output: strides: [12 4 1]
func SafeMul ¶
SafeMul multiplies two uint64 values, returning the product and whether overflow occurred.
func ValidateStrides ¶
ValidateStrides verifies that strides match the dimensions rank and have valid values.
Types ¶
type Constraint ¶
type Constraint interface {
Check(env *Environment) error
String() string
}
Constraint defines an invariant over symbolic bindings.
func DivisibleBy ¶
func DivisibleBy(sym string, divisor int) Constraint
DivisibleBy requires a named symbol to be evenly divisible by divisor.
func EqualConst ¶
func EqualConst(sym string, val int) Constraint
EqualConst requires a named symbol to equal a specified integer constant.
func EqualSymbols ¶
func EqualSymbols(symA, symB string) Constraint
EqualSymbols requires two named symbols to have identical values when bound.
func RangeBound ¶
func RangeBound(sym string, minVal, maxVal int) Constraint
RangeBound requires a named symbol's value to lie within [minVal, maxVal].
type Dim ¶
type Dim struct {
// contains filtered or unexported fields
}
Dim represents a dimension that is either a fixed constant extent or a named symbol.
func NamedDim ¶
NamedDim constructs a symbolic dimension with the given identifier. It returns an error if name is empty.
Example ¶
package main
import (
"fmt"
cudashape "github.com/tmc/lib/nvidia/x/host/shape"
)
func main() {
dim, err := cudashape.NamedDim("batch")
fmt.Println(dim.Name(), dim.IsSymbol(), err)
_, err = cudashape.NamedDim("")
fmt.Println(err)
}
Output: batch true <nil> cudashape: empty symbol name
type DimToken ¶
type DimToken string
DimToken is one normalized einsum rank, such as "A", "B12", or "(P+R)".
func ParseDimTokens ¶
ParseDimTokens parses a SOLAR-style einsum dimension string. Each rank is one letter with an optional integer suffix, or a balanced parenthesized group. Tokens are uppercased. Non-letter characters outside groups are skipped. When validate is true, repeated normalized tokens are rejected.
Example ¶
package main
import (
"fmt"
cudashape "github.com/tmc/lib/nvidia/x/host/shape"
)
func main() {
tokens, err := cudashape.ParseDimTokens("a12BC", true)
if err != nil {
panic(err)
}
fmt.Println(tokens)
}
Output: [A12 B C]
func ParseEinsumEquation ¶
ParseEinsumEquation splits an equation into per-operand and output ranks. Repetition is checked independently within each tensor; a shared rank across operands is the normal signal for contraction.
func (DimToken) Validate ¶
Validate reports whether t has the grammar accepted by ParseDimTokens. A rank prefix is one letter; parenthesized groups must be balanced.
type Environment ¶
type Environment struct {
// contains filtered or unexported fields
}
Environment manages dimension bindings and verifies registered constraints.
func NewEnvironment ¶
func NewEnvironment() *Environment
NewEnvironment creates an empty symbolic binding environment.
func (*Environment) AddConstraint ¶
func (e *Environment) AddConstraint(c Constraint) error
AddConstraint registers a constraint and checks it against current bindings. Returns ErrConstraintViolation if existing bindings violate the constraint.
func (*Environment) Bind ¶
func (e *Environment) Bind(name string, val int) error
Bind assigns a concrete extent value to a named symbol. If the symbol is already bound to a different value, ErrContradictoryBinding is returned. If the binding violates any registered constraint, ErrConstraintViolation is returned and the environment remains unmodified.
func (*Environment) Bindings ¶
func (e *Environment) Bindings() map[string]int
Bindings returns a copy of all current bindings.
type Grid3D ¶
type Grid3D struct {
X, Y, Z uint32
}
Grid3D represents a 3-dimensional launch grid extent (in blocks).
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/shape"
)
func main() {
grid := shape.Grid3D{X: 8, Y: 3, Z: 1}
fmt.Println(grid.Dims(), grid.Equal(shape.Grid3D{X: 8, Y: 3, Z: 1}), grid.IsZero())
}
Output: [8 3 1] true false
func InferGrid ¶
InferGrid calculates the multi-dimensional launch grid dimensions needed to cover tensorShape using tiles of partitionShape.
It performs ceiling division along each dimension:
grid[i] = ceil(tensorShape[i] / partitionShape[i])
For rank-1 shapes, Y and Z are set to 1. For rank-2 shapes, Z is set to 1. Returns ErrRankMismatch if the ranks differ or are not in the range [1, 3]. Returns ErrNegativeDimension if any extent is non-positive. Returns ErrShapeOverflow if a grid dimension exceeds CUDA's limits: X is at most 2^31-1, and Y and Z are at most 65535.
Example ¶
package main
import (
"fmt"
cudashape "github.com/tmc/lib/nvidia/x/host/shape"
)
func main() {
tensor, err := cudashape.New(1024, 2048)
if err != nil {
panic(err)
}
tile, err := cudashape.New(64, 128)
if err != nil {
panic(err)
}
grid, err := cudashape.InferGrid(tensor, tile)
if err != nil {
panic(err)
}
fmt.Printf("grid: %s\n", grid)
}
Output: grid: (16, 16, 1)
Example (Tiled) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/shape"
)
func main() {
tensor, _ := shape.New(1000, 96)
tile, _ := shape.New(128, 32)
grid, err := shape.InferGrid(tensor, tile)
fmt.Println(grid, err)
}
Output: (8, 3, 1) <nil>
type Layout ¶
type Layout int
Layout describes the memory layout order of tensor elements.
const ( // LayoutRowMajor denotes standard C contiguous order (last dimension has stride 1). LayoutRowMajor Layout = iota // LayoutColumnMajor denotes Fortran contiguous order (first dimension has stride 1). LayoutColumnMajor // LayoutStrided denotes an arbitrary or sliced strided layout. LayoutStrided )
func LayoutFromStrides ¶
LayoutFromStrides identifies the Layout variant for the given dims and strides.
type Shape ¶
type Shape struct {
// contains filtered or unexported fields
}
Shape represents concrete multi-dimensional tensor extents. The zero value of Shape represents a 0-dimensional scalar (rank 0, 1 element).
func New ¶
New creates a new checked Shape. It returns ErrNegativeDimension if any extent is negative, or ErrShapeOverflow if the total element count overflows uint64 or exceeds MaxByteLimit.
Example ¶
package main
import (
"fmt"
cudashape "github.com/tmc/lib/nvidia/x/host/shape"
)
func main() {
s, err := cudashape.New(2, 3, 4)
if err != nil {
panic(err)
}
n, _ := s.NumElements()
bytes, _ := s.SizeBytes(4) // float32 elements
fmt.Printf("shape: %s, elements: %d, bytes: %d\n", s, n, bytes)
}
Output: shape: [2, 3, 4], elements: 24, bytes: 96
func (Shape) NumElements ¶
NumElements returns total elements as an int64. Returns ErrShapeOverflow if the element count overflows int64 or MaxByteLimit.
func (Shape) NumElementsSafe ¶
NumElementsSafe returns total elements as uint64 with overflow checking.
type SymbolicShape ¶
type SymbolicShape struct {
// contains filtered or unexported fields
}
SymbolicShape represents a tensor shape with named symbols and/or constant extents.
func NewSymbolicShape ¶
func NewSymbolicShape(dims ...Dim) SymbolicShape
NewSymbolicShape creates a new SymbolicShape from dimensions.
func (SymbolicShape) Bind ¶
func (ss SymbolicShape) Bind(env *Environment) (Shape, error)
Bind evaluates the SymbolicShape against the environment, producing a concrete Shape. Returns ErrUnboundSymbol if any named dimension lacks a binding. Returns ErrConstraintViolation if any constraint is not satisfied.
Example ¶
package main
import (
"fmt"
cudashape "github.com/tmc/lib/nvidia/x/host/shape"
)
func main() {
env := cudashape.NewEnvironment()
_ = env.AddConstraint(cudashape.DivisibleBy("hidden", 64))
_ = env.Bind("batch", 4)
_ = env.Bind("seq", 128)
_ = env.Bind("hidden", 256)
batch, err := cudashape.NamedDim("batch")
if err != nil {
fmt.Println(err)
return
}
seq, err := cudashape.NamedDim("seq")
if err != nil {
fmt.Println(err)
return
}
hidden, err := cudashape.NamedDim("hidden")
if err != nil {
fmt.Println(err)
return
}
symShape := cudashape.NewSymbolicShape(batch, seq, hidden)
shape, err := symShape.Bind(env)
if err != nil {
panic(err)
}
fmt.Println(shape)
}
Output: [4, 128, 256]
func (SymbolicShape) Dims ¶
func (ss SymbolicShape) Dims() []Dim
Dims returns a copy of the symbolic dimensions.
func (SymbolicShape) Rank ¶
func (ss SymbolicShape) Rank() int
Rank returns the number of dimensions.
func (SymbolicShape) String ¶
func (ss SymbolicShape) String() string
String returns a string representation such as "[B, S, 128]".