tensor

package
v0.7.6 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: Apache-2.0 Imports: 1 Imported by: 0

Documentation

Overview

Package tensor provides type-safe tensor operations for the Born ML framework.

Overview

Tensors are the fundamental data structure in Born. This package provides:

  • Generic type-safe tensors (Tensor[T, B])
  • NumPy-style broadcasting
  • Zero-copy operations where possible
  • Device abstraction (CPU, CUDA)

Basic Usage

import (
    "github.com/born-ml/born/tensor"
    "github.com/born-ml/born/backend/cpu"
)

func main() {
    backend := cpu.New()

    // Create tensors
    x := tensor.Zeros[float32](tensor.Shape{2, 3}, backend)
    y := tensor.Ones[float32](tensor.Shape{2, 3}, backend)

    // Tensor operations
    z := x.Add(y)
    result := x.MatMul(y.Transpose())
}

Supported Data Types

The tensor package supports the following data types via the DType constraint:

  • float32, float64 (floating-point)
  • int32, int64 (signed integers)
  • uint8 (unsigned integers, useful for images)
  • bool (boolean masks)

Device Support

Tensors can reside on different devices:

  • CPU: Pure Go implementation (v0.1.0+)
  • WebGPU: Zero-CGO GPU acceleration (v0.2.0+, Windows)
  • CUDA: GPU support (planned for v0.5.0)

Broadcasting

Tensor operations follow NumPy broadcasting rules:

a := tensor.Zeros[float32](tensor.Shape{3, 1}, backend)     // (3, 1)
b := tensor.Ones[float32](tensor.Shape{3, 4}, backend)      // (3, 4)
c := a.Add(b)                                                // (3, 4)

Memory Management

Tensors use zero-copy operations where possible. The underlying data is reference-counted and automatically freed when no longer needed.

Available Operations (v0.3.0+)

Tensor[T, B] provides 31 type-safe operations:

Scalar operations:

y := x.MulScalar(2.0)    // Multiply by scalar
y := x.AddScalar(1.0)    // Add scalar
y := x.SubScalar(0.5)    // Subtract scalar
y := x.DivScalar(2.0)    // Divide by scalar

Math operations:

y := x.Exp()             // Exponential
y := x.Log()             // Natural logarithm
y := x.Sqrt()            // Square root
y := x.Rsqrt()           // Reciprocal square root
y := x.Cos()             // Cosine
y := x.Sin()             // Sine

Comparison operations (return Tensor[bool, B]):

mask := x.Greater(y)     // or x.Gt(y)
mask := x.Lower(y)       // or x.Lt(y)
mask := x.Equal(y)       // or x.Eq(y)

Type conversion:

i := x.Int32()           // Convert to int32
f := x.Float64()         // Convert to float64

See method documentation for full list of operations.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Backend

type Backend = tensor.Backend

Backend interface for device-specific operations. Implementations: cpu.Backend (current), cuda.Backend (planned).

type DType

type DType = tensor.DType

DType is a constraint for tensor data types. Supported types: float32, float64, int32, int64, uint8, bool.

type DataType

type DataType = tensor.DataType

DataType represents the underlying data type of a tensor.

const (
	Float32 DataType = tensor.Float32
	Float64 DataType = tensor.Float64
	Int32   DataType = tensor.Int32
	Int64   DataType = tensor.Int64
	Uint8   DataType = tensor.Uint8
	Bool    DataType = tensor.Bool
)

Data type constants.

type Device

type Device = tensor.Device

Device represents the device where tensor data resides.

const (
	CPU  Device = tensor.CPU
	CUDA Device = tensor.CUDA
)

Device constants.

type RawTensor

type RawTensor = tensor.RawTensor

RawTensor is the low-level tensor representation. Most users should use the high-level Tensor type instead.

func NewRaw

func NewRaw(shape Shape, dtype DataType, device Device) (*RawTensor, error)

NewRaw creates a new raw tensor with the given shape, dtype, and device.

This is a low-level function. Most users should use high-level creation functions instead.

type Shape

type Shape = tensor.Shape

Shape represents the dimensions of a tensor. Example: Shape{2, 3, 4} represents a 3D tensor with dimensions 2×3×4.

func BroadcastShapes

func BroadcastShapes(a, b Shape) (Shape, bool, error)

