Skip to Content
OchreML
Core & Containers

Tensor & Autograd

Hardware-accelerated n-dimensional Tensor with Rust reverse-mode autograd, f32/bf16/f16 dtypes, and no_grad context control.

ochreml.nn.Tensor is the foundational n-dimensional array type for ochreml.nn, backed 100% by Rust storage, reverse-mode autograd tape recording, and hardware dispatch across CPU, CUDA, wgpu, and TPU.

Import & Signatures

import ochreml.nn as nn

t = nn.Tensor(
    data,
    shape=None,
    dtype="float32",
    device=None,
    requires_grad=False,
)

Supported dtype constants exported from ochreml.nn:

  • nn.float32 ("float32", aliases "f32", "fp32")
  • nn.bfloat16 ("bfloat16", alias "bf16")
  • nn.float16 ("float16", aliases "f16", "fp16")

Factory Constructors

ConstructorSignatureDescription
Tensor.zeros(shape, dtype="float32", device=None, requires_grad=False)Zero-initialized tensor.
Tensor.ones(shape, dtype="float32", device=None, requires_grad=False)One-initialized tensor.
Tensor.randn(shape, mean=0.0, std=1.0, dtype="float32", device=None, seed=42, requires_grad=False)Normal distribution with deterministic seed.
Tensor.uniform(shape, low=-1.0, high=1.0, dtype="float32", device=None, seed=42, requires_grad=False)Uniform distribution in [low, high).

Properties & Methods

  • Properties: shape (tuple[int, ...]), ndim (int), numel (int), dtype (str), device (str), requires_grad (bool, writable), node_id (int | None), grad (Tensor | None).
  • Conversion & Device: numpy(), tolist(), item(), to(target) (dtype or device), to_dtype(dtype), to_device(device), detach().
  • Shape & Linear Algebra: reshape(*shape), transpose_last2(), matmul(other) / @.
  • Elementwise & Reductions: +, -, *, unary -, relu(), sigmoid(), tanh(), gelu(), silu(), sum(axis=None), mean(axis=None).
  • Autograd: backward(), zero_grad().

Autograd Control (no_grad, is_grad_enabled)

Use nn.no_grad() as a context manager or decorator during validation and inference to skip recording autograd tape nodes:

import ochreml.nn as nn

x = nn.Tensor.randn([4, 8], requires_grad=True)
w = nn.Tensor.randn([8, 4], requires_grad=True)

y = (x @ w).relu().mean()
y.backward()
print("x.grad shape:", x.grad.shape)  # (4, 8)
print("grad enabled:", nn.is_grad_enabled())  # True

with nn.no_grad():
    pred = (x @ w).relu()
    print("inside no_grad:", nn.is_grad_enabled())  # False

On this page