# Dynamic Tensors and Masks

Use `Tensor<T>` for an owning sequence whose length is known at runtime, and
`Tensor<T, N>` when the length is part of the type. A dynamic `Mask` represents
one boolean decision per runtime lane; `Mask<N>` fixes that lane count in the
type. Choosing a dynamic tensor does not itself request GPU execution.

## Constructing a Dynamic Tensor

The dynamic fill form takes the **element count first**, then the value:

```vex [tensor-fill.vx]
fn main(): i32 {
    let! values = Tensor.fill<i32>(4, 7);
    values[1] = 11;
    let empty = Tensor.fill<i32>(0, 0);
    if values.len() != 4 || values[0] != 7 || values[1] != 11 {
        return 1;
    }
    if empty.len() != 0 { return 2; }
    $println(values[1]);
    $println(empty.len());
    return 0;
}
```

Save this as `tensor-fill.vx` and run `VEX_NO_GPU=1 vex run tensor-fill.vx`.
Expected output is `11` followed by `0`, with exit status 0. An empty tensor has
no valid index; constructing it does not authorize reading `empty[0]`.

`Tensor.fill<T>(count, value)` is different from the fixed-size
`Tensor.fill<T, N>(value)` form. Do not pass a shape vector where an element
count is expected. The old `Tensor.filled(value, count)` recipe is not the
constructor taught by this guide.

## Ownership and Copies

A dynamic tensor owns its backing allocation. A `Span<T>` is a borrowed view:

| Operation | Ownership meaning |
| --- | --- |
| `tensor.clone()` | Independent dynamic storage; modifying the clone does not modify its source. |
| `tensor as Span<T>` | A borrowed view tied to the tensor owner's lifetime. |
| `span as Tensor<T>` / `span.toTensor()` | An owned materialization, with allocation/copy cost. |
| Fixed tensor to span | Scoped addressable storage; the view must not escape its owner/frame. |

Do not infer interchangeability from a similar pointer/length layout. An
owning tensor fabricated from borrowed storage would introduce invalid cleanup
and lifetime behavior. Keep the conversion explicit in a performance-sensitive
path and measure its cost.

## Indexed Reads and Updates

`gather(indices)` returns elements in index order. `scatter(indices, updates)`
returns an independently owned result with those positions changed; it does
**not** mutate the source. Retain the returned value:

```vex [tensor-scatter.vx]
fn main(): i32 {
    let source = Tensor.fill<i32>(4, 7);
    let! indices = Tensor.fill<i32>(2, 0);
    indices[0] = 1;
    indices[1] = 3;
    let updates = Tensor.fill<i32>(2, 11);
    let changed = source.scatter(indices, updates);
    let selected = changed.gather(indices);
    if source[1] != 7 || source[3] != 7 { return 1; }
    if changed[0] != 7 || changed[1] != 11 || changed[3] != 11 { return 2; }
    if selected.len() != 2 || selected[0] != 11 || selected[1] != 11 { return 3; }
    $println(source[1]);
    $println(changed[1]);
    $println(selected.len());
    return 0;
}
```

Expected output is `7`, `11`, `2`, each on a separate line. Use integer index
values within the source extent, and provide one update per selected position.
Negative, too-wide and past-end indices are not valid accesses. Repeated indices
need a deliberate conflict rule; combining forms such as `scatter_add` are
separate operations. Do not infer atomic access to shared application state
from the word “scatter”.

## Dynamic Masks

A comparison such as `values > 0` produces a boolean decision for each lane.
Combine compatible masks with `&`, `|` and `!`; use `any()`, `all()` or
`countBits()` when a scalar decision is required.

Selection and compaction solve different problems:

- `mask.select(whenTrue, whenFalse)` chooses a value per lane and preserves the
  output extent.
- compaction keeps selected values and changes the output extent.

Selection is not short-circuit control flow. Do not evaluate a division by zero
or an invalid memory read and expect a later mask to undo it. For a guarded
calculation, make every evaluated lane valid or use a supported control-flow
form with the required semantics.

## Shapes and Reductions

A dynamic tensor's flat element count does not by itself describe matrix axes.
A reshape or matrix operation must carry compatible shape information through
the supported lowering path. `24` elements could represent `4 × 6`, `2 × 3 × 4`
or a vector; the choice is part of the algorithm, not a property inferred from
the allocation size.

For a mean, handle zero length before dividing by the count. Floating-point
reductions can have backend-dependent accumulation order. Choose and test a
numerical tolerance appropriate to the application.

## GPU Integration

Dynamic tensors can participate in supported SIR graphs. They still need a
compatible generator, runtime bridge and device. Begin with
[Graph Functions](../fusion/graph.md), then validate the exact dynamic operation
and shape on the chosen target. A CPU-only test of the examples above does not
qualify GPU execution.

## Memory Layout

The current host compiler uses internal pointer/length aggregates for dynamic
tensors and packed storage for dynamic masks. Those are implementation details,
not C ABI declarations. See [Tensor and Mask Types](tensor-mask.md) and
the [mask representation contract](simd-simt-contract.md#dynamic-mask-representation-in-the-development-implementation).

## Related Pages

- [SIMD Operations](simd-operations.md)
- [Tensor and Mask Types](tensor-mask.md)
- [Span](../memory/span-t.md)
- [GPU Programming](../gpu/index.md)

<a id="dyntensort"></a>
<a id="construction"></a>
<a id="access-and-manipulation"></a>
<a id="reshape"></a>
<a id="dynmask"></a>
<a id="mask-operations"></a>
<a id="selective-operations-with-masks"></a>
<a id="tensor-dyntensor-interaction"></a>
<a id="best-practices"></a>
