Filesystem-backed tensors with dense and sparse storage, lazy arithmetic, and bounded streaming execution.
Chaining operations constructs typed view descriptions, following ha-ndarray's composition model. Awaiting a view-construction method does not evaluate or persist its result. Import the relevant operation traits to use their methods. The checked crate example composes matrix multiplication, scalar addition, and exponentiation, then consumes coordinate-bearing batches without creating result storage.
Tensor<FE, T> owns storage; tensor.view() creates a geometric TensorView.
Unary, binary, conditional, reduction, and matrix expressions remain lazy and
read-only. Computed views implement neither TensorWrite nor TensorArray;
geometric views retain constrained write-through access. View descriptions can
be cloned without requiring the filesystem adapter to implement Clone.
TensorWriteBulk implementations provide writes from buffers and fill. Each
implementation validates supported geometry and input cardinality.
TensorExpression<T> owns values composed at runtime, including their source
handles. Concrete views retain their operands and implement their operations.
The shared consumer uses an explicit stack of evaluation frames so polling and
destruction remain safe at user-controlled nesting depths. Elementwise
operations realize their bounded numerical result through ha-ndarray before
returning it to the parent; geometric projections forward their source result.
Reductions, matrix products, and Fourier transforms retain bounded batches, tiles,
or accumulators in the same process. They never persist computed intermediates.
Nested expressions can recompute values, and source reads/cache spill can do I/O.
Tensor::copy_from(dir, &expression, destination_layout, max_capacity).await?
creates independent filesystem storage with caller-selected packing. Supported
operations compose without copying; unsupported sparse traversal can be made
explicit through Tensor::copy_from_values. The destination adapter can differ from the
source adapter and must support the output dtype. max_capacity bounds the
values per chunk; each region can end with a shorter chunk. Sparse copying accepts a new
sparse axis and omits final numerical zeros. A reader's reported layout describes
its values and supplies a hint; it does not choose destination allocation.
Dense/sparse kind mismatches return a structured error. Use into_dense() before
materializing a sparse expression as dense storage.
The native storage contract describes logical-block access, source ownership, and replacement guarantees.
Logical shapes, strides, coordinates, and cardinalities use u64; axes use usize.
Import Shape, Strides, Range, AxisRange, and Axes from fensor.
TensorGeometry::size() returns Result<u64>; geometric flat offsets use checked
i128. Operation traits expose per-operation associated output types. Generic
callers state the required dtype bounds, and cast destinations may need annotations.
Storage packing and view geometry are separate:
| Layer | Responsibility |
|---|---|
Stored Tensor |
Fixed logical shape, layout, and block geometry recorded in metadata. |
TensorView |
Maps its current coordinates to the source, without rearranging storage. |
| Storage owner | Resolves logical block IDs and validates/reads their payloads. |
Dense storage uses typed payload files. Sparse storage uses one native BTree, keyed by logical block ID, whose rows contain dense block payloads. Missing blocks represent zero; all-zero blocks are omitted. The BTree has no per-axis secondary indexes. Both layouts use the same geometric transforms and numerical kernels.
For Layout::Sparse { axis: Some(a) }, coordinates through axis a select a
dense trailing region. Blocks have extent one on that prefix and partition the
trailing region within the configured capacity. axis: None selects scalar
sparsity. Capacity changes packing, not tensor values; loading preserves the
recorded block geometry. See native storage
for validation and ownership details.
TensorTransform provides slice, transpose (including arbitrary permutations),
reshape, flip, broadcast, squeeze, and unsqueeze. These compose coordinate mappings;
consumption turns bounded requests into source block IDs and offsets, then gathers
values in the requested output geometry. For example, slicing a 2-D source with
axis ranges 10..20 at step 2 and 30..40 at step 1, then swapping axes, produces
shape [10, 5] with view[i, j] = source[10 + 2*j, 30 + i].
Transforms validate their input and supported composition. Reshape requires equal cardinality and contiguous row-major view geometry; it does not silently copy a transposed, flipped, or gathered view. Explicit copying can provide a new contiguous source. A view's reported layout describes its output and may drop a sparse-axis hint; it neither repacks the source nor selects destination allocation.
A multidimensional selection need not be one contiguous BTree range. Eligible sparse traversal scans occupied block IDs and checks their geometry before reading payloads. Ordinary block reads can evaluate other supported mappings in bounded batches; indexed ordered reads have stricter geometry/order requirements, described under sparse values. Sparsity does not guarantee work proportional to nonzeros for every transform or aggregate. Rank-zero views cannot be streamed or copied, and empty-dimension tensor storage is unsupported.
Stored types are u8/u16/u32/u64, i8/i16/i32/i64, and f32/f64.
The optional complex feature adds fensor::complex::{Complex32, Complex64},
with f32 and f64 components respectively. Boolean outputs use u8, which accepts
the full range 0–255; native bool and abstract number classes are not storage types. Schema
and geometry metadata use number-general's NumberType, re-exported by fensor.
TensorGeometry::DType names the Rust element type; dtype() returns its class.
Unsupported or abstract number classes are rejected during schema construction.
| Trait | Operations | Input → output |
|---|---|---|
TensorUnary |
exp, ln; round |
Float/complex → same dtype; round is real-float only |
TensorAbs |
abs |
Real → same dtype; complex → component real dtype |
TensorTrig |
sin, asin, sinh, cos, acos, cosh, tan, atan, tanh |
Float/complex → same dtype |
TensorCast<To> |
cast |
Any supported concrete dtype → any supported concrete dtype |
TensorComplex |
conj; re, im, angle |
Complex → complex; complex → component real dtype |
TensorUnaryBoolean |
not |
Any supported dtype → u8 |
TensorNumeric |
is_nan, is_inf |
Float/complex → u8 |
TensorMath, TensorMathScalar |
add, sub, mul, div, pow; _scalar variants |
Matching supported dtypes → same dtype |
TensorMath, TensorMathScalar |
rem, rem_scalar; log, log_scalar (value, base) |
Matching real dtypes; matching float/complex dtypes |
TensorCompare, TensorCompareScalar |
eq, ne; gt, ge, lt, le; _scalar variants |
Matching supported dtypes; ordering requires real inputs → u8 |
TensorBoolean, TensorBooleanScalar |
and, or, xor; _scalar variants |
Matching supported dtypes → u8 |
TensorWhere |
condition.cond(&then, &or_else) |
u8 condition; matching branches → branch dtype |
TensorReduceAll |
sum_all, product_all; min_all, max_all |
Any supported dtype; extrema require real inputs → same scalar dtype |
TensorReduceBoolean |
all, any |
Any supported dtype → bool |
TensorReduce |
sum, product; min, max |
Any supported dtype; extrema require real inputs → same dtype |
TensorMatrixUnary |
mt, diag |
Any supported dtype → same dtype |
TensorMatrixUnaryComplex |
mh |
Complex → same dtype |
TensorFourier; fft::fft2, fft::ifft2 |
Last-axis and final-two-axis Fourier transforms | Complex → same dtype; bounded axis lengths |
TensorMatMul |
matmul |
Matching supported dtypes → same dtype |
Arithmetic methods borrow operands and are asynchronous. Elementwise tensor
operands must have identical shapes and dtypes; scalar arguments match the source
dtype. Broadcasting and casts are explicit, including identity and narrowing casts.
Select the destination through the result type or TensorCast::<To>::cast(&view);
operations before and after a cast execute in their respective dtypes.
Conversions follow number-general's pipeline, including intermediate widths:
for example, -1i8 → u64 yields 255, while -1f64 → u8 yields zero.
Unary composition nests sources, for example
UnaryView<UnaryView<Source, Round>, Exp>. Public operation markers live in
unary, binary, scalar, and reduce.
Elementwise transforms preserve operation order. Reduction and matrix output transforms address the output geometry instead of moving through the aggregate.
Numerical rules belong to ha-ndarray. Its
numerical contract
provides non-normative integration context for this standalone crate. Fensor delegates
arithmetic, nonfinite values, signed zeros, predicates, and complex branches to that
backend; it does not clamp results or define substitute numerical rules. mt
transposes without conjugation. Backend validation status belongs to ha-ndarray.
An absent sparse value is ordinary numerical zero. Dense and sparse expressions use the same numerical kernels; there is no separate numerical support mask or history of intermediate zeros. Each pointwise expression retains its typed zero-background result so indexed reductions preserve backend signed-zero behavior. Sparse output omits numerical zeros, including zeros produced by an expression.
Pointwise operations which would change the implicit zero background to a nonzero
value return Error::WouldDensify { operation }. For example, sparse exp() and
add_scalar(1) require explicit conversion first:
let dense = TensorExpression::new(source)?.into_dense();
let result = dense.exp().await?;into_dense() is lazy: it declares dense output without copying storage or
changing existing clones. Evaluation then includes implicit zeros, so
exp() returns one at those coordinates. Both conditional branches are evaluated;
corruption in either branch propagates.
Ordered sparse reads emit logical row-major nonzero values, including transformed
views, and reject other orders with UnsupportedSparseIterationOrder. They sort
and deduplicate explicit selections for this reader only; geometric slicing retains
selection order and duplicates. Compatible geometry traverses occupied logical blocks
through paginated indexes. Eligible pointwise expressions delegate and merge these
candidates incrementally. Runtime-owned forward slices and permutations retain the same indexed planning.
Unsupported mappings or ordering return a structured error for selections larger
than one execution batch; use Tensor::copy_from_values to explicitly materialize
them. Bounded point reads and row-major read_blocks remain available. Aggregate
outputs retain their own logical evaluation; sparse storage alone does not guarantee
work proportional to nonzero values. See slice traversal.
Stored tensors support terminal reductions directly; axis reductions start from
a view, for example tensor.view().sum(axes![1], false).await?. Axes are sorted
and deduplicated, and invalid axes fail at construction. Empty axes reduce
singleton groups. keepdims retains reduced dimensions at extent one; removing
every axis produces [1].
Terminal and axis reductions include every selected logical value, including implicit sparse zeros. They have the same numerical meaning as reductions over equivalent dense values; an all-zero sparse tensor has zero product and extrema.
TensorStatistics supplies mean, population standard deviation, and Euclidean norm,
both whole-tensor and by axis. Counts include implicit zeros. Real results use f64;
complex mean uses c64 and complex standard deviation and norm use f64.
Boolean terminals stop after a decisive consumed batch. Errors in that batch or earlier propagate; later errors may remain unobserved and prefetched reads may already have started. Numeric terminals consume all batches, including extrema.
Matrix multiplication requires rank ≥2, equal batch dimensions, and matching
contraction dimensions: [..., M, K] @ [..., K, N] -> [..., M, N]. Use explicit
broadcasting or casts to align operands. Products compose with every expression
family, including nested products. Dense and sparse operands share bounded tiles
and full logical contraction: zero-times-infinity can produce NaN and must not be
skipped. Floating results obey the backend aggregate accuracy contract, not bitwise
equivalence to a multiply/reduce expression.
Matrix-unary operations also require rank ≥2. mt() swaps the final two axes,
leaving batch axes and existing geometric write constraints intact. diag()
requires square final dimensions and returns a read-only view of shape
[..., N] from [..., N, N]:
let diagonal = tensor.view().mt().await?.diag().await?;Only diagonal source coordinates contribute values. Transforms on a diagonal view address its output, and further operations remain lazy. Selected reads visit the requested diagonal coordinates; a complete sparse scan still scales with logical diagonal length. Neither operation persists results.
With the complex feature, mh() composes matrix transpose and conjugation.
fft() and ifft() transform each last-axis group independently;
fensor::fft::fft2(&view) and ifft2(&view) compose transforms over the final
two axes. All are lazy and read-only. Transforms are unnormalized: inverse after
forward scales by the axis length, or the product of both lengths for 2D.
Each transformed axis must fit the execution limit in the bound table; construction rejects longer axes. Even a point read evaluates a complete axis group, including implicit sparse zeros. Nested and 2D transforms may recompute groups; bounded memory does not imply work proportional to nonzeros or optimal transform throughput.
Native BTree guards coordinate sparse reads and replacement. Synchronization releases operation guards before entering the directory hierarchy; callers quiesce mutations when they need a precise durable boundary. Validation is not a transaction snapshot across concurrent writes. After a failed or cancelled mutation, callers must discard all handles to the affected storage and coordinate recovery before reuse. Native writes may have partially changed storage; cancellation returns no error.
Stored payload lengths are validated against bounded metadata. Adapters remain responsible for limiting decoding allocations before fensor receives a payload.
| Consumer | Delivery order |
|---|---|
read_blocks() |
Logical row-major values |
read_sparse_elements_in_order() |
Requested row-major sparse order |
read_coordinate_blocks() |
Preferred-request-order CoordinateBatch values retaining compact coordinates |
| Whole-tensor numeric terminals | Accumulate batches in request order |
| Boolean terminals | Logical order with short-circuiting |
A CoordinateBatch owns its compact request and value buffer. Native copying
consumes that request directly; into_values moves a value-only result, while
into_coordinates(shape) explicitly expands a bounded batch for coordinate
consumers. Custom readers construct checked batches with from_coordinates.
A successful complete coordinate stream visits every logical coordinate exactly once, including zeros. Its default adapter pairs row-major values with coordinates; built-in sources visit intersecting physical blocks, and matrix expressions can generate tiled requests. Transformed source planning retains consumer coordinates; absent sparse blocks still contribute their zero-valued coordinates. Request traversal is distinct from batch delivery order. Each stream is independent and live, not a snapshot. Concurrent source writes are not isolated. Dropping a stream cancels pending work.
ha-ndarray owns numerical parallelism; dense storage owns concurrent reads.
Expression consumers evaluate one bounded request at a time. Dense storage uses
ordinary file reads with buffered(num_cpus::get().max(1)) and scatters directly
from borrowed payloads. freqfs owns admission and eviction; insufficient cache
capacity can return a bounded error. There is no separate prefetch stage or
expression-batch queue. Independent consumers may run concurrently.
The driver suspends a parent until its requested child completes, preserving
operand order without recursive future
polling. Ready evaluation and occupied-candidate traversal yield cooperatively at
bounded work intervals, so cancellation can interrupt cached work. Synchronous
backend calls run on the polling thread and may use ha-ndarray's workers; async move does not create CPU parallelism.
Numeric terminal accumulation retains request-partitioning and backend scheduling limits, including extreme overflow/underflow differences permitted by ha-ndarray. Wrapping integers, NaN extrema, and signed-zero rules are preserved. Errors stop request consumption and drop active evaluation; later requests are not evaluated.
Execution batches obey the execution limit. Values, coordinates, and partial-result collections must not scale with total tensor, output, or reduction group size. Caller-supplied values and explicit indices, rank-sized metadata, cache/filesystem metadata, and independent consumers are separate memory costs. This is not a total-process memory guarantee. The execution design defines the bounds and private traversal mechanics. Callers may explicitly collect streams when they want an in-memory result; fensor offers no whole-result collector.
Filesystem adapters implement freqfs::FileLoad/FileSave and expose Vec<T>,
SparseNode<T>, and TensorMetadata<T> through AsType. fensor requires
destream but prescribes no byte codec or whole-tensor transfer format. JSON and
TBON adapters are exercised in tests; applications own their format choices.
Metadata encodes shape, layout, sparse axis, and block capacity. The adapter must preserve the Rust payload type across reloads, for example with distinct tagged block/metadata variants per dtype. Decoding untagged metadata as whichever dtype was requested violates this contract. The native storage contract defines these native structures. Adapters choose codecs and preserve exact typed scalar bits in sparse nodes; fensor validates geometry and native structure without recovery or repair paths.
Call tensor.sync().await? before dropping and reopening storage. It writes blocks
and publishes the current sparse index root; syncing only the containing directory
does not publish that in-memory root. Quiesce writes for a precise durable boundary.
Use tensor.sync_all().await? for delegated durable synchronization. Callers own
transaction and recovery policy.
fensor provides no commit, rollback, or isolation semantics.
Tensor::copy_from retains indexed sparse copying and rejects unsupported ordered
traversal. Tensor::copy_from_values is the explicit full-value alternative: it
consumes logical row-major batches once, validates and counts each batch before
omitting sparse zeros, and requires exact total cardinality before publication. It
uses the same storage construction. It can be expensive for huge
sparse shapes; neither operation retries through the other. Both retain the existing
requirement to convert dense/sparse kinds explicitly before copying.
Copying performs destination updates sequentially. Sparse construction may assemble a bounded batch of nonzeros from several input batches; it adds no speculative lookahead or background work. Validation and errors remain non-transactional: failures propagate and can leave partial output without loadable metadata or a guaranteed write prefix. Synchronization and cleanup remain caller responsibilities.
Element types need no destream implementation: adapters encode their payloads, including any complex component representation. fensor's typed metadata remains codec-neutral and encodes geometry only.
The freqfs cache accounts for typed retained allocation and applies admission backpressure through eviction/spill. Configure cache capacity, minimum free disk space, and admission wait in freqfs; oversized files, exhausted admission deadlines, and disk failures return I/O errors. Bounded execution does not eliminate logical sparse contraction scans, repeated nested evaluation, or cache-sensitive read amplification. Completion-order copying can worsen cache locality and increase adapter traffic; fewer delivery stalls do not guarantee faster copying. See benchmark methodology and interpretation.
TensorSource connects typed native or caller-provided logical blocks to the
same geometric views and expression evaluator. StorageGeometry describes bounded
linear chunks, and occupied-block streams use canonical block IDs. Views own their
source handles; TensorExpression<T> owns dynamically composed read-only values.
Borrowed reads and owned consuming streams share one bounded evaluator. Runtime
expression descriptions and evaluation frames have checked limits; each numerical
batch is bounded, but aggregate retained intermediates grow with expression structure.
There is no aggregate payload admission limit; see the bound table.
Request and occupied-candidate traversal use explicit work lists, and final ownership release
detaches operands before draining them. Dropping a stream cancels active evaluation
and releases its retained source handles without following expression depth on the
worker stack. Physical payload and index mutation are private to the native owner.
Storage itself is never erased.
replace_logical_block coordinates native sparse
payload/index changes and preserves other logical blocks sharing native BTree pages.
Tensor::load is strict and non-mutating: missing metadata, blocks or indexes,
wrong payload types, invalid lengths, duplicate logical keys, and inconsistent
index coordinates are errors. Each native owner has separate creation and loading
operations; creation requires empty delegated storage. See the
native storage and sources for the external ownership boundary.
See remaining work, execution design, benchmark reproduction, and test ownership.
Geometric TensorView values can plan bounded BlockUpdates from row-major value
batches with plan_updates, or consume an owned expression with updates_from.
The latter uses preferred-request-order delivery and retains the source until consumption
or drop. These methods describe logical-block offsets; callers own write permission
and publication. Independent native materialization uses Tensor::copy_from.
Tensor::from_values consumes exactly one typed row-major value per dense element.
Tensor::from_sparse_elements consumes ordered unique coordinates for a sparse
layout, validating coordinates and omitting zeros. Both accept borrowed, non-Unpin
streams with an input error convertible from fensor::Error. They require empty
delegated storage and publish metadata only after successful construction; callers
own cleanup after errors or cancellation. Published replacement requires existing,
valid dense files and never creates or repairs missing payloads.
Native block metadata now stores capacity instead of a rectangular tile shape.
Old native stores are rejected and must be recreated; no automatic migration or
compatibility reader is provided. Tensor wire values and semantic hashes are
unchanged. StorageGeometry::new takes a capacity, block_len(id) returns an
exact length, and block_range(id) returns a flat row-major range. Arbitrary tile
shapes, padded blocks, and valid-offset iterators are no longer supported.