BroadcastShapes computes the broadcast shape for two shapes following NumPy broadcasting rules. Returns the resulting shape and two flags indicating if each operand needs broadcasting.

Example:

resultShape, needsBroadcastA, err := tensor.BroadcastShapes(
    tensor.Shape{3, 1},
    tensor.Shape{3, 4},
)
// resultShape = [3, 4], needsBroadcastA = true

type Tensor

type Tensor[T DType, B Backend] = tensor.Tensor[T, B]

Tensor is a generic type-safe tensor.

T is the data type (float32, float64, int32, int64, uint8, bool). B is the backend implementation (CPU, CUDA, etc.).

Example:

backend := cpu.New()
x := tensor.Zeros[float32](tensor.Shape{2, 3}, backend)

func Arange

func Arange[T DType, B Backend](start, end T, b B) *Tensor[T, B]

Arange creates a 1D tensor with values from start to end (exclusive).

Example:

backend := cpu.New()
x := tensor.Arange[float32](0, 10, backend)  // [0, 1, 2, ..., 9]

func Cat added in v0.3.0

func Cat[T DType, B Backend](tensors []*Tensor[T, B], dim int) *Tensor[T, B]

Cat concatenates tensors along a dimension.

Example:

backend := cpu.New()
a := tensor.Ones[float32](tensor.Shape{2, 3}, backend)
b := tensor.Zeros[float32](tensor.Shape{2, 3}, backend)
c := tensor.Cat([]*tensor.Tensor[float32, B]{a, b}, 0)  // Shape: [4, 3]

func Eye

func Eye[T DType, B Backend](n int, b B) *Tensor[T, B]

Eye creates a 2D identity matrix.

Example:

backend := cpu.New()
identity := tensor.Eye[float32](3, backend)  // 3x3 identity matrix

func FromSlice

func FromSlice[T DType, B Backend](data []T, shape Shape, b B) (*Tensor[T, B], error)

FromSlice creates a tensor from a Go slice.

Example:

backend := cpu.New()
data := []float32{1, 2, 3, 4, 5, 6}
x, err := tensor.FromSlice(data, tensor.Shape{2, 3}, backend)

func Full

func Full[T DType, B Backend](shape Shape, value T, b B) *Tensor[T, B]

Full creates a tensor filled with a specific value.

Example:

backend := cpu.New()
x := tensor.Full[float32](tensor.Shape{2, 3}, 3.14, backend)

func New

func New[T DType, B Backend](raw *RawTensor, b B) *Tensor[T, B]

New creates a tensor from a raw tensor.

This is a low-level function. Most users should use creation functions like Zeros, Ones, or FromSlice instead.

func Ones

func Ones[T DType, B Backend](shape Shape, b B) *Tensor[T, B]

Ones creates a tensor filled with ones.

Example:

backend := cpu.New()
x := tensor.Ones[float32](tensor.Shape{2, 3}, backend)

func Rand

func Rand[T DType, B Backend](shape Shape, b B) *Tensor[T, B]

Rand creates a tensor filled with random values from uniform distribution U(0, 1).

Example:

backend := cpu.New()
x := tensor.Rand[float32](tensor.Shape{2, 3}, backend)

func Randn

func Randn[T DType, B Backend](shape Shape, b B) *Tensor[T, B]

Randn creates a tensor filled with random values from standard normal distribution N(0, 1).

Example:

backend := cpu.New()
x := tensor.Randn[float32](tensor.Shape{2, 3}, backend)

func Where added in v0.3.0

func Where[T DType, B Backend](cond *Tensor[bool, B], x, y *Tensor[T, B]) *Tensor[T, B]

Where selects elements from x or y based on condition.

Example:

backend := cpu.New()
cond := tensor.Full[bool](tensor.Shape{3}, true, backend)
x := tensor.Full[float32](tensor.Shape{3}, 1.0, backend)
y := tensor.Full[float32](tensor.Shape{3}, 0.0, backend)
result := tensor.Where(cond, x, y)  // [1.0, 1.0, 1.0]

func Zeros

func Zeros[T DType, B Backend](shape Shape, b B) *Tensor[T, B]

Zeros creates a tensor filled with zeros.

Example:

backend := cpu.New()
x := tensor.Zeros[float32](tensor.Shape{2, 3}, backend)

Jump to

Keyboard shortcuts

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