Miscellaneous spec utilities #
This file collects small helper definitions used across the spec layer.
The contents are intended to be broadly reusable: small constructors, shape-preserving maps, and lightweight conversion/pretty-printing helpers used by examples and by higher-level APIs.
Main definitions include:
map_tensor(change the scalar type of a tensor, preserving shape),- basic constructors like
zeros/ones, - simple pretty-printing (
Spec.pretty) for executable scalar backends, - list ↔ tensor helpers (
from_list_1d,from_list_2d).
User-facing constructors in the tensor API (for example tensorND!, tensorF!) live in
NN/Tensor/API.lean and are built on top of these utilities.
Map a scalar function across a tensor, changing the element type.
PyTorch analogy: torch.Tensor.to(dtype=...) is implemented as a scalar cast map under the hood.
We keep this explicit at the spec layer because it is a common building block.
Instances For
Small constructors #
Fill a tensor with a constant, using the shape of an existing tensor.
PyTorch analogy: torch.full_like(t, value). We implement it by structural recursion so that
the argument tensor is genuinely used (and so this stays friendly to linters).
Instances For
Tensor ↔ list utilities #
Expand a vector into a column vector by inserting a trailing dimension of size 1.
Instances For
Build a vector tensor from a list.
PyTorch analogy: torch.tensor(xs) producing a 1D tensor.
Instances For
Build a matrix tensor from a list of rows (strict validation).
This is the "safe by default" constructor used by the user-facing API layer. It refuses empty input and refuses ragged rows, because that usually indicates a bug at the call site (e.g. an accidental missing column in imported weights).
PyTorch analogy: torch.tensor(xss) will also error if xss is ragged.
Instances For
Build a matrix tensor from a list of rows by padding/truncating to nCols.
This is the "permissive" constructor: it never fails, but it will silently pad missing entries
with default (and ignore any extra entries beyond nCols).
This is useful when importing data that is naturally ragged, or when you intentionally want "pad-right with zeros" semantics (common in NLP style batching).
PyTorch analogy: this is closer to a manual pad_sequence + torch.tensor, except we do it
directly as a tensor constructor at the spec layer.
Instances For
Build a matrix tensor from a list of rows by padding to the maximum row length.
If xss = [], this returns a 0 x 0 tensor. Otherwise, the number of columns is
max_row_length xss and shorter rows are padded with default.