Tensors, Dtypes, and RNG
Reference for jacobi::Tensor, Dtype, Precision, einsum, and jacobi::rng.
Dtypes (Dtype)
| Variant |
StableHLO Type |
Bytes |
Notes |
Dtype::F32 |
f32 |
4 |
Default floating-point dtype |
Dtype::F64 |
f64 |
8 |
Double-precision float |
Dtype::BF16 |
bf16 |
2 |
Brain float16 for mixed precision |
Dtype::F16 |
f16 |
2 |
IEEE half precision |
Dtype::F8E4M3FN |
f8E4M3FN |
1 |
FP8 weights and activations (max 448.0) |
Dtype::F8E5M2 |
f8E5M2 |
1 |
FP8 gradients (max 57344.0) |
Dtype::F4E2M1FN |
f4E2M1FN |
1 (packed 4-bit) |
NVFP4 (max 6.0) |
Dtype::I1 |
i1 |
1 |
Boolean predicate tensor |
Dtype::I8 / Dtype::I16 / Dtype::I32 / Dtype::I64 |
i8..i64 |
1..8 |
Signed integers (I16 for PCM audio, I8 for quantized matmul) |
Dtype::U8 / Dtype::U32 |
ui8 / ui32 |
1 / 4 |
Unsigned integers (U8 for images, U32 for RNG state) |
Helper methods on Dtype include is_float(), is_low_precision(), is_fp8_or_fp4(), byte_size(), and max_finite().
Precision Control (Precision)
Control XLA dot and convolution rounding modes globally or per block.
pub enum Precision {
Default,
High,
Highest,
}
with_precision(Precision::Highest, || a.matmul(&b)) forces exact IEEE f32 (disabling TF32 on NVIDIA Ampere/Hopper/Blackwell) across both forward and backward passes.
set_default_precision(Precision::Highest) updates the process-wide default.
with_autocast(Dtype::BF16, || ...) casts f32 matmul, einsum, and convolution operands to BF16/F16 with f32 accumulation.
Creating Tensors (Tensor)
| Constructor |
Signature |
Description |
| Typed slices |
Tensor::from_f32(&[f32], &[usize]), from_f64, from_i8, from_i16, from_i32, from_i64, from_u8, from_bool, from_f16(&[u16], &[usize]) -> Result<Tensor>, from_bf16(&[u16], &[usize]) -> Result<Tensor> |
Upload host slice with static shape |
| Direct-to-device |
Tensor::from_host_on(&HostTensor, dev), from_raw_bytes_on(&[u8], &[usize], Dtype, dev), from_{f32,f64,f16,bf16,i8,i16,i32,i64,u8,u32,bool}_on(..., dev) -> Result<Tensor> |
Upload directly to target device_idx without bouncing through device 0 |
| Host / raw bytes |
Tensor::from_host(&HostTensor), Tensor::from_raw_bytes(&[u8], &[usize], Dtype) -> Result<Tensor> |
Zero-copy or raw byte buffer upload |
| AOT placeholder |
Tensor::spec(&[usize], Dtype) |
Zero-allocation shape/dtype placeholder for compile_for |
| Scalars |
Tensor::scalar(f64), scalar_f32, scalar_f64, scalar_i32, scalar_i64, constant(f64, Dtype) |
Rank-0 scalar tensor |
| Fills |
Tensor::zeros(&[usize]), ones, full(&[usize], f64, Dtype) |
Filled constant tensors |
| Like-fills |
t.zeros_like(), t.ones_like(), t.full_like(f64) |
Constant tensor matching t.shape() and t.dtype() |
| Ranges and grids |
Tensor::arange(start, stop, step), Tensor::linspace(start, stop, steps), Tensor::eye(n), Tensor::meshgrid(&x, &y) |
Structured numeric tensors |
| Method |
Signature |
Description |
| Metadata |
t.shape() -> Vec<usize>, t.ndim() -> usize, t.numel() -> usize, t.dtype() -> Dtype |
Static tensor metadata |
| Execution & errors |
t.check() -> Result<()>, t.eval() -> Result<()>, sync() |
Flush lazy graph or surface deferred errors |
| Autodiff stop |
t.detach() -> Tensor |
Block gradient flow (stop_gradient) |
| Device placement |
t.device_index() -> Result<usize>, t.to_device(idx: usize) -> Result<Tensor> |
Query or transfer device residence |
| Host readback |
t.item() -> Result<f32>, item_f64, item_i32, item_i64, item_bool, to_vec_f32, to_vec_f64, to_vec_i32, to_vec_i64, to_host() -> Result<HostTensor>, to_raw_bytes() -> Result<Vec<u8>> |
Synchronize and copy to host |
| Casting |
t.cast(Dtype) / t.to_dtype(Dtype), to_f32, to_f64, to_bf16, to_f16, to_fp8_e4m3, to_fp8_e5m2, to_fp4, to_i8, to_i16, to_i32, to_i64, to_u8, to_u32 |
Elementwise dtype conversion |
Elementwise Math, Comparisons, and Reductions
- Binary & scalar operators Standard Rust
+, -, *, / work on &Tensor and f64 scalars (&x * 2.0 + 1.0). Named methods include add, sub, mul, div, pow(&Tensor), powf(f64), atan2(&Tensor), logaddexp(&Tensor), maximum(&Tensor), minimum(&Tensor), max_scalar(f64), min_scalar(f64), clamp(lo, hi), and modulo(&Tensor).
- Unary & activations
neg, abs, exp, expm1, log, log2, log10, log1p, erf, sqrt, rsqrt, sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, sigmoid, log_sigmoid, relu, leaky_relu(slope), elu(alpha), softplus, mish, gelu, gelu_exact, silu, floor, ceil, round, sign.
- Comparisons & selection
eq_tensor, ne_tensor, lt, le, gt, ge, eq_scalar, ne_scalar, lt_scalar, le_scalar, gt_scalar, ge_scalar, allclose(&other, rtol, atol) -> Result<bool>, Tensor::where_select(&cond, &on_true, &on_false), cond.where_scalars(on_true, on_false), t.masked_fill(&mask, value), logical_and, logical_or, logical_xor, logical_not, is_nan, is_inf, is_finite.
- Reductions
sum, sum_axis(ax), sum_axes(&[ax]), mean, mean_axis, mean_axes, max, max_axis, min, min_axis, prod, prod_axis, prod_axes, all, all_axis, any, any_axis, var, var_axis, std, std_axis, norm, norm_axis, logsumexp, logsumexp_axis, softmax, softmax_axis, log_softmax, log_softmax_axis.
Linear Algebra, Einsum, and FFT
| Function / Method |
Signature |
Description |
| Matrix multiplication |
a.matmul(&b), a.matmul_in(&b, out_dtype: Dtype) |
Batched matmul with optional explicit output/accumulator dtype |
| Einstein summation |
einsum(spec: &str, operands: &[&Tensor]), einsum_in(spec, operands, out_dtype) |
Arbitrary tensor contractions (also Tensor::einsum, Tensor::einsum_in) |
| Products |
a.dot(&b), a.outer(&b), a.cross(&b), a.kron(&b), a.trace() |
Vector and Kronecker products |
| Factorizations & solves |
cholesky(), triangular_solve(&b, lower, transpose_a), cholesky_solve(&b), solve(&b), inv(), pinv(), qr() -> (q, r), det(), eigh() -> (w, v), svd() -> (u, s, vt), matrix_rank() -> Result<usize> |
Differentiable linear algebra primitives |
| Spectral transforms |
x.rfft() -> (re, im), Tensor::irfft(&re, &im, n), Tensor::fft(&re, &im) -> (re, im), Tensor::ifft(&re, &im) -> (re, im) |
Differentiable 1D real and complex FFTs |
Shapes, Indexing, Sorting, and Vision Ops
- Shape transforms
reshape(&[usize]), flatten(), unsqueeze(ax), squeeze(ax), broadcast_to(&[usize]), transpose(), permute(&[usize]), reverse(&[usize]), triu(diag), tril(diag), diag(), chunk(n, ax), split(&[usize], ax), repeat(&[usize]), repeat_interleave(repeats, ax), roll(shift, ax), pad(&[(lo, hi)], pad_value), Tensor::concat(&[&Tensor], axis), Tensor::stack(&[&Tensor], axis).
- Slicing, gather, and scatter
slice_axis(axis, start, end), index(idx: isize), dynamic_slice(&start, size), dynamic_update_slice(&update, &[&start]), dynamic_update_slice_axis(&update, axis, &start), take(&indices), take_axis(&indices, axis), gather(axis, &indices), scatter_add(axis, &indices, &updates), scatter_set(axis, &indices, &updates), segment_sum(&segment_ids, num_segments).
- Sorting, selection, and scans
sort, sort_axis, argsort, argsort_axis, argsort_stable, argsort_stable_axis (all backed by StableHLO is_stable = true), top_k(k) -> (values, indices), top_k_axis(k, axis), argmax, argmax_axis, argmin, argmin_axis, searchsorted(&values, right), unique(size, fill_value), one_hot(depth), bincount(bins), cumsum, cumsum_axis, cumprod, cumprod_axis, cumlogsumexp, cumlogsumexp_axis.
- Convolutions and image ops
conv1d, conv1d_grouped, conv_transpose1d, conv2d, conv2d_grouped, conv_transpose2d, conv3d, conv3d_grouped, max_pool1d, avg_pool1d, max_pool2d, avg_pool2d, adaptive_avg_pool2d(h, w), upsample_nearest(h, w), resize_bilinear(h, w), crop(top, left, h, w).
Implicit Device RNG (jacobi::rng)
- Seeding
manual_seed(seed: u64) (alias set_seed(seed: u64)).
- Distributions
Tensor::rand(shape) / rand(shape), Tensor::rand_uniform(shape, lo, hi) / rand_uniform, Tensor::randn(shape) / randn, Tensor::randint(low, high, shape) / randint, Tensor::randperm(n) / randperm, bernoulli(p, shape), truncated_normal(shape, lo, hi), kaiming_normal(shape), kaiming_uniform(shape).
- Sampling
logits.sample(), logits.sample_temperature(temp), logits.sample_top_k(k, temp), logits.sample_top_p(p, temp) (also sample_top_k, sample_top_p).