// DOCS NAVIGATION
std.tensor — Tensores_
SOURCE: content/docs/reference/05-stdlib.md — 05 Stdlib / 6. std.tensor — Tensores / Tensors
PT-BR:
std.tensor fornece o núcleo de produção atual de tensores para IA/ML. A ABI continua usando handles opacos (int), mas a linguagem já reconhece anotações parciais Tensor<dtype, rankN> para código novo. Cada tensor tem dtype (int ou float), shape, strides, layout, armazenamento CPU compartilhado e offset base para views seguras.
EN-US:
std.tensor provides the current production tensor core for AI/ML. The ABI still uses opaque handles (int), but the language now recognizes partial Tensor<dtype, rankN> annotations for new code. Each tensor has dtype (int or float), shape, strides, layout, shared CPU storage, and a base offset for safe views.
import std.tensor as tensor
Criação / Creation
Código novo pode usar Tensor<float, rank1>, Tensor<float, rank2> e metadados opcionais de dimensão/layout/device quando a anotação é explícita:
New code can use Tensor<float, rank1>, Tensor<float, rank2>, and optional dimension/layout/device metadata when the annotation is explicit:
let v: Tensor<float, rank1, dim3, row_major, cpu> = [1.0, 2.0, 3.0]
let any_len: Tensor<float, rank1, dynamic_dim, row_major, cpu> = v
let m: Tensor<float, rank2, dim2, dim2, row_major, cpu> = [[1.0, 2.0], [3.0, 4.0]]
Rank, dtype, dimensão estática, layout e device incompatíveis falham em check/compile com códigos JSON estáveis E1401 a E1405. Literais rank2 precisam ser retangulares.
Rank, dtype, static dimension, layout, and device mismatches fail during check/compile with stable JSON codes E1401 through E1405. Rank2 literals must be rectangular.
| Função / Function | Assinatura / Signature | Descrição / Description |
|---|---|---|
vector_f | (size: int, value: float) -> Tensor<float, rank1> | 1D float tensor filled with value |
matrix_f | (rows: int, cols: int, value: float) -> Tensor<float, rank2> | 2D float tensor filled with value |
zeros | (size: int) -> int | 1D int tensor filled with 0 |
ones | (size: int) -> int | 1D int tensor filled with 1 |
full | (size: int, value: int) -> int | 1D int tensor filled with value |
full_f | (size: int, value: float) -> Tensor<float, rank1> | 1D float tensor filled with value |
arange | (start: int, end: int, step: int) -> int | 1D int range tensor |
zeros2, ones2 | (rows: int, cols: int) -> int | 2D int tensors |
full2, full2_f | (rows: int, cols: int, value) -> int / Tensor<float, rank2> | 2D tensors filled with value |
uniform | (size: int, min: int, max: int) -> int | Seeded int tensor with values in [min, max) |
uniform_f | (size: int, min: float, max: float) -> int | Seeded float tensor with values in [min, max) |
normal_f | (size: int, mean: float, stddev: float) -> int | Seeded normal-distribution float tensor |
bernoulli | (size: int, p: float) -> int | Seeded int tensor with 0/1 samples |
categorical | (size: int, weights: int) -> int | Seeded category samples from a 1D weight tensor |
set_deterministic_mode | (enabled: int) -> int | Enables deterministic tensor mode and resets RNG to a stable seed when enabled; returns 0 on success |
deterministic_mode | () -> int | Reports deterministic tensor mode as 0 or 1 |
tolerance_abs, tolerance_rel | () -> float | Numerical certification tolerance policy |
Metadados e Acesso / Metadata and Access
| Função / Function | Assinatura / Signature |
|---|---|
len | (handle: int) -> int |
rank | (handle: int) -> int |
dim | (handle: int, axis: int) -> int |
rows, cols | (handle: int) -> int |
device | (handle: int) -> int |
device_available | (device: int) -> bool |
device_status | (device: int) -> int |
to_device | (handle: int, device: int) -> int |
cpu | (handle: int) -> int |
sync | (handle: int) -> unit |
precision | (handle: int) -> int |
to_precision | (handle: int, precision: int) -> int |
get, get_f | (handle: int, index: int) -> int/float |
set, set_f | (handle: int, index: int, value) -> unit |
get2, get2_f | (handle: int, row: int, col: int) -> int/float |
set2, set2_f | (handle: int, row: int, col: int, value) -> unit |
Views compartilham armazenamento quando possível. set e set2 aplicam copy-on-write quando o armazenamento é compartilhado, evitando mutação insegura entre aliases.
Views share storage where possible. set and set2 apply copy-on-write when storage is shared, avoiding unsafe alias mutation.
Operações / Operations
| Função / Function | Descrição / Description |
|---|---|
reshape(handle, rows, cols) | Returns a new handle with validated 2D shape |
flatten(handle) | Returns a new 1D tensor handle |
permute(handle, axis_a, axis_b) | Swaps two axes and returns a view handle |
slice(handle, start, end) | Returns a 1D shared-storage slice view |
concat(lhs, rhs) | Concatenates compatible tensors on axis 0 |
stack(lhs, rhs) | Stacks two same-shape tensors on a new leading axis |
add, sub, mul, div | Elementwise ops; shapes and dtypes must match |
neg, relu | Unary ops over int or float tensors |
exp_f, log_f, sqrt_f, sigmoid_f, tanh_f | Float-output unary kernels |
sum, sum_f, mean_f, min, max, argmax | Reductions |
sum_t, mean_t | Differentiable scalar tensor reductions for backward |
matmul(lhs, rhs) | 2D matrix multiplication |
matmul_batched(lhs, rhs) | 3D batched matrix multiplication: [batch, m, k] x [batch, k, n] |
transpose(handle) | 2D transpose |
dot(lhs, rhs) | 1D dot product; returns int for int tensors and f64 ABI bits for float tensors |
dot_t(lhs, rhs) | Differentiable 1D dot product returning a scalar tensor |
seed(value) | Sets the deterministic tensor RNG seed |
requires_grad(handle, enabled) | Enables/disables gradient tracking for a float tensor |
backward(loss) | Runs reverse-mode autodiff from a scalar tensor loss |
grad(handle) | Returns the accumulated gradient tensor |
zero_grad(handle) | Clears accumulated gradient |
set_grad_enabled(enabled), grad_enabled() | Controls inference/no-grad mode |
stats_graph_nodes() | Counts live autograd graph nodes |
stats_allocations, stats_active, stats_active_bytes, stats_peak_bytes | Tensor allocation metrics |
stats_reused_buffers, stats_pool_hits, stats_pool_misses, stats_scratch_reuses | Buffer-pool and scratch metrics |
stats_kernel_ops, stats_kernel_elements, kernel_strategy | Kernel work and dispatch metrics |
stats_device_transfers | Device transfer metric |
stats_gpu_kernel_ops | Successful GPU kernel dispatch count |
stats_cpu_fallbacks | GPU kernel failures recovered through CPU fallback |
stats_lifetime_records, stats_released_lifetimes | Tensor lifetime planning counters |
stats_allocation_sites, stats_reuse_rate_per_mille | Allocation-site visibility and buffer reuse rate |
memory_report() | JSON memory report with schema spectra.tensor.memory_report.v1 |
reset_stats() | Resets tensor metrics while preserving active tensor accounting |
free(handle), free_all() | Release tensor handles |
Blocos diferenciáveis / Differentiable Blocks
diff { ... } marca uma região diferenciável. O bloco deve produzir um tensor escalar de loss, normalmente criado por sum_t, mean_t ou dot_t. O compilador baixa o bloco para backward(loss) e retorna o próprio loss para uso posterior.
diff { ... } marks a differentiable region. The block must produce a scalar tensor loss, usually created by sum_t, mean_t, or dot_t. The compiler lowers the block to backward(loss) and returns the same loss for later use.
let initial: Tensor<float, rank1> = [3.0, 3.0, 3.0]
let weights: Tensor<float, rank1> = tensor.requires_grad(initial, true)
let loss: Tensor<float, rank0> = diff {
tensor.sum_t(tensor.mul(weights, weights))
}
let grad: Tensor<float, rank1> = tensor.grad(weights)
Operações qualificadas de stdlib que não participam do grafo diferenciável, como metadados (tensor.rank) ou lifecycle (tensor.free_all), falham dentro de diff { ... } com o código estável E1406. Mova I/O, metadados e liberação de recursos para fora do bloco.
Qualified stdlib operations that do not participate in the differentiable graph, such as metadata (tensor.rank) or lifecycle (tensor.free_all), fail inside diff { ... } with stable code E1406. Move I/O, metadata, and resource release outside the block.
Exemplo / Example
module tensor_demo
import std.tensor as tensor
public func main() returns int {
let a = tensor.arange(1, 5, 1)
// [1, 2, 3, 4]
let b = tensor.full(4, 2)
// [2, 2, 2, 2]
let c = tensor.add(a, b)
// [3, 4, 5, 6]
if tensor.sum(c) != 18 {
return tensor.sum(c)
}
let m = tensor.reshape(tensor.arange(1, 7, 1), 2, 3)
let ones = tensor.ones2(3, 2)
let product = tensor.matmul(m, ones)
let product_cpu = tensor.to_device(product, 0)
tensor.sync(product_cpu)
if tensor.get2(product_cpu, 1, 0) != 15 {
return tensor.get2(product_cpu, 1, 0)
}
tensor.free_all()
return 0
}
Estado Phase 3/4: std.tensor inclui views seguras, copy-on-write em mutação compartilhada, operações MVP de tensor, kernels CPU portáveis, RNG reproduzível por seed, distribuições básicas, categorical sampling, métricas de alocação/kernel e benchmark release reproduzível. Estado Phase 7/16: device placement é explícito para handles CPU e wgpu, com device, device_available, device_status, to_device, cpu, sync, stats_device_transfers, stats_gpu_kernel_ops e stats_cpu_fallbacks; device 0 é CPU, device 6 é wgpu com --features gpu, e os códigos 1 CUDA, 2 ROCm, 3 Metal, 4 DirectML e 5 Vulkan são reservados sem implementação no build atual. device_status retorna 0 para um backend implementado e disponível, 1 para wgpu implementado mas indisponível no build/host, e HOST_STATUS_INVALID_ARGUMENT para devices reservados ou desconhecidos. Mixed precision usa precision/to_precision com códigos 0 f64, 1 f32, 2 f16 e 3 bf16. Estado Phase 14: Tensor<dtype, rankN, dimN|dynamic_dim, layout, device>, literais rank1/rank2, validação estática de shape em operações principais e diff { ... } com diagnóstico E1406 estão completos para o baseline atual. Estado Phase 15/R-1501: scripts/validate_r1501_bench.py executa benchmarks release de criação de tensor, unary ops, reductions, matmul, convolução, autodiff, otimizadores e data loading contra thresholds versionados. Estado Phase 15/R-1502: std.tensor.memory_report() e métricas stats_lifetime_records/stats_reuse_rate_per_mille expõem lifetimes, allocation sites, reuse e pressão de memória. Estado Phase 15/R-1503: scripts/validate_r1503_correctness.py gera artefatos portáteis de correção numérica para RNG, reductions, matmul, convolução e otimizadores com tolerância 1e-9 absoluta/relativa. Estado Phase 16/R-1603: scripts/validate_r1603_gpu_backend.py valida CPU fallback, WGPU opcional, diagnósticos de capability e kernels de elementwise/reductions/matmul/conv2d/autodiff.
Estado Phase 5: std.tensor inclui autodiff reverse-mode para tensores float, com requires_grad, backward, grad, zero_grad, modo inference/no-grad e liberação automática do graph após backward. Use reduções tensor-returning (sum_t, mean_t, dot_t) para criar losses diferenciáveis. R-3004 adiciona um grafo reverso compiler-visible (spectralang.r3004_autodiff_ir.v1) com seeds, valores salvos, regras versionadas, acumulação explícita e AutodiffStep executado por kernels reversos individuais. Blocos diff não usam mais o adapter interno; tensor.backward permanece disponível somente como API pública de compatibilidade.