shape

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: 6 Imported by: ? 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 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

Examples

Constants

View Source
const MaxByteLimit uint64 = 1 << 48

MaxByteLimit is the maximum addressable memory limit for device/host allocations (256 TiB, 48-bit address space).

Variables

View Source
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")
)
View Source
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")
)
View Source
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

func ByteStrides(elementSizeBytes int, strides []int) ([]int64, error)

ByteStrides converts element strides to byte strides.

func ColumnMajorStrides

func ColumnMajorStrides(dims []int) ([]int, error)

ColumnMajorStrides computes standard column-major strides for the given extents.

func IsContiguousColumnMajor

func IsContiguousColumnMajor(dims, strides []int) bool

IsContiguousColumnMajor checks if the given strides match contiguous column-major order for dims.

func IsContiguousRowMajor

func IsContiguousRowMajor(dims, strides []int) bool

IsContiguousRowMajor checks if the given strides match contiguous row-major order for dims.

func RowMajorStrides

func RowMajorStrides(dims []int) ([]int, error)

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

func SafeMul(a, b uint64) (uint64, bool)

SafeMul multiplies two uint64 values, returning the product and whether overflow occurred.

func ValidateStrides

func ValidateStrides(dims, strides []int) error

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 ConstDim

func ConstDim(v int) Dim

ConstDim constructs a fixed concrete dimension extent.

func NamedDim

func NamedDim(name string) (Dim, error)

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

func (Dim) IsSymbol

func (d Dim) IsSymbol() bool

IsSymbol reports whether the dimension is symbolic.

func (Dim) Name

func (d Dim) Name() string

Name returns the symbol name, or empty string if constant.

func (Dim) String

func (d Dim) String() string

String returns a human-readable representation.

func (Dim) Value

func (d Dim) Value() int

Value returns the constant extent value if not symbolic.

type DimToken

type DimToken string

DimToken is one normalized einsum rank, such as "A", "B12", or "(P+R)".

func ParseDimTokens

func ParseDimTokens(dims string, validate bool) ([]DimToken, error)

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

func ParseEinsumEquation(eq string) (inputs [][]DimToken, output []DimToken, err error)

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

func (t DimToken) Validate() error

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.

func (*Environment) Value

func (e *Environment) Value(name string) (int, bool)

Value looks up the concrete extent bound to name.

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

func InferGrid(tensorShape, partitionShape Shape) (Grid3D, error)

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>

func (Grid3D) Dims

func (g Grid3D) Dims() [3]uint32

Dims returns the grid dimensions as an array of 3 uint32s.

func (Grid3D) Equal

func (g Grid3D) Equal(other Grid3D) bool

Equal reports whether two launch grids have identical extents.

func (Grid3D) IsZero

func (g Grid3D) IsZero() bool

IsZero reports whether all grid dimensions are zero.

func (Grid3D) String

func (g Grid3D) String() string

String returns a human-readable representation of Grid3D.

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

func LayoutFromStrides(dims, strides []int) Layout

LayoutFromStrides identifies the Layout variant for the given dims and strides.

func (Layout) String

func (l Layout) String() string

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

func New(dims ...int) (Shape, error)

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) Dim

func (s Shape) Dim(i int) int

Dim returns the extent at axis i. If i is out of bounds, it returns 0.

func (Shape) Dims

func (s Shape) Dims() []int

Dims returns a copy of the shape extents.

func (Shape) Equal

func (s Shape) Equal(other Shape) bool

Equal reports whether two shapes have identical extents.

func (Shape) NumElements

func (s Shape) NumElements() (int64, error)

NumElements returns total elements as an int64. Returns ErrShapeOverflow if the element count overflows int64 or MaxByteLimit.

func (Shape) NumElementsSafe

func (s Shape) NumElementsSafe() (uint64, error)

NumElementsSafe returns total elements as uint64 with overflow checking.

func (Shape) Rank

func (s Shape) Rank() int

Rank returns the number of dimensions.

func (Shape) SizeBytes

func (s Shape) SizeBytes(elementSizeBytes int) (uint64, error)

SizeBytes returns the total memory in bytes needed for the shape given an element size in bytes. Returns ErrShapeOverflow if the size exceeds MaxByteLimit or overflows uint64.

func (Shape) String

func (s Shape) String() string

String returns a human-readable representation, e.g. "[2, 3, 4]".

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]".

Directories

Path Synopsis
Package rope computes rotary position embedding inverse frequencies the way Hugging Face transformers does.
Package rope computes rotary position embedding inverse frequencies the way Hugging Face transformers does.

Jump to

Keyboard shortcuts

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