Skip to content

qten

Package reference for qten.

qten

Top-level public API for QTen.

This package re-exports the most commonly used tensor, device, and precision entry points so users can work from qten directly without importing deep submodules in day-to-day code.

Main exports
  • Tensor StateSpace-aware tensor wrapper over torch.Tensor.
  • Device Logical device descriptor used by QTen objects.
  • set_precision Configure numeric precision defaults for the library.
Tensor construction and manipulation
Tensor algebra and queries
Linear-algebra helpers
Devices and I/O
  • at_device Context manager forcing newly created tensors onto a chosen logical device.
  • io Save/load helpers exposed as a convenience namespace.
Subpackages

For broader domain APIs, see: - qten.geometries - qten.linalg - qten.phys - qten.pointgroups - qten.symbolics - qten.utils

Exported API

set_precision

set_precision(
    precision: PrecisionInput,
    set_torch_default: bool = True,
) -> None

Set QTen's global real and complex dtype family.

The selected precision updates the dtype values returned by get_precision_config(). When set_torch_default=True, it also calls torch.set_default_dtype() with the selected real PyTorch dtype.

Supported values
  • "32" or 32: use torch.float32, torch.complex64, np.float32, and np.complex64.
  • "64" or 64: use torch.float64, torch.complex128, np.float64, and np.complex128.
  • A supported real or complex torch.dtype selects its matching dtype family.
  • A supported real or complex np.dtype or NumPy scalar dtype selects its matching dtype family.

Parameters:

Name Type Description Default
precision PrecisionInput

Precision selector describing the desired 32-bit or 64-bit dtype family.

required
set_torch_default bool

If True, update PyTorch's process-wide default floating dtype to the selected real dtype. If False, only QTen's stored precision config is updated.

True

Returns:

Type Description
None

Raises:

Type Description
ValueError

If precision does not describe a supported 32-bit or 64-bit dtype family.

Source code in src/qten/precision.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def set_precision(
    precision: PrecisionInput,
    set_torch_default: bool = True,
) -> None:
    """
    Set QTen's global real and complex dtype family.

    The selected precision updates the dtype values returned by
    [`get_precision_config()`][qten.precision.get_precision_config]. When
    `set_torch_default=True`, it also calls `torch.set_default_dtype()` with the
    selected real PyTorch dtype.

    Supported values
    ----------------
    - `"32"` or `32`: use `torch.float32`, `torch.complex64`, `np.float32`, and
      `np.complex64`.
    - `"64"` or `64`: use `torch.float64`, `torch.complex128`, `np.float64`,
      and `np.complex128`.
    - A supported real or complex `torch.dtype` selects its matching dtype
      family.
    - A supported real or complex `np.dtype` or NumPy scalar dtype selects its
      matching dtype family.

    Parameters
    ----------
    precision : PrecisionInput
        Precision selector describing the desired 32-bit or 64-bit dtype family.
    set_torch_default : bool
        If `True`, update PyTorch's process-wide default floating dtype to the
        selected real dtype. If `False`, only QTen's stored precision config is
        updated.

    Returns
    -------
    None

    Raises
    ------
    ValueError
        If `precision` does not describe a supported 32-bit or 64-bit dtype
        family.
    """
    global _torch_float_dtype, _torch_complex_dtype
    global _np_float_dtype, _np_complex_dtype

    precision_info = _normalize_precision(precision)

    if set_torch_default:
        torch.set_default_dtype(precision_info.torch_float)

    _torch_float_dtype = precision_info.torch_float
    _torch_complex_dtype = precision_info.torch_complex
    _np_float_dtype = precision_info.np_float
    _np_complex_dtype = precision_info.np_complex

Tensor dataclass

Tensor(data: T, dims: tuple[StateSpace, ...])

Bases: Generic[T], Operable, Plottable, Convertible, DeviceBounded

StateSpace-aware tensor wrapper over torch.Tensor.

A Tensor pairs raw tensor data with symbolic axis metadata in dims. Each entry of dims is a StateSpace whose size must match the corresponding axis of data. This lets tensor operations preserve not only shapes, but also the semantic identity and ordering of axes.

Core model
  • data stores the underlying numeric values as a torch.Tensor.
  • dims stores one StateSpace per axis.
  • tensor.data.shape must equal tuple(dim.dim for dim in tensor.dims).
  • Axes are aligned by StateSpace compatibility rather than by position alone. If two axes represent the same rays in different orders, QTen can permute one operand to match the other.
  • Singleton broadcast axes are represented symbolically by BroadcastSpace().

Attributes:

Name Type Description
data T

Underlying torch.Tensor storing the numeric values.

dims Tuple[StateSpace, ...]

Symbolic dimension metadata, with one StateSpace per axis of data.

Construction

Create tensors directly from a torch tensor and a matching dims tuple:

Tensor(data=torch.randn(2, 3), dims=(left_space, right_space))

Use Tensor.scalar(number) to construct a rank-0 tensor.

Registered operations

The public arithmetic and comparison operators on Tensor are implemented by multimethod registrations on Operable. Those inherited __xxx__ members are hidden from the generated API page, so this section is the canonical reference for Tensor-specific operator behavior.

Matrix multiplication

a @ b contracts two tensors with StateSpace-aware matrix multiplication. The actual logic is implemented by matmul, which:

  • aligns shared contraction axes by StateSpace,
  • supports batch broadcasting over leading axes,
  • preserves output metadata on the surviving axes.

For ordinary rank-2 matrix axes this is the contraction

\((A B)_{ik} = \sum_j A_{ij} B_{jk}\), with the contracted index matched through symbolic StateSpace metadata.

Addition and subtraction

a + b and a - b operate on two tensors using StateSpace-aware alignment.

  • If ranks differ, the lower-rank operand is promoted with leading BroadcastSpace axes.
  • Output metadata is computed from union_dims(..., allow_merge=True).
  • Broadcast axes are materialized with expand_to_union.
  • If two compatible axes represent the same rays in different orders, the right-hand operand is embedded into the merged output ordering before the data is accumulated.

Scalar addition and subtraction are not element-wise broadcast operations.

  • a + c and c + a treat a as a matrix or batch of matrices over its last two axes and compute \(A + cI\).
  • a - c computes \(A - cI\).
  • c - a computes \(cI - A\).
  • These operations therefore require metadata that can construct eye on the tensor dims.

Equivalently, scalar shifts act as \(A \mapsto A + cI\) on the final two axes, not as element-wise broadcasting over every entry.

Negation and scaling
  • -a negates the tensor element-wise while preserving dims.
  • a * c and c * a perform element-wise scalar multiplication.
  • a / c performs element-wise scalar division.
Equality and ordered comparisons

a == b, a < b, a <= b, a > b, and a >= b use symmetric StateSpace-aware comparison semantics.

  • operands are rank-promoted to a common rank,
  • dims are merged with union_dims(..., allow_merge=False),
  • both operands are aligned to the merged dims,
  • torch broadcasting is validated against the merged symbolic shape,
  • the result is a bool Tensor on the merged dims.

Scalar comparisons promote the scalar through Tensor.scalar(...), so:

  • a < c, a <= c, a > c, a >= c follow the same tensor-tensor comparison pipeline,
  • c < a, c <= a, c > a, c >= a use the reflected comparison with the scalar converted to a rank-0 tensor first.
Comparison semantics

Comparisons use symmetric StateSpace-aware alignment: - operands are rank-promoted with leading BroadcastSpace() axes when needed, - dims are merged with union_dims(..., allow_merge=False), - operands are aligned to the merged dims, - runtime broadcast compatibility is validated, - the result is a bool Tensor with those merged dims.

Ordered comparisons on complex tensors are not supported and defer to PyTorch's runtime error behavior.

Shape and axis transforms
Reductions and element queries
Boolean-mask helpers
Indexing

__getitem__ supports: - Python integers, slices, None, and ..., - StateSpace / Convertible axis selection and reindexing, - Tensor advanced indices.

Tensor advanced indexing is metadata-aware and can align tensor index dims before dispatching to torch indexing. Boolean tensor indices are not supported in __getitem__; use comparison masks together with where or nonzero instead.

Autograd and devices
  • attach(): return a leaf tensor with requires_grad=True.
  • detach(): detach from autograd without cloning storage.
  • clone(): deep-copy tensor data.
  • grad: wrapped gradient tensor, if available.
  • requires_grad: autograd flag from underlying data.
  • backward(...): autograd backward pass.
  • device: logical QTen device view of the underlying torch device.
  • to_device(device): move data to another logical device.
Factory and module-level companion functions

The module also exposes helpers that create or operate on Tensor: matmul, permute, transpose, conj, unsqueeze, squeeze, align, align_all, all, mean, norm, argmax, argmin, astype, one_hot, equal, allclose, expand_to_union, union_dims, mapping_matrix, eye, zeros, ones, kernel_tensor, cat, replace_dim, factorize_dim, product_dims, promote_rank, where, and nonzero.

data instance-attribute

data: T

Underlying torch.Tensor storing the numeric values. Its shape must match the dimensions implied by dims.

dims instance-attribute

dims: tuple[StateSpace, ...]

Symbolic dimension metadata, with one StateSpace per axis of data. These dimensions preserve axis identity and ordering beyond raw shape.

device property

device: Device

Return the logical device associated with the tensor data.

Raises:

Type Description
ValueError

If the underlying torch device type is not one of the supported QTen device mappings.

requires_grad property

requires_grad: bool

Check if the tensor data requires gradient tracking.

Returns:

Type Description
bool

True if the tensor data requires gradient tracking, False otherwise.

grad property

grad: Self | None

Return the accumulated gradient wrapped as a QTen tensor.

Returns:

Type Description
Optional[Self]

The current gradient with the same dims, or None if no gradient has been accumulated.

__str__ class-attribute instance-attribute

__str__ = __repr__

cpu

cpu() -> Self

Return a copy of this object residing on the CPU device.

Returns:

Type Description
Self

A copy of this object on the logical CPU device.

Source code in src/qten/utils/devices.py
191
192
193
194
195
196
197
198
199
200
def cpu(self) -> Self:
    """
    Return a copy of this object residing on the CPU device.

    Returns
    -------
    Self
        A copy of this object on the logical CPU device.
    """
    return self.to_device(Device("cpu"))

gpu

gpu(index: Optional[int] = None) -> Self

Return a copy of this object residing on a GPU device.

Parameters:

Name Type Description Default
index Optional[int]

Optional CUDA device index. This should only be set when the target GPU backend supports multiple devices (e.g. CUDA). If not provided, the current device will be used.

`None`

Returns:

Type Description
Self

A copy of this object on the specified GPU device.

Source code in src/qten/utils/devices.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def gpu(self, index: Optional[int] = None) -> Self:
    """
    Return a copy of this object residing on a GPU device.

    Parameters
    ----------
    index : Optional[int], default=`None`
        Optional CUDA device index. This should only be set when the target
        GPU backend supports multiple devices (e.g. CUDA). If not provided,
        the current device will be used.

    Returns
    -------
    Self
        A copy of this object on the specified GPU device.
    """
    device = Device("gpu", index)
    return self.to_device(device)

add_conversion classmethod

add_conversion(
    T: type[B],
) -> Callable[[Callable[[A], B]], Callable[[A], B]]

Register a conversion from cls to T.

The decorated function is stored under (cls, T). When an instance of cls later calls convert(T), that function is used to produce the converted object.

Parameters:

Name Type Description Default
T Type[B]

Destination type produced by the registered conversion function.

required

Returns:

Type Description
Callable[[Callable[[A], B]], Callable[[A], B]]

Decorator that stores the conversion function and returns it unchanged.

Examples:

@MyType.add_conversion(TargetType)
def to_target(x: MyType) -> TargetType:
    ...
Source code in src/qten/abstracts.py
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
@classmethod
def add_conversion(
    cls: Type[A], T: Type[B]
) -> Callable[[Callable[[A], B]], Callable[[A], B]]:
    """
    Register a conversion from `cls` to `T`.

    The decorated function is stored under `(cls, T)`. When an instance of
    `cls` later calls [`convert(T)`][qten.abstracts.Convertible.convert],
    that function is used to produce the converted object.

    Parameters
    ----------
    T : Type[B]
        Destination type produced by the registered conversion function.

    Returns
    -------
    Callable[[Callable[[A], B]], Callable[[A], B]]
        Decorator that stores the conversion function and returns it
        unchanged.

    Examples
    --------
    ```python
    @MyType.add_conversion(TargetType)
    def to_target(x: MyType) -> TargetType:
        ...
    ```
    """

    def decorator(func: Callable[[A], B]) -> Callable[[A], B]:
        _type_conversion_table[(cls, T)] = cast(Callable[[Any], Any], func)
        return func

    return decorator

convert

convert(T: type[B]) -> B

Convert this instance to the requested target type.

Parameters:

Name Type Description Default
T Type[B]

Destination type to convert into.

required

Returns:

Type Description
B

Converted object produced by the registered conversion function.

Raises:

Type Description
NotImplementedError

If no conversion function has been registered for (type(self), T) or any source supertype via add_conversion().

Source code in src/qten/abstracts.py
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
@final
def convert(self, T: Type[B]) -> B:
    """
    Convert this instance to the requested target type.

    Parameters
    ----------
    T : Type[B]
        Destination type to convert into.

    Returns
    -------
    B
        Converted object produced by the registered conversion function.

    Raises
    ------
    NotImplementedError
        If no conversion function has been registered for
        `(type(self), T)` or any source supertype via
        [`add_conversion()`][qten.abstracts.Convertible.add_conversion].
    """
    source_type = type(self)
    table_get = _type_conversion_table.get

    convertor = table_get((source_type, T))
    if convertor is None:
        for super_type in source_type.__mro__[1:]:
            convertor = table_get((super_type, T))
            if convertor is not None:
                # Cache resolved parent conversion under the concrete source type.
                _type_conversion_table[(source_type, T)] = convertor
                break

    if convertor is None:
        raise NotImplementedError(
            f"No conversion from {source_type.__name__} to {T.__name__}!"
        )
    return cast(Callable[["Convertible"], B], convertor)(self)

register_plot_method classmethod

register_plot_method(name: str, backend: str = 'plotly')

Register a backend plotting function for this plottable class.

The returned decorator stores the function in the global plotting registry. Registered functions receive the object being plotted as their first argument, followed by any extra positional and keyword arguments supplied to plot().

Parameters:

Name Type Description Default
name str

User-facing plot method name, such as scatter, structure, or heatmap.

required
backend str

Backend name that selects the implementation. The qten-plots extension currently uses plotly and matplotlib.

'plotly'

Returns:

Type Description
Callable

Decorator that registers the provided plotting function and returns it unchanged.

Source code in src/qten/plottings/_plottings.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@classmethod
def register_plot_method(cls, name: str, backend: str = "plotly"):
    """
    Register a backend plotting function for this plottable class.

    The returned decorator stores the function in the global plotting
    registry. Registered functions receive the object being plotted as their
    first argument, followed by any extra positional and keyword arguments
    supplied to [`plot()`][qten.plottings.Plottable.plot].

    Parameters
    ----------
    name : str
        User-facing plot method name, such as `scatter`, `structure`, or
        `heatmap`.
    backend : str
        Backend name that selects the implementation. The `qten-plots`
        extension currently uses `plotly` and `matplotlib`.

    Returns
    -------
    Callable
        Decorator that registers the provided plotting function and returns
        it unchanged.
    """

    def decorator(func: Callable):
        # We register against 'cls' - the class this method was called on.
        Plottable._registry[(cls, name, backend)] = func
        return func

    return decorator

plot

plot(method: str, backend: str = 'plotly', *args, **kwargs)

Dispatch a named plot method to a registered backend implementation.

The dispatcher first loads plotting entry points, then searches the instance type and its base classes for a matching (type, method, backend) registration. Additional arguments are forwarded unchanged to the selected backend function.

Parameters:

Name Type Description Default
method str

Plot method name registered for this object's type.

required
backend str

Backend implementation to use. The qten-plots extension currently registers plotly and matplotlib.

'plotly'
args

Positional arguments forwarded to the registered plotting function.

()
kwargs

Keyword arguments forwarded to the registered plotting function.

{}

Returns:

Type Description
object

Backend-specific figure object returned by the registered plotting function, such as a Plotly or Matplotlib figure.

Raises:

Type Description
ValueError

If no plotting function is registered for the requested method and backend on this object.

See Also

qten_plots.plottables.PointCloud Public plottable helper object provided by the plotting extension.

Source code in src/qten/plottings/_plottings.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def plot(self, method: str, backend: str = "plotly", *args, **kwargs):
    """
    Dispatch a named plot method to a registered backend implementation.

    The dispatcher first loads plotting entry points, then searches the
    instance type and its base classes for a matching `(type, method,
    backend)` registration. Additional arguments are forwarded unchanged to
    the selected backend function.

    Parameters
    ----------
    method : str
        Plot method name registered for this object's type.
    backend : str
        Backend implementation to use. The `qten-plots` extension currently
        registers `plotly` and `matplotlib`.
    args
        Positional arguments forwarded to the registered plotting function.
    kwargs
        Keyword arguments forwarded to the registered plotting function.

    Returns
    -------
    object
        Backend-specific figure object returned by the registered plotting
        function, such as a Plotly or Matplotlib figure.

    Raises
    ------
    ValueError
        If no plotting function is registered for the requested method and
        backend on this object.

    See Also
    --------
    qten_plots.plottables.PointCloud
        Public plottable helper object provided by the plotting extension.
    """
    Plottable._ensure_backends_loaded()

    # Iterate over the MRO (Method Resolution Order) of the instance
    for class_in_hierarchy in type(self).__mro__:
        key = (class_in_hierarchy, method, backend)

        # Check the central registry
        if key in Plottable._registry:
            plot_func = Plottable._registry[key]
            return plot_func(self, *args, **kwargs)

    # If we reach here, no method was found. Provide a helpful error.
    self._raise_method_not_found(method, backend)

__post_init__

__post_init__() -> None

Finalize construction after dataclass initialization.

If an at_device context is active for the current thread, this method moves data onto that forced device before the frozen dataclass instance escapes to user code. When no device-forcing context is active, construction is left unchanged.

Notes

Because Tensor is a frozen dataclass, the post-init device update uses object.__setattr__ to replace data in-place during initialization.

Source code in src/qten/linalg/tensors.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def __post_init__(self) -> None:
    """
    Finalize construction after dataclass initialization.

    If an [`at_device`][qten.linalg.tensors.at_device] context is active for the current thread, this method
    moves `data` onto that forced device before the frozen dataclass
    instance escapes to user code. When no device-forcing context is
    active, construction is left unchanged.

    Notes
    -----
    Because [`Tensor`][qten.linalg.tensors.Tensor] is a frozen dataclass, the post-init device update uses
    `object.__setattr__` to replace `data` in-place during initialization.
    """
    forced_device = _forced_tensor_device()
    if forced_device is None:
        return

    target = forced_device.torch_device()
    if self.data.device != target:
        object.__setattr__(self, "data", cast(T, self.data.to(target)))

scalar staticmethod

scalar(
    number: Scalar, *, device: Device | None = None
) -> Tensor

Create a 0-dimensional Tensor from a scalar number.

Parameters:

Name Type Description Default
number Number

The scalar value to convert into a tensor.

required
device Optional[Device]

Device to place the scalar on, by default None (CPU).

None

Returns:

Type Description
Tensor

A 0-dimensional tensor containing the given number.

Source code in src/qten/linalg/tensors.py
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
@staticmethod
def scalar(number: Number, *, device: Optional[Device] = None) -> "Tensor":
    """
    Create a 0-dimensional [`Tensor`][qten.linalg.tensors.Tensor] from a scalar number.

    Parameters
    ----------
    number : Number
        The scalar value to convert into a tensor.
    device : Optional[Device], optional
        Device to place the scalar on, by default None (CPU).

    Returns
    -------
    Tensor
        A 0-dimensional tensor containing the given number.
    """
    precision = get_precision_config()
    dtype = (
        precision.torch_complex
        if isinstance(number, complex)
        else precision.torch_float
    )
    torch_device = device.torch_device() if device is not None else None
    data = torch.tensor(number, dtype=dtype, device=torch_device)
    return Tensor(data=data, dims=())

astype

astype(dtype: dtype) -> Self

Return a new tensor with the same dims and converted data dtype.

This method delegates to astype(tensor, dtype), which applies tensor.data.to(dtype=...) to the underlying torch data.

See Also

astype(tensor, dtype) Functional form with the same behavior.

Parameters:

Name Type Description Default
dtype dtype

Target PyTorch dtype.

This must be a torch.dtype object such as torch.float32, torch.float64, torch.complex64, torch.complex128, torch.int64, or torch.bool. Any dtype accepted by torch.Tensor.to(dtype=...) is valid here.

required

Returns:

Type Description
Self

A new tensor of the same wrapper type whose data has dtype dtype.

Source code in src/qten/linalg/tensors.py
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
def astype(self, dtype: torch.dtype) -> Self:
    """
    Return a new tensor with the same dims and converted data dtype.

    This method delegates to [`astype(tensor, dtype)`][qten.linalg.tensors.astype],
    which applies `tensor.data.to(dtype=...)` to the underlying torch data.

    See Also
    --------
    [`astype(tensor, dtype)`][qten.linalg.tensors.astype]
        Functional form with the same behavior.

    Parameters
    ----------
    dtype : torch.dtype
        Target PyTorch dtype.

        This must be a [`torch.dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch-dtype)
        object such as `torch.float32`, `torch.float64`,
        `torch.complex64`, `torch.complex128`, `torch.int64`, or
        `torch.bool`. Any dtype accepted by
        `torch.Tensor.to(dtype=...)` is valid here.

    Returns
    -------
    Self
        A new tensor of the same wrapper type whose data has dtype `dtype`.
    """
    return astype(self, dtype)

equal

equal(other: Tensor) -> bool

Compare this tensor to another tensor for exact equality.

See Also

equal(a, b) Functional form with the full comparison semantics.

Behavior
  • Attempts to align other.dims to self.dims using align_all.
  • If dimension alignment is not possible, returns False.
  • If alignment succeeds, compares aligned data via torch.equal.

Parameters:

Name Type Description Default
other Tensor

The tensor to compare against this tensor.

required

Returns:

Type Description
bool

True if tensors are exactly equal after alignment; otherwise False.

Source code in src/qten/linalg/tensors.py
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
def equal(self, other: "Tensor") -> bool:
    """
    Compare this tensor to another tensor for exact equality.

    See Also
    --------
    [`equal(a, b)`][qten.linalg.tensors.equal]
        Functional form with the full comparison semantics.

    Behavior
    --------
    - Attempts to align `other.dims` to `self.dims` using `align_all`.
    - If dimension alignment is not possible, returns `False`.
    - If alignment succeeds, compares aligned data via `torch.equal`.

    Parameters
    ----------
    other : Tensor
        The tensor to compare against this tensor.

    Returns
    -------
    bool
        True if tensors are exactly equal after alignment; otherwise `False`.
    """
    return equal(self, other)

allclose

allclose(
    other: Tensor,
    rtol: float = 1e-05,
    atol: float = 1e-08,
    equal_nan: bool = False,
) -> bool

Compare this tensor to another tensor for approximate equality.

See Also

allclose(a, b, ...) Functional form with the full comparison semantics.

Behavior
  • Attempts to align other.dims to self.dims using align_all.
  • If dimension alignment is not possible, returns False.
  • If alignment succeeds, compares aligned data via torch.allclose.

Parameters:

Name Type Description Default
other Tensor

The tensor to compare against this tensor.

required
rtol float

Relative tolerance used by torch.allclose.

1e-05
atol float

Absolute tolerance used by torch.allclose.

1e-08
equal_nan bool

Whether NaN values are considered equal.

False

Returns:

Type Description
bool

True if tensors are close after alignment; otherwise False.

Source code in src/qten/linalg/tensors.py
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
def allclose(
    self,
    other: "Tensor",
    rtol: float = 1e-05,
    atol: float = 1e-08,
    equal_nan: bool = False,
) -> bool:
    """
    Compare this tensor to another tensor for approximate equality.

    See Also
    --------
    [`allclose(a, b, ...)`][qten.linalg.tensors.allclose]
        Functional form with the full comparison semantics.

    Behavior
    --------
    - Attempts to align `other.dims` to `self.dims` using `align_all`.
    - If dimension alignment is not possible, returns `False`.
    - If alignment succeeds, compares aligned data via `torch.allclose`.

    Parameters
    ----------
    other : Tensor
        The tensor to compare against this tensor.
    rtol : float, optional
        Relative tolerance used by `torch.allclose`.
    atol : float, optional
        Absolute tolerance used by `torch.allclose`.
    equal_nan : bool, optional
        Whether `NaN` values are considered equal.

    Returns
    -------
    bool
        True if tensors are close after alignment; otherwise `False`.
    """
    return allclose(self, other, rtol=rtol, atol=atol, equal_nan=equal_nan)

isclose

isclose(
    other: Tensor | Scalar,
    rtol: float = 1e-05,
    atol: float = 1e-08,
    equal_nan: bool = False,
) -> Self

Perform element-wise approximate equality comparison.

This is the mask-producing counterpart to allclose: it returns a bool Tensor instead of a Python bool.

Supported forms

tensor.isclose(other) Method form.

isclose(tensor, other) Functional equivalent.

Parameter forms

other : Tensor Compared after symbolic alignment and broadcast handling.

other : Number Promoted through Tensor.scalar(other) before applying the same comparison rules.

Parameters:

Name Type Description Default
other Tensor | Number

Comparison target. If other is a Tensor, it is aligned and broadcast against self. If other is a scalar number, it is promoted through Tensor.scalar(other) before comparison.

required
rtol float

Relative tolerance passed to torch.isclose.

1e-05
atol float

Absolute tolerance passed to torch.isclose.

1e-08
equal_nan bool

Whether NaN values are considered equal.

False

Returns:

Type Description
Self

Boolean tensor mask with the merged symbolic output dims.

See Also

isclose(a, b, ...) Functional form with the full behavior description.

Source code in src/qten/linalg/tensors.py
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
def isclose(
    self,
    other: Union["Tensor", Number],
    rtol: float = 1e-05,
    atol: float = 1e-08,
    equal_nan: bool = False,
) -> Self:
    """
    Perform element-wise approximate equality comparison.

    This is the mask-producing counterpart to `allclose`: it returns a bool
    [`Tensor`][qten.linalg.tensors.Tensor] instead of a Python bool.

    Supported forms
    ---------------
    [`tensor.isclose(other)`][qten.linalg.tensors.Tensor.isclose]
        Method form.

    [`isclose(tensor, other)`][qten.linalg.tensors.isclose]
        Functional equivalent.

    Parameter forms
    ---------------
    `other : Tensor`
        Compared after symbolic alignment and broadcast handling.

    `other : Number`
        Promoted through `Tensor.scalar(other)` before applying the same
        comparison rules.

    Parameters
    ----------
    other : Tensor | Number
        Comparison target. If `other` is a
        [`Tensor`][qten.linalg.tensors.Tensor], it is aligned and
        broadcast against `self`. If `other` is a scalar number, it is
        promoted through `Tensor.scalar(other)` before comparison.
    rtol : float, optional
        Relative tolerance passed to `torch.isclose`.
    atol : float, optional
        Absolute tolerance passed to `torch.isclose`.
    equal_nan : bool, optional
        Whether `NaN` values are considered equal.

    Returns
    -------
    Self
        Boolean tensor mask with the merged symbolic output dims.

    See Also
    --------
    [`isclose(a, b, ...)`][qten.linalg.tensors.isclose]
        Functional form with the full behavior description.
    """
    return isclose(self, other, rtol=rtol, atol=atol, equal_nan=equal_nan)

conj

conj() -> Self

Compute the complex conjugate of the given tensor.

See Also

conj(tensor) Functional form with the same behavior.

Returns:

Type Description
Self

The complex conjugate of the tensor.

Source code in src/qten/linalg/tensors.py
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
def conj(self) -> Self:
    """
    Compute the complex conjugate of the given tensor.

    See Also
    --------
    [`conj(tensor)`][qten.linalg.tensors.conj]
        Functional form with the same behavior.

    Returns
    -------
    Self
        The complex conjugate of the tensor.
    """
    return conj(self)

real

real() -> Self

Return the real part of the tensor, preserving dims.

For complex-valued tensors this drops the imaginary component. For real-valued tensors this returns a tensor with the same values.

See Also

real(tensor) Functional form with the same behavior.

Source code in src/qten/linalg/tensors.py
627
628
629
630
631
632
633
634
635
636
637
638
639
def real(self) -> Self:
    """
    Return the real part of the tensor, preserving dims.

    For complex-valued tensors this drops the imaginary component. For
    real-valued tensors this returns a tensor with the same values.

    See Also
    --------
    [`real(tensor)`][qten.linalg.tensors.real]
        Functional form with the same behavior.
    """
    return real(self)

imag

imag() -> Self

Return the imaginary part of the tensor, preserving dims.

For complex-valued tensors this returns the imaginary component. For real-valued tensors this returns zeros with the corresponding real dtype.

See Also

imag(tensor) Functional form with the same behavior.

Source code in src/qten/linalg/tensors.py
641
642
643
644
645
646
647
648
649
650
651
652
653
def imag(self) -> Self:
    """
    Return the imaginary part of the tensor, preserving dims.

    For complex-valued tensors this returns the imaginary component. For
    real-valued tensors this returns zeros with the corresponding real dtype.

    See Also
    --------
    [`imag(tensor)`][qten.linalg.tensors.imag]
        Functional form with the same behavior.
    """
    return imag(self)

abs

abs() -> Self

Return the element-wise absolute value / magnitude of the tensor.

For complex-valued tensors this returns the magnitude.

See Also

abs(tensor) Functional form with the same behavior.

Source code in src/qten/linalg/tensors.py
655
656
657
658
659
660
661
662
663
664
665
666
def abs(self) -> Self:
    """
    Return the element-wise absolute value / magnitude of the tensor.

    For complex-valued tensors this returns the magnitude.

    See Also
    --------
    [`abs(tensor)`][qten.linalg.tensors.abs]
        Functional form with the same behavior.
    """
    return abs(self)

permute

permute(*order: int | Sequence[int]) -> Self

Permute the dimensions according to the specified order.

See Also

permute(tensor, *order) Functional form with the full permutation semantics.

Parameters:

Name Type Description Default
order Union[int, Sequence[int]]

The desired order of dimensions.

()

Returns:

Type Description
Self

The permuted tensor.

Source code in src/qten/linalg/tensors.py
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
def permute(self, *order: Union[int, Sequence[int]]) -> Self:
    """
    Permute the dimensions according to the specified order.

    See Also
    --------
    [`permute(tensor, *order)`][qten.linalg.tensors.permute]
        Functional form with the full permutation semantics.

    Parameters
    ----------
    order : Union[int, Sequence[int]]
        The desired order of dimensions.

    Returns
    -------
    Self
        The permuted tensor.
    """
    return permute(self, *order)

transpose

transpose(dim0: int, dim1: int) -> Self

Transpose the specified dimensions.

See Also

transpose(tensor, dim0, dim1) Functional form with the full transpose semantics.

Parameters:

Name Type Description Default
dim0 int

The first dimension to transpose.

required
dim1 int

The second dimension to transpose.

required

Returns:

Type Description
Self

The transposed tensor.

Source code in src/qten/linalg/tensors.py
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
def transpose(self, dim0: int, dim1: int) -> Self:
    """
    Transpose the specified dimensions.

    See Also
    --------
    [`transpose(tensor, dim0, dim1)`][qten.linalg.tensors.transpose]
        Functional form with the full transpose semantics.

    Parameters
    ----------
    dim0 : int
        The first dimension to transpose.
    dim1 : int
        The second dimension to transpose.

    Returns
    -------
    Self
        The transposed tensor.
    """
    return transpose(self, dim0, dim1)

h

h(dim0: int, dim1: int) -> Self

Hermitian transpose (conjugate transpose) of the specified dimensions.

See Also

conj(tensor) transpose(tensor, dim0, dim1)

Parameters:

Name Type Description Default
dim0 int

The first dimension to transpose.

required
dim1 int

The second dimension to transpose.

required

Returns:

Type Description
Self

The Hermitian transposed tensor.

Source code in src/qten/linalg/tensors.py
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
def h(self, dim0: int, dim1: int) -> Self:
    """
    Hermitian transpose (conjugate transpose) of the specified dimensions.

    See Also
    --------
    [`conj(tensor)`][qten.linalg.tensors.conj]
    [`transpose(tensor, dim0, dim1)`][qten.linalg.tensors.transpose]

    Parameters
    ----------
    dim0 : int
        The first dimension to transpose.
    dim1 : int
        The second dimension to transpose.

    Returns
    -------
    Self
        The Hermitian transposed tensor.
    """
    return self.conj().transpose(dim0, dim1)

align

align(dim: int, target_dim: StateSpace) -> Self

Align the specified dimension to the target StateSpace.

Behavior

Delegates to align. This may:

  • leave the tensor unchanged if the axis already matches,
  • expand a broadcast axis to target_dim,
  • permute the axis if the same rays appear in a different order,
  • raise if the axis is not symbolically compatible with target_dim.
Use cases
  • reorder one axis to match another tensor before contraction,
  • materialize a broadcast axis as a concrete symbolic space.

Parameters:

Name Type Description Default
dim int

The dimension index to align.

required
target_dim StateSpace

The target StateSpace to align to.

required

Returns:

Type Description
Self

The aligned tensor.

See Also

align(tensor, dim, target_dim) Functional form with the full behavior description.

Source code in src/qten/linalg/tensors.py
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
def align(self, dim: int, target_dim: StateSpace) -> Self:
    """
    Align the specified dimension to the target StateSpace.

    Behavior
    --------
    Delegates to [`align`][qten.linalg.tensors.align]. This may:

    - leave the tensor unchanged if the axis already matches,
    - expand a broadcast axis to `target_dim`,
    - permute the axis if the same rays appear in a different order,
    - raise if the axis is not symbolically compatible with `target_dim`.

    Use cases
    ---------
    - reorder one axis to match another tensor before contraction,
    - materialize a broadcast axis as a concrete symbolic space.

    Parameters
    ----------
    dim : int
        The dimension index to align.
    target_dim : StateSpace
        The target StateSpace to align to.

    Returns
    -------
    Self
        The aligned tensor.

    See Also
    --------
    [`align(tensor, dim, target_dim)`][qten.linalg.tensors.align]
        Functional form with the full behavior description.
    """
    return align(self, dim, target_dim)

align_all

align_all(dims: tuple[StateSpace, ...]) -> Self

Align all tensor dimensions to dims.

Behavior

Delegates to align_all, aligning the tensor axis-by-axis to the requested symbolic layout.

Use cases
  • normalize one tensor to the metadata layout of another before comparison or arithmetic,
  • prepare a tensor for an API that expects a specific symbolic axis ordering.

Parameters:

Name Type Description Default
dims Tuple[StateSpace, ...]

The target dimensions to align to.

required

Returns:

Type Description
Self

The aligned tensor.

Raises:

Type Description
ValueError

If the provided dims are not compatible with the tensor's current dimensions.

See Also

align_all(tensor, dims) Functional form with the full behavior description.

Source code in src/qten/linalg/tensors.py
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
def align_all(self, dims: Tuple[StateSpace, ...]) -> Self:
    """
    Align all tensor dimensions to `dims`.

    Behavior
    --------
    Delegates to [`align_all`][qten.linalg.tensors.align_all], aligning the
    tensor axis-by-axis to the requested symbolic layout.

    Use cases
    ---------
    - normalize one tensor to the metadata layout of another before
      comparison or arithmetic,
    - prepare a tensor for an API that expects a specific symbolic axis
      ordering.

    Parameters
    ----------
    dims : Tuple[StateSpace, ...]
        The target dimensions to align to.

    Returns
    -------
    Self
        The aligned tensor.

    Raises
    ------
    ValueError
        If the provided `dims` are not compatible with the tensor's current dimensions.

    See Also
    --------
    [`align_all(tensor, dims)`][qten.linalg.tensors.align_all]
        Functional form with the full behavior description.
    """
    return align_all(self, dims)

all

all(
    dim: int | tuple[int, ...] | None = None,
    keepdim: bool = False,
) -> Self

Return whether all elements evaluate to True.

Parameters:

Name Type Description Default
dim Optional[Union[int, Tuple[int, ...]]]

Reduction axis (or axes). If None, reduce over all dimensions.

None
keepdim bool

If True, retains the reduced axis as BroadcastSpace.

False

Returns:

Type Description
Self

Boolean tensor after reduction.

See Also

all(tensor, dim=None, keepdim=False) Functional form with the full reduction semantics.

Source code in src/qten/linalg/tensors.py
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
def all(
    self, dim: Optional[Union[int, Tuple[int, ...]]] = None, keepdim: bool = False
) -> Self:
    """
    Return whether all elements evaluate to `True`.

    Parameters
    ----------
    dim : Optional[Union[int, Tuple[int, ...]]], optional
        Reduction axis (or axes). If `None`, reduce over all dimensions.
    keepdim : bool, optional
        If `True`, retains the reduced axis as [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace].

    Returns
    -------
    Self
        Boolean tensor after reduction.

    See Also
    --------
    [`all(tensor, dim=None, keepdim=False)`][qten.linalg.tensors.all]
        Functional form with the full reduction semantics.
    """
    return all(self, dim=dim, keepdim=keepdim)

where

where(
    input: Tensor,
    other: Tensor,
    index_type: type[Any] = ...,
) -> Tensor
where(
    input: None = None,
    other: None = None,
    index_type: type[Tensor[Any]] = ...,
) -> tuple[Tensor, ...]
where(
    input: None = None,
    other: None = None,
    index_type: type[tuple] = tuple,
) -> tuple[tuple[int, ...], ...]
where(
    input: None = None,
    other: None = None,
    index_type: type[StateSpace[Any]] = StateSpace,
) -> StateSpace[Any]
where(
    input: Tensor | None = None,
    other: Tensor | None = None,
    index_type: type[Any] = ...,
) -> (
    Tensor
    | tuple[Tensor, ...]
    | tuple[tuple[int, ...], ...]
    | StateSpace[Any]
)

Apply where using this tensor as the boolean condition mask.

Supported call forms
  • condition.where(input, other): elementwise selection between input and other.
  • condition.where(): returns index tensors of True entries.
  • condition.where(index_type=...): returns the requested index representation for True entries.
Semantics

This method requires condition.data.dtype == torch.bool.

For condition.where(input, other): - condition, input, and other are promoted to a common rank by prepending leading BroadcastSpace axes as needed. - metadata is merged with union_dims(condition.dims, input.dims, other.dims, allow_merge=False). - all three operands are aligned to those merged dims and broadcast-expanded. - selection is then applied elementwise with torch.where.

For condition.where() and condition.where(index_type=...): - behavior follows torch.where(condition) / torch.nonzero(condition, as_tuple=True). - for a rank-R mask, the Tensor form returns R one-dimensional index tensors, one per axis. - each returned Tensor index uses IndexSpace.linear(nnz), where nnz is the number of True entries.

Parameters:

Name Type Description Default
input Optional[Tensor]

Tensor selected where condition is True in the selection form condition.where(input, other).

None
other Optional[Tensor]

Tensor selected where condition is False in the selection form condition.where(input, other).

None
index_type Type[Any]

Only used for the condition-only form condition.where(...).

Supported values are Tensor to return one rank-1 integer tensor per axis, tuple / Tuple to return Python coordinate tuples, and StateSpace to return the selected symbolic subspace for rank-1 conditions.

None

Returns:

Type Description
Union[Tensor, Tuple[Tensor, ...], Tuple[Tuple[int, ...], ...], StateSpace]

Return value depends on call form. condition.where(input, other) returns a single Tensor with dims == union_dims(condition.dims, input.dims, other.dims, allow_merge=False), after all operands are aligned and broadcast. condition.where() and condition.where(index_type=Tensor) return Tuple[Tensor, ...] with one rank-1 index tensor per condition axis, each with dims (IndexSpace.linear(nnz),). Using index_type=tuple or Tuple returns one Python coordinate tuple per True entry. Using index_type=StateSpace returns the selected subspace for rank-1 conditions only.

Raises:

Type Description
TypeError

If condition.data is not boolean, if only one of input/other is provided, or if index_type is passed together with input/other.

ValueError

If operands cannot be aligned/broadcast to shared union dims, or if index_type=StateSpace is requested for a non-rank-1 mask.

See Also

where(...) Functional form with the full supported-form documentation.

Source code in src/qten/linalg/tensors.py
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
def where(
    self,
    input: Optional["Tensor"] = None,
    other: Optional["Tensor"] = None,
    index_type: Type[Any] = None,
) -> Union[
    "Tensor",
    Tuple["Tensor", ...],
    Tuple[Tuple[int, ...], ...],
    StateSpace,
]:
    """
    Apply `where` using this tensor as the boolean condition mask.

    Supported call forms
    --------------------
    - `condition.where(input, other)`:
      elementwise selection between `input` and `other`.
    - `condition.where()`:
      returns index tensors of `True` entries.
    - `condition.where(index_type=...)`:
      returns the requested index representation for `True` entries.

    Semantics
    ---------
    This method requires `condition.data.dtype == torch.bool`.

    For `condition.where(input, other)`:
    - `condition`, `input`, and `other` are promoted to a common rank by
      prepending leading [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace] axes as needed.
    - metadata is merged with
      [`union_dims(condition.dims, input.dims, other.dims, allow_merge=False)`][qten.linalg.tensors.union_dims].
    - all three operands are aligned to those merged dims and broadcast-expanded.
    - selection is then applied elementwise with `torch.where`.

    For `condition.where()` and `condition.where(index_type=...)`:
    - behavior follows `torch.where(condition)` /
      `torch.nonzero(condition, as_tuple=True)`.
    - for a rank-`R` mask, the Tensor form returns `R` one-dimensional
      index tensors, one per axis.
    - each returned Tensor index uses `IndexSpace.linear(nnz)`, where
      `nnz` is the number of `True` entries.

    Parameters
    ----------
    input : Optional[Tensor], optional
        Tensor selected where `condition` is `True` in the selection form
        `condition.where(input, other)`.
    other : Optional[Tensor], optional
        Tensor selected where `condition` is `False` in the selection form
        `condition.where(input, other)`.
    index_type : Type[Any], optional
        Only used for the condition-only form `condition.where(...)`.

        Supported values are
        [`Tensor`][qten.linalg.tensors.Tensor] to return one rank-1
        integer tensor per axis, `tuple` / `Tuple` to return Python
        coordinate tuples, and
        [`StateSpace`][qten.symbolics.state_space.StateSpace] to return the
        selected symbolic subspace for rank-1 conditions.

    Returns
    -------
    Union[Tensor, Tuple[Tensor, ...], Tuple[Tuple[int, ...], ...], StateSpace]
        Return value depends on call form. `condition.where(input, other)`
        returns a single [`Tensor`][qten.linalg.tensors.Tensor] with
        `dims == union_dims(condition.dims, input.dims, other.dims,
        allow_merge=False)`, after all operands are aligned and broadcast.
        `condition.where()` and `condition.where(index_type=Tensor)` return
        `Tuple[Tensor, ...]` with one rank-1 index tensor per condition
        axis, each with dims `(IndexSpace.linear(nnz),)`. Using
        `index_type=tuple` or `Tuple` returns one Python coordinate tuple
        per `True` entry. Using `index_type=StateSpace` returns the
        selected subspace for rank-1 conditions only.

    Raises
    ------
    TypeError
        If `condition.data` is not boolean, if only one of `input`/`other`
        is provided, or if `index_type` is passed together with
        input/`other`.
    ValueError
        If operands cannot be aligned/broadcast to shared union dims, or if
        index_type=StateSpace is requested for a non-rank-1 mask.

    See Also
    --------
    [`where(...)`][qten.linalg.tensors.where]
        Functional form with the full supported-form documentation.
    """
    if index_type is None:
        index_type = Tensor
    if input is None and other is None:
        return where(self, index_type=index_type)
    if input is None or other is None:
        raise TypeError(
            "Tensor.where supports either where() or where(input, other)"
        )
    if index_type is not Tensor:
        raise TypeError("index_type is only supported for where()")
    return where(self, input, other)

nonzero

nonzero(
    as_tuple: bool = True,
    index_type: type[Tensor[Any]] = ...,
) -> tuple[Tensor, ...]
nonzero(
    as_tuple: bool = True, index_type: type[tuple] = tuple
) -> tuple[tuple[int, ...], ...]
nonzero(
    as_tuple: bool = True,
    index_type: type[StateSpace[Any]] = StateSpace,
) -> StateSpace[Any]
nonzero(
    as_tuple: bool = True, index_type: type[Any] = ...
) -> (
    tuple[Tensor, ...]
    | tuple[tuple[int, ...], ...]
    | StateSpace[Any]
)

Return indices of non-zero / True entries for this tensor.

Currently supports only as_tuple=True, matching torch.nonzero(..., as_tuple=True).

Parameters:

Name Type Description Default
as_tuple bool

Must be True.

True
index_type Type[Any]

Requested index representation. Supported values are Tensor to return one rank-1 integer tensor per axis, tuple / Tuple to return Python coordinate tuples, and StateSpace to return the selected symbolic subspace for rank-1 conditions.

None

Returns:

Type Description
Union[Tuple[Tensor, ...], Tuple[Tuple[int, ...], ...], StateSpace]

Index representation selected by index_type.

Raises:

Type Description
NotImplementedError

If as_tuple is False.

See Also

nonzero(condition, ...) Functional form with the full supported-form documentation.

Source code in src/qten/linalg/tensors.py
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
def nonzero(
    self, as_tuple: bool = True, index_type: Type[Any] = None
) -> Union[
    Tuple["Tensor", ...],
    Tuple[Tuple[int, ...], ...],
    StateSpace,
]:
    """
    Return indices of non-zero / `True` entries for this tensor.

    Currently supports only `as_tuple=True`, matching
    `torch.nonzero(..., as_tuple=True)`.

    Parameters
    ----------
    as_tuple : bool, optional
        Must be `True`.
    index_type : Type[Any], optional
        Requested index representation. Supported values are
        [`Tensor`][qten.linalg.tensors.Tensor] to return one rank-1
        integer tensor per axis, `tuple` / `Tuple` to return Python
        coordinate tuples, and
        [`StateSpace`][qten.symbolics.state_space.StateSpace] to return the
        selected symbolic subspace for rank-1 conditions.

    Returns
    -------
    Union[Tuple[Tensor, ...], Tuple[Tuple[int, ...], ...], StateSpace]
        Index representation selected by `index_type`.

    Raises
    ------
    NotImplementedError
        If `as_tuple` is `False`.

    See Also
    --------
    [`nonzero(condition, ...)`][qten.linalg.tensors.nonzero]
        Functional form with the full supported-form documentation.
    """
    if index_type is None:
        index_type = Tensor
    return nonzero(self, as_tuple=as_tuple, index_type=index_type)

unsqueeze

unsqueeze(dim: int) -> Self

Unsqueeze the specified dimension.

See Also

unsqueeze(tensor, dim) Functional form with the full behavior description.

Parameters:

Name Type Description Default
dim int

The dimension to unsqueeze.

required

Returns:

Type Description
Self

The unsqueezed tensor.

Source code in src/qten/linalg/tensors.py
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
def unsqueeze(self, dim: int) -> Self:
    """
    Unsqueeze the specified dimension.

    See Also
    --------
    [`unsqueeze(tensor, dim)`][qten.linalg.tensors.unsqueeze]
        Functional form with the full behavior description.

    Parameters
    ----------
    dim : int
        The dimension to unsqueeze.

    Returns
    -------
    Self
        The unsqueezed tensor.
    """
    return unsqueeze(self, dim)

squeeze

squeeze(dim: int) -> Self

Squeeze the specified dimension.

See Also

squeeze(tensor, dim) Functional form with the full behavior description.

Parameters:

Name Type Description Default
dim int

The dimension to squeeze.

required

Returns:

Type Description
Self

The squeezed tensor.

Source code in src/qten/linalg/tensors.py
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
def squeeze(self, dim: int) -> Self:
    """
    Squeeze the specified dimension.

    See Also
    --------
    [`squeeze(tensor, dim)`][qten.linalg.tensors.squeeze]
        Functional form with the full behavior description.

    Parameters
    ----------
    dim : int
        The dimension to squeeze.

    Returns
    -------
    Self
        The squeezed tensor.
    """
    return squeeze(self, dim)

index_add

index_add(
    dim: int,
    index: Tensor[Any],
    source: Tensor,
    alpha: int | float | complex = 1,
) -> Self

Return a copy of this tensor with indexed additions applied along dim.

Parameters:

Name Type Description Default
dim int

Dimension along which to accumulate updates.

required
index Tensor

Rank-1 integer tensor of destination indices. Its single StateSpace defines the symbolic order of the updates.

required
source Tensor

Tensor of update values. It must have the same rank as self.

required
alpha Union[int, float, complex]

Scalar multiplier applied to source before accumulation.

1
Alignment rules
  • index must be a rank-1 integer tensor.
  • source must have the same rank as self.
  • On non-indexed axes, source is aligned to self.
  • On the indexed axis, source is aligned to index.dims[0], so the source rows or blocks follow the same symbolic order as the index list.

Returns:

Type Description
Self

A new tensor with the same dimensions as self.

See Also

index_add(tensor, dim, index, source, alpha=1) Functional form with the full behavior description.

Source code in src/qten/linalg/tensors.py
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
def index_add(
    self,
    dim: int,
    index: "Tensor[Any]",
    source: "Tensor",
    alpha: Union[int, float, complex] = 1,
) -> Self:
    """
    Return a copy of this tensor with indexed additions applied along `dim`.

    Parameters
    ----------
    dim : int
        Dimension along which to accumulate updates.
    index : Tensor
        Rank-1 integer tensor of destination indices. Its single
        [`StateSpace`][qten.symbolics.state_space.StateSpace] defines the symbolic order of the updates.
    source : Tensor
        Tensor of update values. It must have the same rank as `self`.
    alpha : Union[int, float, complex], optional
        Scalar multiplier applied to `source` before accumulation.

    Alignment rules
    ---------------
    - `index` must be a rank-1 integer tensor.
    - `source` must have the same rank as `self`.
    - On non-indexed axes, `source` is aligned to `self`.
    - On the indexed axis, `source` is aligned to `index.dims[0]`, so the
      source rows or blocks follow the same symbolic order as the index
      list.

    Returns
    -------
    Self
        A new tensor with the same dimensions as `self`.

    See Also
    --------
    [`index_add(tensor, dim, index, source, alpha=1)`][qten.linalg.tensors.index_add]
        Functional form with the full behavior description.
    """
    return index_add(self, dim=dim, index=index, source=source, alpha=alpha)

index_add_

index_add_(
    dim: int,
    index: Tensor[Any],
    source: Tensor,
    alpha: int | float | complex = 1,
) -> Self

In-place variant of index_add.

Parameters:

Name Type Description Default
dim int

Dimension along which to accumulate updates.

required
index Tensor

Rank-1 integer tensor of destination indices.

required
source Tensor

Tensor of update values. It must have the same rank as self.

required
alpha Union[int, float, complex]

Scalar multiplier applied to source before accumulation.

1

Returns:

Type Description
Self

This tensor after in-place accumulation.

See Also

index_add_(tensor, dim, index, source, alpha=1) Functional in-place form with the full behavior description.

Source code in src/qten/linalg/tensors.py
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
def index_add_(
    self,
    dim: int,
    index: "Tensor[Any]",
    source: "Tensor",
    alpha: Union[int, float, complex] = 1,
) -> Self:
    """
    In-place variant of `index_add`.

    Parameters
    ----------
    dim : int
        Dimension along which to accumulate updates.
    index : Tensor
        Rank-1 integer tensor of destination indices.
    source : Tensor
        Tensor of update values. It must have the same rank as `self`.
    alpha : Union[int, float, complex], optional
        Scalar multiplier applied to `source` before accumulation.

    Returns
    -------
    Self
        This tensor after in-place accumulation.

    See Also
    --------
    [`index_add_(tensor, dim, index, source, alpha=1)`][qten.linalg.tensors.index_add_]
        Functional in-place form with the full behavior description.
    """
    return index_add_(self, dim=dim, index=index, source=source, alpha=alpha)

rank

rank() -> int

Get the rank (number of dimensions) of the tensor.

See Also

rank(tensor) Functional form.

Returns:

Type Description
int

The rank of the tensor.

Source code in src/qten/linalg/tensors.py
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
def rank(self) -> int:
    """
    Get the rank (number of dimensions) of the tensor.

    See Also
    --------
    [`rank(tensor)`][qten.linalg.tensors.rank]
        Functional form.

    Returns
    -------
    int
        The rank of the tensor.
    """
    return rank(self)

mean

mean(dim: int | tuple[int, ...] | None = None) -> Self

Compute the mean over specified dimension(s).

See Also

mean(tensor, dim=None) Functional form with the full reduction semantics.

Parameters:

Name Type Description Default
dim Optional[Union[int, Tuple[int, ...]]]

Reduction axis (or axes). If None, reduce over all dimensions.

None

Returns:

Type Description
Self

A new tensor with the specified dimensions reduced.

Source code in src/qten/linalg/tensors.py
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
def mean(self, dim: Optional[Union[int, Tuple[int, ...]]] = None) -> Self:
    """
    Compute the mean over specified dimension(s).

    See Also
    --------
    [`mean(tensor, dim=None)`][qten.linalg.tensors.mean]
        Functional form with the full reduction semantics.

    Parameters
    ----------
    dim : Optional[Union[int, Tuple[int, ...]]], optional
        Reduction axis (or axes). If `None`, reduce over all dimensions.

    Returns
    -------
    Self
        A new tensor with the specified dimensions reduced.
    """
    return mean(self, dim)

norm

norm(
    ord: int | float | str | None = None,
    dim: int | tuple[int, int] | None = None,
) -> Self

Compute a vector or matrix norm over the specified dimension(s).

This method delegates to norm(tensor, ord=None, dim=None), which in turn forwards the numeric computation to torch.linalg.norm.

Supported ord values

The accepted values depend on whether dim selects a vector norm or a matrix norm:

  • dim is an int: vector norm. Supported ord values include None, 0, any finite int or float, float("inf"), and -float("inf").
  • dim is a 2-tuple: matrix norm. Supported ord values include None, "fro", "nuc", 1, -1, 2, -2, float("inf"), and -float("inf").
  • dim is None: PyTorch decides whether to interpret the input as a flattened vector or as a 1D/2D tensor norm depending on ord. See the linked torch.linalg.norm reference for the exact dispatch rules.

Parameters:

Name Type Description Default
ord Optional[Union[int, float, str]]

Norm order forwarded to torch.linalg.norm.

Common choices are None for the default norm chosen by PyTorch, 2 for the Euclidean vector norm or spectral matrix norm, 1 for an L1 vector norm or induced 1 matrix norm, float("inf") for max-based norms, "fro" for the Frobenius matrix norm, and "nuc" for the nuclear matrix norm.

None
dim Optional[Union[int, Tuple[int, int]]]

Reduction axis or axes. Use an int to compute a vector norm along one axis, a Tuple[int, int] to compute a matrix norm over two axes, or None to let PyTorch use its default torch.linalg.norm semantics.

None

Returns:

Type Description
Self

A new tensor with the specified dimensions reduced.

See Also

norm(tensor, ord=None, dim=None) Functional form with the full reduction semantics.

Source code in src/qten/linalg/tensors.py
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
def norm(
    self,
    ord: Optional[Union[int, float, str]] = None,
    dim: Optional[Union[int, Tuple[int, int]]] = None,
) -> Self:
    """
    Compute a vector or matrix norm over the specified dimension(s).

    This method delegates to [`norm(tensor, ord=None, dim=None)`][qten.linalg.tensors.norm],
    which in turn forwards the numeric computation to
    [`torch.linalg.norm`](https://docs.pytorch.org/docs/stable/generated/torch.linalg.norm.html).

    Supported `ord` values
    ----------------------
    The accepted values depend on whether `dim` selects a vector norm or a
    matrix norm:

    - `dim` is an `int`: vector norm.
      Supported `ord` values include `None`, `0`, any finite `int` or
      `float`, `float("inf")`, and `-float("inf")`.
    - `dim` is a 2-tuple: matrix norm.
      Supported `ord` values include `None`, `"fro"`, `"nuc"`, `1`, `-1`,
      `2`, `-2`, `float("inf")`, and `-float("inf")`.
    - `dim is None`:
      PyTorch decides whether to interpret the input as a flattened vector
      or as a 1D/2D tensor norm depending on `ord`. See the linked
      `torch.linalg.norm` reference for the exact dispatch rules.

    Parameters
    ----------
    ord : Optional[Union[int, float, str]], optional
        Norm order forwarded to `torch.linalg.norm`.

        Common choices are `None` for the default norm chosen by PyTorch,
        `2` for the Euclidean vector norm or spectral matrix norm, `1` for
        an L1 vector norm or induced 1 matrix norm, `float("inf")` for
        max-based norms, `"fro"` for the Frobenius matrix norm, and
        `"nuc"` for the nuclear matrix norm.
    dim : Optional[Union[int, Tuple[int, int]]], optional
        Reduction axis or axes. Use an `int` to compute a vector norm along
        one axis, a `Tuple[int, int]` to compute a matrix norm over two
        axes, or `None` to let PyTorch use its default
        `torch.linalg.norm` semantics.

    Returns
    -------
    Self
        A new tensor with the specified dimensions reduced.

    See Also
    --------
    [`norm(tensor, ord=None, dim=None)`][qten.linalg.tensors.norm]
        Functional form with the full reduction semantics.
    """
    return norm(self, ord=ord, dim=dim)

argmax

argmax(dim: int) -> Self

Compute the indices of the maximum values over a specified dimension.

See Also

argmax(tensor, dim) Functional form with the full reduction semantics.

Parameters:

Name Type Description Default
dim int

The dimension to reduce.

required

Returns:

Type Description
Self

A new tensor with the specified dimension reduced.

Source code in src/qten/linalg/tensors.py
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
def argmax(self, dim: int) -> Self:
    """
    Compute the indices of the maximum values over a specified dimension.

    See Also
    --------
    [`argmax(tensor, dim)`][qten.linalg.tensors.argmax]
        Functional form with the full reduction semantics.

    Parameters
    ----------
    dim : int
        The dimension to reduce.

    Returns
    -------
    Self
        A new tensor with the specified dimension reduced.
    """
    return argmax(self, dim)

argmin

argmin(dim: int) -> Self

Compute the indices of the minimum values over a specified dimension.

See Also

argmin(tensor, dim) Functional form with the full reduction semantics.

Parameters:

Name Type Description Default
dim int

The dimension to reduce.

required

Returns:

Type Description
Self

A new tensor with the specified dimension reduced.

Source code in src/qten/linalg/tensors.py
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
def argmin(self, dim: int) -> Self:
    """
    Compute the indices of the minimum values over a specified dimension.

    See Also
    --------
    [`argmin(tensor, dim)`][qten.linalg.tensors.argmin]
        Functional form with the full reduction semantics.

    Parameters
    ----------
    dim : int
        The dimension to reduce.

    Returns
    -------
    Self
        A new tensor with the specified dimension reduced.
    """
    return argmin(self, dim)

expand_to_union

expand_to_union(union_dims: list[StateSpace]) -> Self

Expand the tensor to the union of the specified dimensions.

See Also

expand_to_union(tensor, union_dims) Functional form with the full broadcast-expansion semantics.

Parameters:

Name Type Description Default
union_dims list[StateSpace]

The dimensions to expand to the union of.

required

Returns:

Type Description
Self

The expanded tensor.

Source code in src/qten/linalg/tensors.py
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
def expand_to_union(self, union_dims: list[StateSpace]) -> Self:
    """
    Expand the tensor to the union of the specified dimensions.

    See Also
    --------
    [`expand_to_union(tensor, union_dims)`][qten.linalg.tensors.expand_to_union]
        Functional form with the full broadcast-expansion semantics.

    Parameters
    ----------
    union_dims : list[StateSpace]
        The dimensions to expand to the union of.

    Returns
    -------
    Self
        The expanded tensor.
    """
    return expand_to_union(self, union_dims)

item

item() -> Scalar

Return the value of a 0-dimensional tensor as a standard Python number.

Returns:

Type Description
number

The value of the tensor.

Raises:

Type Description
ValueError

If the tensor is not 0-dimensional.

Source code in src/qten/linalg/tensors.py
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
def item(self) -> Union[Number, int, float]:
    """
    Return the value of a 0-dimensional tensor as a standard Python number.

    Returns
    -------
    number
        The value of the tensor.

    Raises
    ------
    ValueError
        If the tensor is not 0-dimensional.
    """
    if self.rank() != 0:
        raise ValueError(
            f"Tensor.item() only works for rank-0 tensors, got rank {self.rank()}"
        )
    return self.data.item()

to_device

to_device(device: Device) -> Self

Copy the tensor data to the specified logical device and return a new tensor.

Source code in src/qten/linalg/tensors.py
1296
1297
1298
1299
1300
1301
1302
1303
1304
@override
def to_device(self, device: Device) -> Self:
    """
    Copy the tensor data to the specified logical device and return a new tensor.
    """
    target = device.torch_device()
    if self.data.device == target:
        return self
    return replace(self, data=cast(T, self.data.to(target)))

backward

backward(
    gradient: Self | None = None,
    retain_graph: bool | None = None,
    create_graph: bool = False,
    inputs: Sequence[Self] | None = None,
) -> None

Run autograd backward from this tensor.

Parameters:

Name Type Description Default
gradient Optional[Self]

Upstream gradient for non-scalar tensors.

None
retain_graph Optional[bool]

Whether to retain the autograd graph after backward.

None
create_graph bool

Whether to construct the derivative graph.

False
inputs Optional[Sequence[Self]]

Restrict gradient accumulation to the specified leaf inputs.

None
Source code in src/qten/linalg/tensors.py
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
def backward(
    self,
    gradient: Optional[Self] = None,
    retain_graph: Optional[bool] = None,
    create_graph: bool = False,
    inputs: Optional[Sequence[Self]] = None,
) -> None:
    """
    Run autograd backward from this tensor.

    Parameters
    ----------
    gradient : Optional[Self], optional
        Upstream gradient for non-scalar tensors.
    retain_graph : Optional[bool], optional
        Whether to retain the autograd graph after backward.
    create_graph : bool, optional
        Whether to construct the derivative graph.
    inputs : Optional[Sequence[Self]], optional
        Restrict gradient accumulation to the specified leaf inputs.
    """
    grad_data = gradient.align_all(self.dims).data if gradient is not None else None
    input_data = [tensor.data for tensor in inputs] if inputs is not None else None
    self.data.backward(
        gradient=grad_data,
        retain_graph=retain_graph,
        create_graph=create_graph,
        inputs=input_data,
    )

attach

attach() -> Self

Enable gradient tracking for the tensor data and return the attached Tensor instance.

Behavior
  • If requires_grad is already True, this returns self unchanged.
  • Otherwise, this detaches the underlying data from any existing autograd graph, clones it to ensure a fresh leaf tensor, and sets requires_grad to True.
  • The returned tensor preserves the original dims, device, and dtype.

Returns:

Type Description
Self

The new tensor of the same wrapper type with gradient tracking enabled.

Source code in src/qten/linalg/tensors.py
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
def attach(self) -> Self:
    """
    Enable gradient tracking for the tensor data and return the attached [`Tensor`][qten.linalg.tensors.Tensor] instance.

    Behavior
    --------
    - If [`requires_grad`][qten.linalg.tensors.Tensor.requires_grad] is already `True`, this returns `self` unchanged.
    - Otherwise, this detaches the underlying data from any existing autograd graph,
      clones it to ensure a fresh leaf tensor, and sets [`requires_grad`][qten.linalg.tensors.Tensor.requires_grad] to `True`.
    - The returned tensor preserves the original `dims`, device, and dtype.

    Returns
    -------
    Self
        The new tensor of the same wrapper type with gradient tracking enabled.
    """
    if self.data.requires_grad:
        return self
    return replace(
        self,
        data=cast(T, self.data.detach().clone().requires_grad_(True)),
    )

detach

detach() -> Self

Disable gradient tracking for the tensor data and create a new Tensor instance.

Behavior
  • Always returns a new Tensor whose data is a detached view of the original tensor (no clone), so it shares storage with the original.
  • The returned tensor preserves the original dims, device, and dtype.

Returns:

Type Description
Self

The new tensor of the same wrapper type with gradient tracking disabled.

Source code in src/qten/linalg/tensors.py
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
def detach(self) -> Self:
    """
    Disable gradient tracking for the tensor data and create a new [`Tensor`][qten.linalg.tensors.Tensor] instance.

    Behavior
    --------
    - Always returns a new [`Tensor`][qten.linalg.tensors.Tensor] whose data is a detached view of the
      original tensor (no clone), so it shares storage with the original.
    - The returned tensor preserves the original `dims`, device, and dtype.

    Returns
    -------
    Self
        The new tensor of the same wrapper type with gradient tracking disabled.
    """
    return replace(self, data=cast(T, self.data.detach()))

clone

clone() -> Self

Create a deep copy of the tensor.

Returns:

Type Description
Self

The cloned tensor.

Source code in src/qten/linalg/tensors.py
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
def clone(self) -> Self:
    """
    Create a deep copy of the tensor.

    Returns
    -------
    Self
        The cloned tensor.
    """
    return replace(self, data=cast(T, self.data.clone()))

replace_dim

replace_dim(dim: int, new_dim: StateSpace) -> Self

Replace the StateSpace at the specified dimension with a new StateSpace.

See Also

replace_dim(tensor, dim, new_dim) Functional form with the full metadata replacement semantics.

Parameters:

Name Type Description Default
dim int

The index of the dimension to replace.

required
new_dim StateSpace

The new StateSpace to assign to the dimension.

required

Returns:

Type Description
Self

A new tensor of the same wrapper type with the updated dimension.

Source code in src/qten/linalg/tensors.py
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
def replace_dim(self, dim: int, new_dim: StateSpace) -> Self:
    """
    Replace the StateSpace at the specified dimension with a new StateSpace.

    See Also
    --------
    [`replace_dim(tensor, dim, new_dim)`][qten.linalg.tensors.replace_dim]
        Functional form with the full metadata replacement semantics.

    Parameters
    ----------
    dim : int
        The index of the dimension to replace.
    new_dim : StateSpace
        The new StateSpace to assign to the dimension.

    Returns
    -------
    Self
        A new tensor of the same wrapper type with the updated dimension.
    """
    return replace_dim(self, dim, new_dim)

__getitem__

__getitem__(key)

Index tensor data with TensorIndexing and return a new Tensor.

Parameters:

Name Type Description Default
key Any

Index expression accepted by QTen tensor indexing. Supported tokens include Python integers, slices, None, ..., StateSpace objects, Convertible objects that can be converted to StateSpace, and QTen Tensor index tensors.

required

Returns:

Type Description
Tensor

A new tensor with indexed data and output metadata compiled from the provided key.

Index normalization
  • A non-tuple key is treated as a 1-tuple.
  • At most one ellipsis (...) is allowed.
  • ... expands to the required number of full slices (:) based on source-axis-consuming tokens (all non-None entries).
  • If fewer source-axis-consuming indices are provided than rank, missing trailing full slices (:) are appended.
Per-token semantics
  • int: selects one element along the current source axis and removes that output dimension.
  • slice:
  • full slice : preserves the current StateSpace,
  • non-full slice uses self.dims[axis][slice], except BroadcastSpace axes where metadata follows sliced size: size 1 keeps BroadcastSpace, size 0 becomes IndexSpace.linear(0).
  • None: inserts a new output axis with BroadcastSpace and does not consume a source axis.
  • StateSpace / Convertible:
  • indexing a BroadcastSpace axis with any non-BroadcastSpace StateSpace is rejected (IndexError),
  • if equal to current axis space: behaves like full slice,
  • if same span: uses permutation indexing and output dim is the index StateSpace,
  • if contained subspace: uses embedding indexing and output dim is the subspace,
  • otherwise raises IndexError.
  • Tensor index:
  • bool dtype is not supported (NotImplementedError),
  • lower-rank tensor indices are left-padded with singleton/broadcast axes to match the maximum tensor-index rank before metadata union/alignment,
  • index metadata is aligned to the union of all tensor-index dims.
Mode rules
  • Mixing Tensor indices with StateSpace/Convertible indices is rejected (ValueError).
  • If at least one Tensor index is present, data indexing is executed in one torch advanced-indexing call.
  • Otherwise indexing is applied step-by-step per axis (including tuple index_select steps), so per-axis StateSpace tuple indices are not jointly broadcast by torch.
Output dim ordering for tensor advanced indexing

Let tensor_union_dims be the broadcast/union dims of all tensor index tensors. - If tensor index tokens form one contiguous block in the normalized key, tensor_union_dims is inserted at that block position. - If tensor index tokens are separated by non-tensor tokens, tensor_union_dims is moved to the front of output dims.

Raises:

Type Description
IndexError

If the key contains too many indices, incompatible StateSpace metadata, or more than one ellipsis.

ValueError

If tensor indices are mixed with StateSpace / Convertible indices in one indexing operation.

NotImplementedError

If boolean tensor indices are used in a mode that QTen does not support through __getitem__.

Notes

This method delegates key analysis to TensorIndexing. When advanced tensor indexing is present, indexing is executed in one torch call. In all other cases, indexing is applied step-by-step so QTen can preserve per-axis StateSpace semantics.

Source code in src/qten/linalg/tensors.py
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
def __getitem__(self, key):
    """
    Index tensor data with [`TensorIndexing`][qten.linalg.tensors.TensorIndexing] and return a new [`Tensor`][qten.linalg.tensors.Tensor].

    Parameters
    ----------
    key : Any
        Index expression accepted by QTen tensor indexing. Supported tokens
        include Python integers, slices, `None`, `...`, [`StateSpace`][qten.symbolics.state_space.StateSpace]
        objects, [`Convertible`][qten.abstracts.Convertible] objects that can be converted to
        [`StateSpace`][qten.symbolics.state_space.StateSpace], and QTen [`Tensor`][qten.linalg.tensors.Tensor] index tensors.

    Returns
    -------
    Tensor
        A new tensor with indexed data and output metadata compiled from the
        provided key.

    Index normalization
    -------------------
    - A non-tuple key is treated as a 1-tuple.
    - At most one ellipsis (`...`) is allowed.
    - `...` expands to the required number of full slices (`:`) based on
      source-axis-consuming tokens (all non-`None` entries).
    - If fewer source-axis-consuming indices are provided than rank, missing
      trailing full slices (`:`) are appended.

    Per-token semantics
    -------------------
    - `int`: selects one element along the current source axis and removes
      that output dimension.
    - `slice`:
      - full slice `:` preserves the current [`StateSpace`][qten.symbolics.state_space.StateSpace],
      - non-full slice uses `self.dims[axis][slice]`, except
        [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace] axes where metadata follows sliced size:
        size `1` keeps [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace], size `0` becomes
        `IndexSpace.linear(0)`.
    - `None`: inserts a new output axis with [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace] and does not
      consume a source axis.
    - [`StateSpace`][qten.symbolics.state_space.StateSpace] / [`Convertible`][qten.abstracts.Convertible]:
      - indexing a [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace] axis with any non-[`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace]
        [`StateSpace`][qten.symbolics.state_space.StateSpace] is rejected (`IndexError`),
      - if equal to current axis space: behaves like full slice,
      - if same span: uses permutation indexing and output dim is the index
        [`StateSpace`][qten.symbolics.state_space.StateSpace],
      - if contained subspace: uses embedding indexing and output dim is the
        subspace,
      - otherwise raises `IndexError`.
    - [`Tensor`][qten.linalg.tensors.Tensor] index:
      - `bool` dtype is not supported (`NotImplementedError`),
      - lower-rank tensor indices are left-padded with singleton/broadcast
        axes to match the maximum tensor-index rank before metadata
        union/alignment,
      - index metadata is aligned to the union of all tensor-index dims.

    Mode rules
    ----------
    - Mixing [`Tensor`][qten.linalg.tensors.Tensor] indices with [`StateSpace`][qten.symbolics.state_space.StateSpace]/[`Convertible`][qten.abstracts.Convertible] indices is
      rejected (`ValueError`).
    - If at least one [`Tensor`][qten.linalg.tensors.Tensor] index is present, data indexing is executed
      in one torch advanced-indexing call.
    - Otherwise indexing is applied step-by-step per axis (including tuple
      index_select steps), so per-axis [`StateSpace`][qten.symbolics.state_space.StateSpace] tuple indices are not
      jointly broadcast by torch.

    Output dim ordering for tensor advanced indexing
    -----------------------------------------------
    Let `tensor_union_dims` be the broadcast/union dims of all tensor index
    tensors.
    - If tensor index tokens form one contiguous block in the normalized key,
      `tensor_union_dims` is inserted at that block position.
    - If tensor index tokens are separated by non-tensor tokens,
      `tensor_union_dims` is moved to the front of output dims.

    Raises
    ------
    IndexError
        If the key contains too many indices, incompatible [`StateSpace`][qten.symbolics.state_space.StateSpace]
        metadata, or more than one ellipsis.
    ValueError
        If tensor indices are mixed with [`StateSpace`][qten.symbolics.state_space.StateSpace] / [`Convertible`][qten.abstracts.Convertible]
        indices in one indexing operation.
    NotImplementedError
        If boolean tensor indices are used in a mode that QTen does not
        support through `__getitem__`.

    Notes
    -----
    This method delegates key analysis to [`TensorIndexing`][qten.linalg.tensors.TensorIndexing]. When advanced
    tensor indexing is present, indexing is executed in one torch call. In
    all other cases, indexing is applied step-by-step so QTen can preserve
    per-axis [`StateSpace`][qten.symbolics.state_space.StateSpace] semantics.
    """
    if not isinstance(key, tuple):
        key = (key,)
    compiled = TensorIndexing(self.dims, key).compile()
    if compiled.has_tensor_index:
        indices = tuple(
            idx.to(self.data.device) if isinstance(idx, torch.Tensor) else idx
            for idx in compiled.indices
        )
        data = self.data[indices]
        return Tensor(data=data, dims=compiled.dims)

    data = self.data
    axis = 0
    for step in compiled.indices_steps:
        if step is None:
            data = data.unsqueeze(axis)
            axis += 1
            continue
        if isinstance(step, tuple):
            index_data = torch.tensor(step, dtype=torch.long, device=data.device)
            data = data.index_select(axis, index_data)
            axis += 1
            continue
        key_step = (slice(None),) * axis + (step,)
        data = data[key_step]
        if not isinstance(step, int):
            axis += 1
    return Tensor(data=data, dims=compiled.dims)

factorize_dim

factorize_dim(
    dim: int, rule: StateSpaceFactorization
) -> Self

Factorize one StateSpace-like dimension into multiple subspaces.

For a tensor with shape (A, B), factorizing the 0th dimension with factorized=(A1, A2) and a compatible align_dim produces shape (A1, A2, B).

Parameters:

Name Type Description Default
dim int

The index of the dimension to factorize.

required
rule StateSpaceFactorization

The factorization rule. Its factorized field gives the output factor spaces that replace the selected axis, and its align_dim field gives a compatible reordering of the original axis used before reshape.

required

Returns:

Type Description
Self

A new tensor of the same wrapper type with the specified dimension factorized.

See Also

factorize_dim(tensor, dim, rule) Functional form with the full factorization semantics.

Source code in src/qten/linalg/tensors.py
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
def factorize_dim(self, dim: int, rule: StateSpaceFactorization) -> Self:
    """
    Factorize one [`StateSpace`][qten.symbolics.state_space.StateSpace]-like dimension into multiple subspaces.

    For a tensor with shape `(A, B)`, factorizing the `0`th dimension with
    `factorized=(A1, A2)` and a compatible `align_dim` produces shape
    `(A1, A2, B)`.

    Parameters
    ----------
    dim : int
        The index of the dimension to factorize.
    rule : StateSpaceFactorization
        The factorization rule. Its `factorized` field gives the output
        factor spaces that replace the selected axis, and its `align_dim`
        field gives a compatible reordering of the original axis used
        before reshape.

    Returns
    -------
    Self
        A new tensor of the same wrapper type with the specified dimension factorized.

    See Also
    --------
    [`factorize_dim(tensor, dim, rule)`][qten.linalg.tensors.factorize_dim]
        Functional form with the full factorization semantics.
    """
    return factorize_dim(self, dim, rule)

product_dims

product_dims(*indices_group: tuple[int, ...]) -> Self

Combine selected tensor dimensions into product dimensions.

Each entry in indices_group defines one output product dimension. For a group (i0, i1, ..., ik), the returned tensor contains a single axis whose size is the product of the grouped axis sizes and whose StateSpace is self.dims[i0] @ self.dims[i1] @ ... @ self.dims[ik]. Dimensions not listed in any group are preserved as-is.

Negative indices are supported and follow Python indexing rules. Grouped dimensions do not need to be contiguous in the input tensor; the method reorders axes internally, performs one reshape, and returns the result in the canonical output order.

Use cases
  • flatten several symbolic axes into one composite axis before a decomposition,
  • build tensor-product state spaces explicitly in the metadata.

Parameters:

Name Type Description Default
indices_group Tuple[int, ...]

One or more non-empty groups of dimension indices to combine. Indices must be unique across all groups (a dimension can belong to at most one group).

()

Returns:

Type Description
Self

A new tensor of the same wrapper type where each requested group is replaced by one product dimension and all non-grouped dimensions are retained.

See Also

product_dims(tensor, *indices_group) Functional form with the full product-dimension semantics.

Raises:

Type Description
IndexError

If any provided index is out of range for the tensor rank.

ValueError

If any group is empty, if a group contains duplicate indices, or if the same index appears in more than one group.

Source code in src/qten/linalg/tensors.py
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
def product_dims(self, *indices_group: Tuple[int, ...]) -> Self:
    """
    Combine selected tensor dimensions into product dimensions.

    Each entry in `indices_group` defines one output product dimension.
    For a group `(i0, i1, ..., ik)`, the returned tensor contains a single
    axis whose size is the product of the grouped axis sizes and whose
    [`StateSpace`][qten.symbolics.state_space.StateSpace] is `self.dims[i0] @ self.dims[i1] @ ... @ self.dims[ik]`.
    Dimensions not listed in any group are preserved as-is.

    Negative indices are supported and follow Python indexing rules.
    Grouped dimensions do not need to be contiguous in the input tensor; the
    method reorders axes internally, performs one reshape, and returns the
    result in the canonical output order.

    Use cases
    ---------
    - flatten several symbolic axes into one composite axis before a
      decomposition,
    - build tensor-product state spaces explicitly in the metadata.

    Parameters
    ----------
    indices_group : Tuple[int, ...]
        One or more non-empty groups of dimension indices to combine.
        Indices must be unique across all groups (a dimension can belong to
        at most one group).

    Returns
    -------
    Self
        A new tensor of the same wrapper type where each requested group is
        replaced by one product dimension and all non-grouped dimensions
        are retained.

    See Also
    --------
    [`product_dims(tensor, *indices_group)`][qten.linalg.tensors.product_dims]
        Functional form with the full product-dimension semantics.

    Raises
    ------
    IndexError
        If any provided index is out of range for the tensor rank.
    ValueError
        If any group is empty, if a group contains duplicate indices, or if
        the same index appears in more than one group.
    """
    return product_dims(self, *indices_group)

dim_types

dim_types() -> tuple[type, ...]

Return a tuple of the types of the dimensions in the tensor.

Returns:

Type Description
Tuple[type, ...]

A tuple containing the types of each dimension in the tensor.

Source code in src/qten/linalg/tensors.py
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
def dim_types(self) -> Tuple[type, ...]:
    """
    Return a tuple of the types of the dimensions in the tensor.

    Returns
    -------
    Tuple[type, ...]
        A tuple containing the types of each dimension in the tensor.
    """
    return tuple(type(dim) for dim in self.dims)

__repr__

__repr__() -> str

Return a compact developer-facing representation of the tensor.

The representation summarizes:

  • the execution device class (CPU or GPU),
  • whether gradients are tracked,
  • and one TypeName:size entry per axis in dims.

Returns:

Type Description
str

A one-line summary suitable for debugging and interactive use.

Source code in src/qten/linalg/tensors.py
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
def __repr__(self) -> str:
    """
    Return a compact developer-facing representation of the tensor.

    The representation summarizes:

    - the execution device class (`CPU` or `GPU`),
    - whether gradients are tracked,
    - and one `TypeName:size` entry per axis in `dims`.

    Returns
    -------
    str
        A one-line summary suitable for debugging and interactive use.
    """
    device_type = self.data.device.type
    device = "GPU" if device_type in {"cuda", "mps"} else "CPU"
    if self.dims:
        shape = ", ".join(f"{type(dim).__name__}:{dim.dim}" for dim in self.dims)
        shape_repr = f"({shape})"
    else:
        shape_repr = "()"
    return f"<{device} Tensor grad={self.data.requires_grad} shape={shape_repr}>"

align

align(
    tensor: TensorType, dim: int, target_dim: StateSpace
) -> TensorType

Align one tensor axis to a target symbolic dimension.

Alignment is QTen's core metadata-aware axis reordering operation:

  • if the source axis already matches target_dim, the tensor is returned unchanged,
  • if the source axis is BroadcastSpace(), it is expanded to the size of target_dim,
  • if the source and target axes span the same rays in a different order, the data is permuted along that axis to match target_dim,
  • otherwise alignment fails.

Parameters:

Name Type Description Default
tensor Tensor

Input tensor.

required
dim int

The dimension index to align.

required
target_dim StateSpace

The target StateSpace to align to.

required

Returns:

Type Description
TensorType

Tensor whose selected axis matches target_dim, preserving the input wrapper type.

Raises:

Type Description
IndexError

If dim is out of range for the tensor rank.

ValueError

If the source and target dimensions are not symbolically compatible for alignment.

Source code in src/qten/linalg/tensors.py
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
def align(tensor: TensorType, dim: int, target_dim: StateSpace) -> TensorType:
    """
    Align one tensor axis to a target symbolic dimension.

    Alignment is QTen's core metadata-aware axis reordering operation:

    - if the source axis already matches `target_dim`, the tensor is returned
      unchanged,
    - if the source axis is
      [`BroadcastSpace()`][qten.symbolics.state_space.BroadcastSpace], it is
      expanded to the size of `target_dim`,
    - if the source and target axes span the same rays in a different order,
      the data is permuted along that axis to match `target_dim`,
    - otherwise alignment fails.

    Parameters
    ----------
    tensor : Tensor
        Input tensor.
    dim : int
        The dimension index to align.
    target_dim : StateSpace
        The target StateSpace to align to.

    Returns
    -------
    TensorType
        Tensor whose selected axis matches `target_dim`, preserving the input
        wrapper type.

    Raises
    ------
    IndexError
        If `dim` is out of range for the tensor rank.
    ValueError
        If the source and target dimensions are not symbolically compatible for
        alignment.
    """
    if dim < 0:
        dim = dim + len(tensor.dims)
    if dim < 0 or dim >= len(tensor.dims):
        raise IndexError(
            f"Dimension index {dim} out of range for rank {len(tensor.dims)}"
        )

    current_dim = tensor.dims[dim]
    if isinstance(target_dim, BroadcastSpace):
        return tensor  # No alignment needed for BroadcastSpace
    if current_dim is target_dim or current_dim == target_dim:
        return tensor

    if isinstance(current_dim, BroadcastSpace):
        # Expand broadcast dimension to match the target StateSpace size.
        expanded_shape = list(tensor.data.shape)
        expanded_shape[dim] = target_dim.dim
        aligned_data = tensor.data.expand(*expanded_shape)
        return replace(
            tensor,
            data=aligned_data,
            dims=tensor.dims[:dim] + (target_dim,) + tensor.dims[dim + 1 :],
        )

    if type(current_dim) is not type(target_dim):
        raise ValueError(
            f"Cannot align dimensions with different StateSpace types: "
            f"current={type(current_dim).__name__}:{current_dim.dim} vs "
            f"target={type(target_dim).__name__}:{target_dim.dim}"
        )
    if not same_rays(current_dim, target_dim):
        raise ValueError(
            f"StateSpace at axis {dim} cannot be aligned to target StateSpace: "
            f"current={type(current_dim).__name__}:{current_dim.dim}, "
            f"target={type(target_dim).__name__}:{target_dim.dim}"
        )

    try:
        target_order = permutation_order(current_dim, target_dim)
    except ValueError as e:
        raise ValueError(
            f"StateSpace at axis {dim} cannot be aligned to target StateSpace: "
            f"current={type(current_dim).__name__}:{current_dim.dim}, "
            f"target={type(target_dim).__name__}:{target_dim.dim}"
        ) from e
    if target_order == tuple(range(current_dim.dim)):
        return tensor
    aligned_data = torch.index_select(
        tensor.data,
        dim,
        torch.tensor(target_order, dtype=torch.long, device=tensor.data.device),
    )

    aligned_tensor = replace(
        tensor,
        data=aligned_data,
        dims=tensor.dims[:dim] + (target_dim,) + tensor.dims[dim + 1 :],
    )

    return aligned_tensor

align_all

align_all(
    tensor: TensorType, dims: tuple[StateSpace, ...]
) -> TensorType

Align every tensor axis to a target symbolic layout.

This applies align axis-by-axis and is the standard utility used before value comparisons and metadata-aware broadcasting.

Parameters:

Name Type Description Default
tensor Tensor

The tensor to align.

required
dims Tuple[StateSpace, ...]

Target dimensions for each axis.

required

Returns:

Type Description
TensorType

Tensor whose dims match the requested target layout, preserving the input wrapper type.

Raises:

Type Description
ValueError

If rank does not match or any dimension cannot be aligned.

Source code in src/qten/linalg/tensors.py
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
def align_all(tensor: TensorType, dims: Tuple[StateSpace, ...]) -> TensorType:
    """
    Align every tensor axis to a target symbolic layout.

    This applies [`align`][qten.linalg.tensors.align] axis-by-axis and is the
    standard utility used before value comparisons and metadata-aware
    broadcasting.

    Parameters
    ----------
    tensor : Tensor
        The tensor to align.
    dims : Tuple[StateSpace, ...]
        Target dimensions for each axis.

    Returns
    -------
    TensorType
        Tensor whose `dims` match the requested target layout, preserving the
        input wrapper type.

    Raises
    ------
    ValueError
        If rank does not match or any dimension cannot be aligned.
    """
    if len(dims) != tensor.rank():
        raise ValueError(
            f"Cannot align rank-{tensor.rank()} tensor to rank-{len(dims)} dims: "
            f"current={_format_dims(tensor.dims)}, target={_format_dims(dims)}"
        )

    aligned = tensor
    for idx, target_dim in enumerate(dims):
        aligned = aligned.align(idx, target_dim)
    return aligned

all

all(
    tensor: TensorType,
    dim: int | tuple[int, ...] | None = None,
    keepdim: bool = False,
) -> TensorType

Reduce a tensor with logical AND, matching torch.all semantics.

Parameters:

Name Type Description Default
tensor Tensor

Input tensor.

required
dim Optional[Union[int, Tuple[int, ...]]]

Reduction axis (or axes). If None, reduce over all dimensions.

None
keepdim bool

If True, retains the reduced axis as BroadcastSpace.

False

Returns:

Type Description
TensorType

Boolean tensor with reduced dimensions, preserving the input wrapper type.

Notes

When keepdim=True, reduced axes are retained as BroadcastSpace() dimensions rather than their original concrete spaces.

Raises:

Type Description
IndexError

If any requested reduction axis is out of range for the tensor rank.

Source code in src/qten/linalg/tensors.py
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
def all(
    tensor: TensorType,
    dim: Optional[Union[int, Tuple[int, ...]]] = None,
    keepdim: bool = False,
) -> TensorType:
    """
    Reduce a tensor with logical AND, matching `torch.all` semantics.

    Parameters
    ----------
    tensor : Tensor
        Input tensor.
    dim : Optional[Union[int, Tuple[int, ...]]], optional
        Reduction axis (or axes). If `None`, reduce over all dimensions.
    keepdim : bool, optional
        If `True`, retains the reduced axis as [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace].

    Returns
    -------
    TensorType
        Boolean tensor with reduced dimensions, preserving the input wrapper
        type.

    Notes
    -----
    When `keepdim=True`, reduced axes are retained as
    [`BroadcastSpace()`][qten.symbolics.state_space.BroadcastSpace] dimensions
    rather than their original concrete spaces.

    Raises
    ------
    IndexError
        If any requested reduction axis is out of range for the tensor rank.
    """
    if dim is None:
        return replace(tensor, data=torch.all(tensor.data), dims=())

    rank_ = tensor.rank()
    if isinstance(dim, int):
        dims_tuple: Tuple[int, ...] = (dim,)
    else:
        dims_tuple = dim

    normalized_dims: list[int] = []
    for d in dims_tuple:
        nd = d
        if nd < 0:
            nd += rank_
        if nd < 0 or nd >= rank_:
            raise IndexError(f"Dimension index {d} out of range for rank {rank_}")
        normalized_dims.append(nd)

    reduced_dims = tuple(normalized_dims)
    reduced_dims_set = set(reduced_dims)

    reduced = torch.all(tensor.data, dim=dim, keepdim=keepdim)
    if keepdim:
        new_dims = tuple(
            BroadcastSpace() if idx in reduced_dims_set else current_dim
            for idx, current_dim in enumerate(tensor.dims)
        )
    else:
        new_dims = tuple(
            current_dim
            for idx, current_dim in enumerate(tensor.dims)
            if idx not in reduced_dims_set
        )
    return replace(tensor, data=reduced, dims=new_dims)

allclose

allclose(
    a: Tensor,
    b: Tensor,
    rtol: float = 1e-05,
    atol: float = 1e-08,
    equal_nan: bool = False,
) -> bool

Compare two tensors for approximate equality with dimension-aware alignment.

Supported forms

allclose(a, b, ...) Functional form.

a.allclose(b, ...) Method form.

This function first aligns b to a by calling b.align_all(a.dims). If alignment fails (for example, mismatched rank or non-alignable StateSpaces), this function returns False instead of raising. When alignment succeeds, the function compares data values using torch.allclose.

After alignment, comparison is delegated directly to torch.allclose, preserving native PyTorch behavior for dtype/device handling.

Parameters:

Name Type Description Default
a Tensor

Reference tensor defining the target dimension layout.

required
b Tensor

Tensor that will be aligned to a before comparison.

required
rtol float

Relative tolerance used by torch.allclose.

1e-05
atol float

Absolute tolerance used by torch.allclose.

1e-08
equal_nan bool

Whether NaN values are considered equal.

False

Returns:

Type Description
bool

True if values are close after successful alignment; False if alignment fails or values are not close.

Use cases
  • compare tensors that may differ only by symbolic axis ordering,
  • validate numerical results in tests without manually aligning metadata first.
Source code in src/qten/linalg/tensors.py
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
def allclose(
    a: Tensor,
    b: Tensor,
    rtol: float = 1e-05,
    atol: float = 1e-08,
    equal_nan: bool = False,
) -> bool:
    """
    Compare two tensors for approximate equality with dimension-aware alignment.

    Supported forms
    ---------------
    [`allclose(a, b, ...)`][qten.linalg.tensors.allclose]
        Functional form.

    [`a.allclose(b, ...)`][qten.linalg.tensors.Tensor.allclose]
        Method form.

    This function first aligns `b` to `a` by calling `b.align_all(a.dims)`.
    If alignment fails (for example, mismatched rank or non-alignable
    [`StateSpace`][qten.symbolics.state_space.StateSpace]s), this function returns `False` instead of raising.
    When alignment succeeds, the function compares data values using
    `torch.allclose`.

    After alignment, comparison is delegated directly to `torch.allclose`,
    preserving native PyTorch behavior for dtype/device handling.

    Parameters
    ----------
    a : Tensor
        Reference tensor defining the target dimension layout.
    b : Tensor
        Tensor that will be aligned to `a` before comparison.
    rtol : float, optional
        Relative tolerance used by `torch.allclose`.
    atol : float, optional
        Absolute tolerance used by `torch.allclose`.
    equal_nan : bool, optional
        Whether `NaN` values are considered equal.

    Returns
    -------
    bool
        True if values are close after successful alignment; `False` if
        alignment fails or values are not close.

    Use cases
    ---------
    - compare tensors that may differ only by symbolic axis ordering,
    - validate numerical results in tests without manually aligning metadata
      first.
    """
    a, b = _promote_to_device(a, b)

    try:
        aligned_b = b.align_all(a.dims)
    except (IndexError, TypeError, ValueError, RuntimeError):
        return False

    return torch.allclose(
        a.data, aligned_b.data, rtol=rtol, atol=atol, equal_nan=equal_nan
    )

at_device

at_device(device: Device | str)

Bases: ContextDecorator

Temporarily force newly created QTen tensors onto a specific device.

This applies to Tensor(...) construction within the current thread, including tensors created indirectly by helper functions in this module. Nested scopes are supported; the innermost device takes precedence.

Source code in src/qten/linalg/tensors.py
138
139
def __init__(self, device: Device | str):
    self.device = Device.new(device) if isinstance(device, str) else device

device instance-attribute

device: Device = (
    new(device) if isinstance(device, str) else device
)

__enter__

__enter__() -> Self

Activate the context for the current thread.

The target device is validated eagerly by resolving its underlying torch.device. The resolved device is then pushed onto the thread-local device stack used by Tensor.__post_init__.

Returns:

Type Description
at_device

This context manager instance.

Source code in src/qten/linalg/tensors.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def __enter__(self) -> "at_device":
    """
    Activate the context for the current thread.

    The target device is validated eagerly by resolving its underlying
    `torch.device`. The resolved device is then pushed onto the thread-local
    device stack used by `Tensor.__post_init__`.

    Returns
    -------
    at_device
        This context manager instance.
    """
    self.device.torch_device()
    _tensor_device_stack().append(self.device)
    return self

__exit__

__exit__(
    exc_type: type[BaseException] | None,
    exc: BaseException | None,
    tb: Any,
) -> None

Deactivate the current device-forcing scope.

Parameters:

Name Type Description Default
exc_type type[BaseException] | None

Exception type raised inside the context, if any.

required
exc BaseException | None

Exception instance raised inside the context, if any.

required
tb Any

Traceback object associated with exc, if any.

required
Notes

The exception information is ignored; this method only restores the previous thread-local device stack. Any active exception continues to propagate normally.

Source code in src/qten/linalg/tensors.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def __exit__(
    self,
    exc_type: type[BaseException] | None,
    exc: BaseException | None,
    tb: Any,
) -> None:
    """
    Deactivate the current device-forcing scope.

    Parameters
    ----------
    exc_type : type[BaseException] | None
        Exception type raised inside the context, if any.
    exc : BaseException | None
        Exception instance raised inside the context, if any.
    tb : Any
        Traceback object associated with `exc`, if any.

    Notes
    -----
    The exception information is ignored; this method only restores the
    previous thread-local device stack. Any active exception continues to
    propagate normally.
    """
    stack = _tensor_device_stack()
    stack.pop()
    if not stack:
        delattr(_TENSOR_DEVICE_STATE, "stack")

argmax

argmax(tensor: TensorType, dim: int) -> TensorType

Return indices of maximum values along one tensor axis.

Parameters:

Name Type Description Default
tensor Tensor

The tensor to reduce.

required
dim int

The dimension to reduce.

required

Returns:

Type Description
TensorType

Integer-valued tensor with the reduced axis removed from dims, preserving the input wrapper type.

Raises:

Type Description
IndexError

If dim is out of range for the tensor rank.

Source code in src/qten/linalg/tensors.py
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
def argmax(tensor: TensorType, dim: int) -> TensorType:
    """
    Return indices of maximum values along one tensor axis.

    Parameters
    ----------
    tensor : Tensor
        The tensor to reduce.
    dim : int
        The dimension to reduce.

    Returns
    -------
    TensorType
        Integer-valued tensor with the reduced axis removed from `dims`,
        preserving the input wrapper type.

    Raises
    ------
    IndexError
        If `dim` is out of range for the tensor rank.
    """
    if dim < 0:
        dim += tensor.rank()
    if dim < 0 or dim >= tensor.rank():
        raise IndexError(f"Dimension index {dim} out of range for rank {tensor.rank()}")

    return replace(
        tensor,
        data=tensor.data.argmax(dim=dim),
        dims=tensor.dims[:dim] + tensor.dims[dim + 1 :],
    )

argmin

argmin(tensor: TensorType, dim: int) -> TensorType

Return indices of minimum values along one tensor axis.

Parameters:

Name Type Description Default
tensor Tensor

The tensor to reduce.

required
dim int

The dimension to reduce.

required

Returns:

Type Description
TensorType

Integer-valued tensor with the reduced axis removed from dims, preserving the input wrapper type.

Raises:

Type Description
IndexError

If dim is out of range for the tensor rank.

Source code in src/qten/linalg/tensors.py
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
def argmin(tensor: TensorType, dim: int) -> TensorType:
    """
    Return indices of minimum values along one tensor axis.

    Parameters
    ----------
    tensor : Tensor
        The tensor to reduce.
    dim : int
        The dimension to reduce.

    Returns
    -------
    TensorType
        Integer-valued tensor with the reduced axis removed from `dims`,
        preserving the input wrapper type.

    Raises
    ------
    IndexError
        If `dim` is out of range for the tensor rank.
    """
    if dim < 0:
        dim += tensor.rank()
    if dim < 0 or dim >= tensor.rank():
        raise IndexError(f"Dimension index {dim} out of range for rank {tensor.rank()}")

    return replace(
        tensor,
        data=tensor.data.argmin(dim=dim),
        dims=tensor.dims[:dim] + tensor.dims[dim + 1 :],
    )

abs

abs(tensor: TensorType) -> TensorType

Return the element-wise absolute value or magnitude of a tensor.

The symbolic dimensions are unchanged. Complex inputs produce a real-valued magnitude tensor following PyTorch semantics.

Source code in src/qten/linalg/tensors.py
2599
2600
2601
2602
2603
2604
2605
2606
def abs(tensor: TensorType) -> TensorType:
    """
    Return the element-wise absolute value or magnitude of a tensor.

    The symbolic dimensions are unchanged. Complex inputs produce a real-valued
    magnitude tensor following PyTorch semantics.
    """
    return replace(tensor, data=cast(T, tensor.data.abs()))

astype

astype(tensor: TensorType, dtype: dtype) -> TensorType

Return a new tensor with data converted to dtype.

This is the metadata-preserving dtype-conversion helper for QTen tensors. Only the underlying torch data dtype changes; tensor.dims is left unchanged.

See Also

torch.Tensor.to Underlying PyTorch dtype/device conversion API.

Parameters:

Name Type Description Default
tensor Tensor

Input tensor.

required
dtype dtype

Target PyTorch dtype.

This must be a torch.dtype object such as torch.float32, torch.float64, torch.complex64, torch.complex128, torch.int64, or torch.bool. Any dtype accepted by torch.Tensor.to(dtype=...) is valid here.

required

Returns:

Type Description
TensorType

A new tensor with converted data and unchanged dims, preserving the input wrapper type.

Source code in src/qten/linalg/tensors.py
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
def astype(tensor: TensorType, dtype: torch.dtype) -> TensorType:
    """
    Return a new tensor with data converted to `dtype`.

    This is the metadata-preserving dtype-conversion helper for QTen tensors.
    Only the underlying torch data dtype changes; `tensor.dims` is left
    unchanged.

    See Also
    --------
    [`torch.Tensor.to`](https://pytorch.org/docs/stable/generated/torch.Tensor.to.html)
        Underlying PyTorch dtype/device conversion API.

    Parameters
    ----------
    tensor : Tensor
        Input tensor.
    dtype : torch.dtype
        Target PyTorch dtype.

        This must be a [`torch.dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch-dtype)
        object such as `torch.float32`, `torch.float64`, `torch.complex64`,
        `torch.complex128`, `torch.int64`, or `torch.bool`. Any dtype
        accepted by `torch.Tensor.to(dtype=...)` is valid here.

    Returns
    -------
    TensorType
        A new tensor with converted data and unchanged dims, preserving the input wrapper type.
    """
    return replace(tensor, data=tensor.data.to(dtype=dtype))

cat

cat(
    tensors: Sequence[TensorType], dim: int = 0
) -> TensorType

Concatenate tensors along an existing dimension with metadata-aware alignment.

Non-concatenated dimensions must represent the same rays and are aligned to the ordering of the first tensor before concatenation. The concatenated output dimension is rebuilt by ordered append. IndexSpace dimensions are resized linearly; structured dimensions require fully disjoint labels. Any overlap at all, even partial overlap, raises ValueError rather than being merged.

Parameters:

Name Type Description Default
tensors Sequence[TensorType]

Tensors to concatenate. All tensors must have the same rank.

required
dim int

Axis along which to concatenate.

`0`

Returns:

Type Description
TensorType

Concatenated tensor whose non-concatenated dims match the first input and whose concatenated dim is rebuilt to describe the appended axis.

Raises:

Type Description
ValueError

If tensors is empty, if the input tensors do not all have the same rank, if any non-concatenated axes do not span the same rays, or if the concatenated symbolic dimension cannot be rebuilt consistently (for example because dimension types differ, concatenation is attempted along BroadcastSpace, or structured labels overlap in any amount).

IndexError

If dim is out of range for the input tensor rank.

Source code in src/qten/linalg/tensors.py
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
def cat(tensors: Sequence[TensorType], dim: int = 0) -> TensorType:
    """
    Concatenate tensors along an existing dimension with metadata-aware alignment.

    Non-concatenated dimensions must represent the same rays and are aligned to
    the ordering of the first tensor before concatenation. The concatenated
    output dimension is rebuilt by ordered append. [`IndexSpace`][qten.symbolics.state_space.IndexSpace] dimensions are
    resized linearly; structured dimensions require fully disjoint labels.
    Any overlap at all, even partial overlap, raises `ValueError` rather than
    being merged.

    Parameters
    ----------
    tensors : Sequence[TensorType]
        Tensors to concatenate. All tensors must have the same rank.
    dim : int, default `0`
        Axis along which to concatenate.

    Returns
    -------
    TensorType
        Concatenated tensor whose non-concatenated dims match the first input
        and whose concatenated dim is rebuilt to describe the appended axis.

    Raises
    ------
    ValueError
        If `tensors` is empty, if the input tensors do not all have the same
        rank, if any non-concatenated axes do not span the same rays, or if
        the concatenated symbolic dimension cannot be rebuilt consistently
        (for example because dimension types differ, concatenation is attempted
        along [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace], or
        structured labels overlap in any amount).
    IndexError
        If `dim` is out of range for the input tensor rank.
    """
    if not tensors:
        raise ValueError("cat expects at least one tensor")

    first = tensors[0]
    rank_ = first.rank()
    if dim < 0:
        dim += rank_
    if dim < 0 or dim >= rank_:
        raise IndexError(f"Dimension index {dim} out of range for rank {rank_}")

    for tensor in tensors[1:]:
        if tensor.rank() != rank_:
            raise ValueError("All tensors passed to cat must have the same rank")

    common_dtype = first.data.dtype
    for tensor in tensors[1:]:
        common_dtype = torch.promote_types(common_dtype, tensor.data.dtype)

    promoted = tuple(
        tensor
        if tensor.data.dtype == common_dtype
        else replace(tensor, data=tensor.data.to(common_dtype))
        for tensor in _promote_to_device(*tensors)
    )

    aligned: list[TensorType] = []
    for tensor in promoted:
        current = tensor
        for axis in range(rank_):
            if axis == dim:
                continue
            target_dim = first.dims[axis]
            if not same_rays(current.dims[axis], target_dim):
                raise ValueError(
                    f"All non-concatenated dims must have the same rays; "
                    f"axis {axis} differs between {current.dims[axis]} and {target_dim}"
                )
            current = current.align(axis, target_dim)
        aligned.append(current)

    out_dim = _cat_dim([tensor.dims[dim] for tensor in aligned])
    out_dims = first.dims[:dim] + (out_dim,) + first.dims[dim + 1 :]
    out_data = torch.cat([tensor.data for tensor in aligned], dim=dim)
    return replace(first, data=out_data, dims=out_dims)

conj

conj(tensor: TensorType) -> TensorType

Return the element-wise complex conjugate of a tensor.

Parameters:

Name Type Description Default
tensor Tensor

Input tensor.

required

Returns:

Type Description
TensorType

Tensor with conjugated data and unchanged dims, preserving the input wrapper type.

Source code in src/qten/linalg/tensors.py
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
def conj(tensor: TensorType) -> TensorType:
    """
    Return the element-wise complex conjugate of a tensor.

    Parameters
    ----------
    tensor : Tensor
        Input tensor.

    Returns
    -------
    TensorType
        Tensor with conjugated data and unchanged dims, preserving the input
        wrapper type.
    """
    return replace(tensor, data=tensor.data.conj())

equal

equal(a: Tensor, b: Tensor) -> bool

Compare two tensors for exact equality with dimension-aware alignment.

Supported forms

equal(a, b) Functional form.

a.equal(b) Method form.

This function first aligns b to a by calling b.align_all(a.dims). If alignment fails (for example, mismatched rank or non-alignable StateSpaces), this function returns False instead of raising. When alignment succeeds, the function compares data values using torch.equal.

After alignment, equality is delegated directly to torch.equal, preserving native PyTorch equality behavior for dtype/device handling.

Parameters:

Name Type Description Default
a Tensor

Reference tensor defining the target dimension layout.

required
b Tensor

Tensor that will be aligned to a before comparison.

required

Returns:

Type Description
bool

True if values are exactly equal after successful alignment; False if alignment fails or values are not equal.

Source code in src/qten/linalg/tensors.py
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
def equal(a: Tensor, b: Tensor) -> bool:
    """
    Compare two tensors for exact equality with dimension-aware alignment.

    Supported forms
    ---------------
    [`equal(a, b)`][qten.linalg.tensors.equal]
        Functional form.

    [`a.equal(b)`][qten.linalg.tensors.Tensor.equal]
        Method form.

    This function first aligns `b` to `a` by calling `b.align_all(a.dims)`.
    If alignment fails (for example, mismatched rank or non-alignable
    [`StateSpace`][qten.symbolics.state_space.StateSpace]s), this function returns `False` instead of raising.
    When alignment succeeds, the function compares data values using
    `torch.equal`.

    After alignment, equality is delegated directly to `torch.equal`, preserving
    native PyTorch equality behavior for dtype/device handling.

    Parameters
    ----------
    a : Tensor
        Reference tensor defining the target dimension layout.
    b : Tensor
        Tensor that will be aligned to `a` before comparison.

    Returns
    -------
    bool
        True if values are exactly equal after successful alignment; `False`
        if alignment fails or values are not equal.
    """
    a, b = _promote_to_device(a, b)

    try:
        aligned_b = b.align_all(a.dims)
    except (IndexError, TypeError, ValueError, RuntimeError):
        return False

    return torch.equal(a.data, aligned_b.data)

expand_to_union

expand_to_union(
    tensor: TensorType, union_dims: list[StateSpace]
) -> TensorType

Expand broadcast axes to match a merged symbolic dimension layout.

This helper is typically used after union_dims determines the target dims for a broadcasted operation. Only axes labeled by BroadcastSpace() are expanded; concrete non-broadcast axes are preserved as-is.

Parameters:

Name Type Description Default
tensor TensorType

Input tensor whose broadcast axes may need to be materialized.

required
union_dims list[StateSpace]

Target symbolic dimensions, typically produced by union_dims(...). This must have the same length as tensor.dims.

required

Returns:

Type Description
TensorType

Tensor whose broadcast axes have been expanded to the corresponding concrete sizes in union_dims. If no expansion is needed, returns the input tensor unchanged.

Raises:

Type Description
ValueError

If union_dims does not match the tensor rank or does not describe a layout compatible with the underlying data shape.

Source code in src/qten/linalg/tensors.py
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
def expand_to_union(tensor: TensorType, union_dims: list[StateSpace]) -> TensorType:
    """
    Expand broadcast axes to match a merged symbolic dimension layout.

    This helper is typically used after
    [`union_dims`][qten.linalg.tensors.union_dims] determines the target dims
    for a broadcasted operation. Only axes labeled by
    [`BroadcastSpace()`][qten.symbolics.state_space.BroadcastSpace] are
    expanded; concrete non-broadcast axes are preserved as-is.

    Parameters
    ----------
    tensor : TensorType
        Input tensor whose broadcast axes may need to be materialized.
    union_dims : list[StateSpace]
        Target symbolic dimensions, typically produced by
        [`union_dims(...)`][qten.linalg.tensors.union_dims]. This must have the
        same length as `tensor.dims`.

    Returns
    -------
    TensorType
        Tensor whose broadcast axes have been expanded to the corresponding
        concrete sizes in `union_dims`. If no expansion is needed, returns the
        input tensor unchanged.

    Raises
    ------
    ValueError
        If `union_dims` does not match the tensor rank or does not describe a
        layout compatible with the underlying data shape.
    """

    if not any(isinstance(d, BroadcastSpace) for d in tensor.dims):
        return tensor
    target_shape = []
    new_dims = []
    needs_expansion = False

    for dim, u_dim, size in zip(tensor.dims, union_dims, tensor.data.shape):
        if isinstance(dim, BroadcastSpace) and not isinstance(u_dim, BroadcastSpace):
            target_shape.append(u_dim.dim)
            new_dims.append(u_dim)
            needs_expansion = True
        else:
            target_shape.append(size)
            new_dims.append(dim)

    if not needs_expansion:
        return tensor

    return replace(tensor, data=tensor.data.expand(target_shape), dims=tuple(new_dims))

eye

eye(
    dims: tuple[StateSpace, ...],
    *,
    device: Device | None = None,
) -> Tensor

Create an identity matrix tensor from the last two symbolic dimensions.

This helper interprets dims[-2:] as the matrix axes and returns a rank-2 identity tensor on those spaces. Any leading dimensions in dims are ignored; this function does not build a batched identity tensor.

Parameters:

Name Type Description Default
dims Tuple[StateSpace, ...]

Dimension tuple whose last two entries define the row and column spaces of the identity matrix.

required
device Optional[Device]

Device on which to place the returned tensor.

None

Returns:

Type Description
Tensor

Rank-2 identity tensor with dims (dims[-2], dims[-1]).

Raises:

Type Description
ValueError

If dims has rank less than 2.

Source code in src/qten/linalg/tensors.py
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
def eye(dims: Tuple[StateSpace, ...], *, device: Optional[Device] = None) -> Tensor:
    """
    Create an identity matrix tensor from the last two symbolic dimensions.

    This helper interprets `dims[-2:]` as the matrix axes and returns a rank-2
    identity tensor on those spaces. Any leading dimensions in `dims` are
    ignored; this function does not build a batched identity tensor.

    Parameters
    ----------
    dims : Tuple[StateSpace, ...]
        Dimension tuple whose last two entries define the row and column
        spaces of the identity matrix.
    device : Optional[Device], optional
        Device on which to place the returned tensor.

    Returns
    -------
    Tensor
        Rank-2 identity tensor with dims `(dims[-2], dims[-1])`.

    Raises
    ------
    ValueError
        If `dims` has rank less than 2.
    """
    if len(dims) < 2:
        raise ValueError(
            f"Identity tensor creation requires at least rank 2, got rank {len(dims)}!"
        )
    matrix_dims = dims[-2:]
    rows = matrix_dims[0].dim
    cols = matrix_dims[1].dim
    torch_device = device.torch_device() if device is not None else None
    return Tensor(data=torch.eye(rows, cols, device=torch_device), dims=matrix_dims)

factorize_dim

factorize_dim(
    tensor: TensorType,
    dim: int,
    rule: StateSpaceFactorization,
) -> TensorType

Factorize one symbolic dimension into multiple output axes.

For a tensor with shape (A, B), factorizing the 0th dimension with factorized=(A1, A2) and a compatible align_dim produces shape (A1, A2, B).

The source axis is first aligned to rule.align_dim, then reshaped into the factor spaces listed in rule.factorized.

How to construct rule

StateSpaceFactorization has two fields:

  • factorized: the tuple of output spaces that should replace the selected axis after reshaping.
  • align_dim: a symbolic dimension with the same total size as the input axis, but with an ordering compatible with flattening/unflattening into factorized.

The key requirement is: prod(subspace.dim for subspace in rule.factorized) == rule.align_dim.dim.

In practice, you usually do not construct this object by hand. When the target axis is a HilbertSpace, the usual workflow is to derive the rule from HilbertSpace.factorize(...).

Use cases
  • split a flattened composite axis into its constituent symbolic factors,
  • recover tensor-product structure after linear-algebra operations that temporarily flattened an axis.
Example
space = tensor.dims[0]  # suppose this is a homogeneous HilbertSpace
rule = space.factorize((int,), (str,))

# `rule.factorized` is the tuple of output factor spaces.
# `rule.align_dim` is the reordered version of `space` whose basis order is
# compatible with reshaping into those factors.

out = factorize_dim(tensor, 0, rule)

If you want to see the equivalent low-level structure, the rule behaves like:

left_factor, right_factor = rule.factorized
align_dim = rule.align_dim

# Equivalent internal steps:
aligned = tensor.align(0, align_dim)
out = factorize_dim(tensor, 0, rule)
# out.dims == (left_factor, right_factor, *tensor.dims[1:])

Parameters:

Name Type Description Default
tensor Tensor

The tensor to modify.

required
dim int

The index of the dimension to factorize.

required
rule StateSpaceFactorization

The factorization rule.

required

Returns:

Type Description
TensorType

Tensor with the requested axis replaced by multiple factor axes, preserving the input wrapper type.

Raises:

Type Description
IndexError

If dim is out of range for the tensor rank.

ValueError

If the product of rule.factorized sizes does not match rule.align_dim.dim, or if the selected axis cannot be aligned to rule.align_dim.

Source code in src/qten/linalg/tensors.py
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
def factorize_dim(
    tensor: TensorType, dim: int, rule: StateSpaceFactorization
) -> TensorType:
    """
    Factorize one symbolic dimension into multiple output axes.

    For a tensor with shape `(A, B)`, factorizing the `0`th dimension with
    `factorized=(A1, A2)` and a compatible `align_dim` produces shape
    `(A1, A2, B)`.

    The source axis is first aligned to `rule.align_dim`, then reshaped into
    the factor spaces listed in `rule.factorized`.

    How to construct `rule`
    -----------------------
    [`StateSpaceFactorization`][qten.symbolics.state_space.StateSpaceFactorization]
    has two fields:

    - `factorized`: the tuple of output spaces that should replace the selected
      axis after reshaping.
    - `align_dim`: a symbolic dimension with the same total size as the input
      axis, but with an ordering compatible with flattening/unflattening into
      `factorized`.

    The key requirement is:
    `prod(subspace.dim for subspace in rule.factorized) == rule.align_dim.dim`.

    In practice, you usually do not construct this object by hand. When the
    target axis is a
    [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace], the usual
    workflow is to derive the rule from
    [`HilbertSpace.factorize(...)`][qten.symbolics.hilbert_space.HilbertSpace.factorize].

    Use cases
    ---------
    - split a flattened composite axis into its constituent symbolic factors,
    - recover tensor-product structure after linear-algebra operations that
      temporarily flattened an axis.

    Example
    -------
    ```python
    space = tensor.dims[0]  # suppose this is a homogeneous HilbertSpace
    rule = space.factorize((int,), (str,))

    # `rule.factorized` is the tuple of output factor spaces.
    # `rule.align_dim` is the reordered version of `space` whose basis order is
    # compatible with reshaping into those factors.

    out = factorize_dim(tensor, 0, rule)
    ```

    If you want to see the equivalent low-level structure, the rule behaves
    like:

    ```python
    left_factor, right_factor = rule.factorized
    align_dim = rule.align_dim

    # Equivalent internal steps:
    aligned = tensor.align(0, align_dim)
    out = factorize_dim(tensor, 0, rule)
    # out.dims == (left_factor, right_factor, *tensor.dims[1:])
    ```

    Parameters
    ----------
    tensor : Tensor
        The tensor to modify.
    dim : int
        The index of the dimension to factorize.
    rule : StateSpaceFactorization
        The factorization rule.

    Returns
    -------
    TensorType
        Tensor with the requested axis replaced by multiple factor axes,
        preserving the input wrapper type.

    Raises
    ------
    IndexError
        If `dim` is out of range for the tensor rank.
    ValueError
        If the product of `rule.factorized` sizes does not match
        `rule.align_dim.dim`, or if the selected axis cannot be aligned to
        `rule.align_dim`.
    """
    rank = tensor.rank()
    if dim < 0:
        dim += rank
    if dim < 0 or dim >= rank:
        raise IndexError(f"Dimension index {dim} out of range for rank {rank}")

    align_dim = rule.align_dim
    factorized_sizes = tuple(d.dim for d in rule.factorized)
    expected_size = 1
    for s in factorized_sizes:
        expected_size *= s
    if expected_size != align_dim.dim:
        raise ValueError(
            f"Factorized dimensions product {expected_size} does not match "
            f"align_dim size {align_dim.dim}"
        )

    aligned = tensor.align(dim, align_dim)
    new_shape = (
        tuple(aligned.data.shape[:dim])
        + factorized_sizes
        + tuple(aligned.data.shape[dim + 1 :])
    )
    new_data = aligned.data.reshape(new_shape)
    new_dims = tensor.dims[:dim] + rule.factorized + tensor.dims[dim + 1 :]
    return replace(tensor, data=new_data, dims=new_dims)

kernel_tensor

kernel_tensor(
    ker: Callable[..., Scalar],
    dims: tuple[StateSpace, ...],
    *,
    device: Device | None = None,
) -> Tensor[torch.Tensor]

Build a tensor by evaluating a scalar-valued kernel over StateSpace elements.

For each multi-index (i0, i1, ..., iN) this evaluates: ker(dims[0].elements()[i0], dims[1].elements()[i1], ..., dims[N].elements()[iN]) and stores the result at that tensor position.

Parameters:

Name Type Description Default
ker Callable[..., Number]

Scalar-valued callable that accepts one element from each state space in dims.

required
dims Tuple[StateSpace, ...]

Output tensor dimensions.

required

Returns:

Type Description
Tensor

Tensor with dims and values produced by ker.

Notes

This is the most direct construction helper when tensor entries are defined by symbolic basis elements rather than by raw numeric arrays.

Raises:

Type Description
ValueError

If any state space reports a number of elements different from its declared dim.

Source code in src/qten/linalg/tensors.py
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
def kernel_tensor(
    ker: Callable[..., Number],
    dims: Tuple[StateSpace, ...],
    *,
    device: Optional[Device] = None,
) -> Tensor[torch.Tensor]:
    """
    Build a tensor by evaluating a scalar-valued kernel over StateSpace elements.

    For each multi-index `(i0, i1, ..., iN)` this evaluates:
    `ker(dims[0].elements()[i0], dims[1].elements()[i1], ..., dims[N].elements()[iN])`
    and stores the result at that tensor position.

    Parameters
    ----------
    ker : Callable[..., Number]
        Scalar-valued callable that accepts one element from each state space in
        `dims`.
    dims : Tuple[StateSpace, ...]
        Output tensor dimensions.

    Returns
    -------
    Tensor
        Tensor with `dims` and values produced by `ker`.

    Notes
    -----
    This is the most direct construction helper when tensor entries are defined
    by symbolic basis elements rather than by raw numeric arrays.

    Raises
    ------
    ValueError
        If any state space reports a number of elements different from its
        declared `dim`.
    """
    torch_device = device.torch_device() if device is not None else None
    if not dims:
        return Tensor(data=torch.as_tensor(ker(), device=torch_device), dims=dims)

    element_axes = tuple(dim.elements() for dim in dims)
    for axis, dim in zip(element_axes, dims):
        if len(axis) != dim.dim:
            raise ValueError(
                f"kernel_tensor expects one element per index for each StateSpace; "
                f"got len(elements)={len(axis)} and dim={dim.dim} for {type(dim).__name__}"
            )

    values = [ker(*args) for args in product(*element_axes)]
    data = torch.as_tensor(values, device=torch_device).reshape(
        *(len(axis) for axis in element_axes)
    )
    return Tensor(data=data, dims=dims)

mapping_matrix

mapping_matrix(
    from_space: StateSpace,
    to_space: StateSpace,
    mapping: dict[Any, Any],
    factors: dict[tuple[Any, Any], int | float | complex]
    | None = None,
    *,
    device: Device | None = None,
) -> Tensor

Create a sector-wise mapping matrix between two state spaces.

Use cases
  • build explicit basis-change or selection matrices between symbolic spaces,
  • embed one set of labeled states into another using a sparse symbolic correspondence,
  • construct structured linear maps for use in tensor contractions.

For each (from_marker, to_marker) pair in mapping, this function inserts an identity block from the corresponding sector in from_space to the corresponding sector in to_space. Each block can be scaled by factors[(from_marker, to_marker)]; if omitted, a factor of 1 is used.

Parameters:

Name Type Description Default
from_space StateSpace

Source state space defining the row dimension and source sectors.

required
to_space StateSpace

Target state space defining the column dimension and target sectors.

required
mapping Dict[Any, Any]

Dictionary mapping sector markers in from_space to sector markers in to_space. For each entry, a block is written between the slices implied by the integer indices in from_space.structure and to_space.structure.

required
factors Optional[Dict[Tuple[Any, Any], int | float | complex]]

Optional per-entry factors. Keys are (from_marker, to_marker) tuples. Scalar values scale entries. Missing keys default to 1.

None

Returns:

Type Description
Tensor

Rank-2 tensor with dimensions (from_space, to_space) containing the assembled mapping matrix in complex precision.

Raises:

Type Description
ValueError

If any mapped source and target sectors have different sizes.

Source code in src/qten/linalg/tensors.py
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
def mapping_matrix(
    from_space: StateSpace,
    to_space: StateSpace,
    mapping: Dict[Any, Any],
    factors: Optional[Dict[Tuple[Any, Any], int | float | complex]] = None,
    *,
    device: Optional[Device] = None,
) -> Tensor:
    """
    Create a sector-wise mapping matrix between two state spaces.

    Use cases
    ---------
    - build explicit basis-change or selection matrices between symbolic
      spaces,
    - embed one set of labeled states into another using a sparse symbolic
      correspondence,
    - construct structured linear maps for use in tensor contractions.

    For each `(from_marker, to_marker)` pair in `mapping`, this function inserts
    an identity block from the corresponding sector in `from_space` to the
    corresponding sector in `to_space`. Each block can be scaled by
    `factors[(from_marker, to_marker)]`; if omitted, a factor of `1` is used.

    Parameters
    ----------
    from_space : StateSpace
        Source state space defining the row dimension and source sectors.
    to_space : StateSpace
        Target state space defining the column dimension and target sectors.
    mapping : Dict[Any, Any]
        Dictionary mapping sector markers in `from_space` to sector markers in
        `to_space`. For each entry, a block is written between the slices
        implied by the integer indices in `from_space.structure` and
        `to_space.structure`.
    factors : Optional[Dict[Tuple[Any, Any], int | float | complex]], optional
        Optional per-entry factors. Keys are `(from_marker, to_marker)` tuples.
        Scalar values scale entries. Missing keys default to `1`.

    Returns
    -------
    Tensor
        Rank-2 tensor with dimensions `(from_space, to_space)` containing the
        assembled mapping matrix in complex precision.

    Raises
    ------
    ValueError
        If any mapped source and target sectors have different sizes.
    """
    if factors is None:
        factors = {}

    precision = get_precision_config()
    torch_device = device.torch_device() if device is not None else None
    mat = torch.zeros(
        (from_space.dim, to_space.dim),
        dtype=precision.torch_complex,
        device=torch_device,
    )
    for fm, tm in mapping.items():
        findex = from_space.structure[fm]
        tindex = to_space.structure[tm]
        factor = factors.get((fm, tm), 1)
        mat[findex, tindex] = cast(Any, factor)

    return Tensor(data=mat, dims=(from_space, to_space))

matmul

matmul(left: Tensor, right: Tensor) -> Tensor

Perform matrix multiplication between two Tensors with StateSpace-aware alignment and torch-style rank handling.

Supported forms

matmul(left, right) Functional form.

left @ right Operator form provided by Operable and dispatched to this function.

Both operands must be at least 1D. If either operand is 1D, this follows torch.matmul behavior by temporarily unsqueezing it to 2D, performing the matmul, then squeezing out the added dimension(s).

The function first makes the tensors have the same number of dimensions by unsqueezing leading dimensions with BroadcastSpace. It then aligns any leading (batch) dimensions so that BroadcastSpace can expand to concrete StateSpaces and any non-broadcast StateSpaces are reordered to match. Finally, the right tensor's second-to-last dimension is aligned to the left tensor's last dimension, and torch.matmul is applied.

The contraction always happens between left.dims[-1] and right.dims[-2]. Leading dimensions behave like batch dimensions and follow the broadcast and alignment rules described above. The output keeps all aligned leading dimensions (including any BroadcastSpace that remain), drops the contracted dimension, and appends the right-most dimension from right.

Use cases
  • contract two symbolic matrix/tensor operators while preserving axis labels,
  • multiply batched operators whose batch axes need symbolic alignment,
  • handle vector-matrix, matrix-vector, and vector-vector products with the same API used for higher-rank tensors.

Parameters:

Name Type Description Default
left Tensor

The left tensor operand.

required
right Tensor

The right tensor operand.

required

Returns:

Type Description
Tensor

A tensor with data torch.matmul(left.data, right.data) and dimensions left.dims[:-1] + right.dims[-1:], after the alignment and any 1D squeeze handling.

Raises:

Type Description
ValueError

If either operand is 0D or any StateSpace alignment fails during the broadcast or contraction alignment steps.

Source code in src/qten/linalg/tensors.py
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
@auto_promote
def matmul(left: Tensor, right: Tensor) -> Tensor:
    """
    Perform matrix multiplication between two Tensors with StateSpace-aware
    alignment and torch-style rank handling.

    Supported forms
    ---------------
    [`matmul(left, right)`][qten.linalg.tensors.matmul]
        Functional form.

    [`left @ right`][qten.linalg.tensors.matmul]
        Operator form provided by [`Operable`][qten.abstracts.Operable] and
        dispatched to this function.

    Both operands must be at least 1D. If either operand is 1D, this follows
    `torch.matmul` behavior by temporarily unsqueezing it to 2D, performing the
    matmul, then squeezing out the added dimension(s).

    The function first makes the tensors have the same number of dimensions by
    unsqueezing leading dimensions with [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace]. It then aligns any
    leading (batch) dimensions so that [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace] can expand to concrete
    StateSpaces and any non-broadcast StateSpaces are reordered to match. Finally,
    the right tensor's second-to-last dimension is aligned to the left tensor's
    last dimension, and `torch.matmul` is applied.

    The contraction always happens between `left.dims[-1]` and `right.dims[-2]`.
    Leading dimensions behave like batch dimensions and follow the broadcast and
    alignment rules described above. The output keeps all aligned leading
    dimensions (including any [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace] that remain), drops the contracted
    dimension, and appends the right-most dimension from `right`.

    Use cases
    ---------
    - contract two symbolic matrix/tensor operators while preserving axis
      labels,
    - multiply batched operators whose batch axes need symbolic alignment,
    - handle vector-matrix, matrix-vector, and vector-vector products with the
      same API used for higher-rank tensors.

    Parameters
    ----------
    left : Tensor
        The left tensor operand.
    right : Tensor
        The right tensor operand.

    Returns
    -------
    Tensor
        A tensor with data `torch.matmul(left.data, right.data)` and dimensions
        left.dims[:-1] + right.dims[-1:], after the alignment and any
        1D squeeze handling.

    Raises
    ------
    ValueError
        If either operand is 0D or any StateSpace alignment fails during the
        broadcast or contraction alignment steps.
    """
    left_rank = left.rank()
    right_rank = right.rank()

    if left_rank < 1:
        raise ValueError("Left tensor must have rank at least 1 for matmul!")
    if right_rank < 1:
        raise ValueError("Right tensor must have rank at least 1 for matmul!")

    left, right = _match_dims_for_matmul(left, right)

    # Reconcile batch dimensions using strict union semantics.
    batch_target = union_dims(left.dims[:-2], right.dims[:-2], allow_merge=False)

    # Align only batch dimensions to the shared batch target.
    left_target_dims = batch_target + left.dims[-2:]
    right_target_dims = batch_target + right.dims[-2:]
    left = left.align_all(left_target_dims)
    right = right.align_all(right_target_dims)

    # Materialize data broadcast where any batch axis is still broadcast-backed.
    left = left.expand_to_union(list(left_target_dims))
    right = right.expand_to_union(list(right_target_dims))

    right = right.align(-2, left.dims[-1])
    data = torch.matmul(left.data, right.data)
    new_dims = left.dims[:-1] + right.dims[-1:]

    prod = Tensor(data=data, dims=new_dims)

    if left_rank == 1 and right_rank == 1:
        prod = prod.squeeze(0).squeeze(-1)
    elif right_rank == 1:
        prod = prod.squeeze(-1)
    elif left_rank == 1:
        prod = prod.squeeze(-2)

    return prod

mean

mean(
    tensor: TensorType,
    dim: int | tuple[int, ...] | None = None,
) -> TensorType

Compute the mean over one or more tensor axes.

This mirrors torch.mean for the supported dim forms while updating the symbolic dimension metadata to remove the reduced axes.

Parameters:

Name Type Description Default
tensor Tensor

The tensor to reduce.

required
dim Optional[Union[int, Tuple[int, ...]]]

Reduction axis (or axes). If None, reduce over all dimensions.

None

Returns:

Type Description
TensorType

Tensor with the requested axes reduced and removed from dims, preserving the input wrapper type.

Raises:

Type Description
IndexError

If any requested reduction axis is out of range for the tensor rank.

Source code in src/qten/linalg/tensors.py
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
def mean(
    tensor: TensorType, dim: Optional[Union[int, Tuple[int, ...]]] = None
) -> TensorType:
    """
    Compute the mean over one or more tensor axes.

    This mirrors `torch.mean` for the supported `dim` forms while updating the
    symbolic dimension metadata to remove the reduced axes.

    Parameters
    ----------
    tensor : Tensor
        The tensor to reduce.
    dim : Optional[Union[int, Tuple[int, ...]]], optional
        Reduction axis (or axes). If `None`, reduce over all dimensions.

    Returns
    -------
    TensorType
        Tensor with the requested axes reduced and removed from `dims`,
        preserving the input wrapper type.

    Raises
    ------
    IndexError
        If any requested reduction axis is out of range for the tensor rank.
    """
    if dim is None:
        return replace(tensor, data=tensor.data.mean(), dims=())

    rank_ = tensor.rank()
    if isinstance(dim, int):
        dims_tuple: Tuple[int, ...] = (dim,)
    else:
        dims_tuple = dim

    normalized_dims: list[int] = []
    for d in dims_tuple:
        nd = d
        if nd < 0:
            nd += rank_
        if nd < 0 or nd >= rank_:
            raise IndexError(f"Dimension index {d} out of range for rank {rank_}")
        normalized_dims.append(nd)

    reduced_dims_set = set(normalized_dims)
    reduced = tensor.data.mean(dim=dim)
    new_dims = tuple(
        current_dim
        for idx, current_dim in enumerate(tensor.dims)
        if idx not in reduced_dims_set
    )
    return replace(tensor, data=reduced, dims=new_dims)

norm

norm(
    tensor: TensorType,
    ord: int | float | str | None = None,
    dim: int | tuple[int, int] | None = None,
) -> TensorType

Compute a vector or matrix norm with metadata-aware dimension reduction.

This forwards to torch.linalg.norm for the numeric computation, then removes the reduced axes from the symbolic output dims.

See Also

torch.linalg.norm Official PyTorch reference for the underlying numeric operation. torch.linalg.vector_norm Clearer vector-only norm API in PyTorch. torch.linalg.matrix_norm Clearer matrix-only norm API in PyTorch.

Behavior

The interpretation of ord depends on dim:

  • dim is an int: compute a vector norm along that axis.
  • dim is a 2-tuple: compute a matrix norm over those two axes.
  • dim is None: follow PyTorch's torch.linalg.norm rules. In particular, ord=None flattens the tensor and computes a vector 2-norm, while ord != None expects PyTorch's documented 1D/2D behavior.
Supported ord values

Vector-norm forms (dim is an int) - None - 0 - any finite int or float - float("inf") - -float("inf")

Matrix-norm forms (dim is a 2-tuple) - None - "fro" - "nuc" - 1, -1 - 2, -2 - float("inf") - -float("inf")

Parameters:

Name Type Description Default
tensor Tensor

The tensor to reduce.

required
ord Optional[Union[int, float, str]]

Order of the norm forwarded to torch.linalg.norm.

Common examples: - ord=2 for the Euclidean vector norm or spectral matrix norm - ord=1 for an L1 vector norm or induced 1 matrix norm - ord=float("inf") for max-based norms - ord="fro" for the Frobenius matrix norm - ord="nuc" for the nuclear matrix norm

None
dim Optional[Union[int, Tuple[int, int]]]

Reduction axis or axes.

  • int: vector norm
  • Tuple[int, int]: matrix norm
  • None: use PyTorch's default torch.linalg.norm behavior
None

Returns:

Type Description
TensorType

Tensor containing the requested norm values with reduced axes removed from dims.

Raises:

Type Description
IndexError

If any requested reduction axis is out of range for the tensor rank.

ValueError

If dim contains duplicate axes.

Source code in src/qten/linalg/tensors.py
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
def norm(
    tensor: TensorType,
    ord: Optional[Union[int, float, str]] = None,
    dim: Optional[Union[int, Tuple[int, int]]] = None,
) -> TensorType:
    """
    Compute a vector or matrix norm with metadata-aware dimension reduction.

    This forwards to `torch.linalg.norm` for the numeric computation, then
    removes the reduced axes from the symbolic output dims.

    See Also
    --------
    [`torch.linalg.norm`](https://docs.pytorch.org/docs/stable/generated/torch.linalg.norm.html)
        Official PyTorch reference for the underlying numeric operation.
    [`torch.linalg.vector_norm`](https://docs.pytorch.org/docs/stable/generated/torch.linalg.vector_norm.html)
        Clearer vector-only norm API in PyTorch.
    [`torch.linalg.matrix_norm`](https://docs.pytorch.org/docs/stable/generated/torch.linalg.matrix_norm.html)
        Clearer matrix-only norm API in PyTorch.

    Behavior
    --------
    The interpretation of `ord` depends on `dim`:

    - `dim` is an `int`: compute a vector norm along that axis.
    - `dim` is a 2-tuple: compute a matrix norm over those two axes.
    - `dim is None`: follow PyTorch's `torch.linalg.norm` rules. In
      particular, `ord=None` flattens the tensor and computes a vector 2-norm,
      while `ord != None` expects PyTorch's documented 1D/2D behavior.

    Supported `ord` values
    ----------------------
    Vector-norm forms (`dim` is an `int`)
    - `None`
    - `0`
    - any finite `int` or `float`
    - `float("inf")`
    - `-float("inf")`

    Matrix-norm forms (`dim` is a 2-tuple)
    - `None`
    - `"fro"`
    - `"nuc"`
    - `1`, `-1`
    - `2`, `-2`
    - `float("inf")`
    - `-float("inf")`

    Parameters
    ----------
    tensor : Tensor
        The tensor to reduce.
    ord : Optional[Union[int, float, str]], optional
        Order of the norm forwarded to `torch.linalg.norm`.

        Common examples:
        - `ord=2` for the Euclidean vector norm or spectral matrix norm
        - `ord=1` for an L1 vector norm or induced 1 matrix norm
        - `ord=float("inf")` for max-based norms
        - `ord="fro"` for the Frobenius matrix norm
        - `ord="nuc"` for the nuclear matrix norm
    dim : Optional[Union[int, Tuple[int, int]]], optional
        Reduction axis or axes.

        - `int`: vector norm
        - `Tuple[int, int]`: matrix norm
        - `None`: use PyTorch's default `torch.linalg.norm` behavior

    Returns
    -------
    TensorType
        Tensor containing the requested norm values with reduced axes removed
        from `dims`.

    Raises
    ------
    IndexError
        If any requested reduction axis is out of range for the tensor rank.
    ValueError
        If `dim` contains duplicate axes.
    """
    reduced = torch.linalg.norm(tensor.data, ord=ord, dim=dim)
    if dim is None:
        return replace(tensor, data=reduced, dims=())

    rank_ = tensor.rank()
    dims_tuple: Tuple[int, ...]
    if isinstance(dim, int):
        dims_tuple = (dim,)
    else:
        dims_tuple = dim

    normalized_dims: list[int] = []
    for d in dims_tuple:
        nd = d
        if nd < 0:
            nd += rank_
        if nd < 0 or nd >= rank_:
            raise IndexError(f"Dimension index {d} out of range for rank {rank_}")
        if nd in normalized_dims:
            raise ValueError("norm dim entries must be unique")
        normalized_dims.append(nd)

    reduced_dims_set = set(normalized_dims)
    new_dims = tuple(
        current_dim
        for idx, current_dim in enumerate(tensor.dims)
        if idx not in reduced_dims_set
    )
    return replace(tensor, data=reduced, dims=new_dims)

nonzero

nonzero(
    condition: Tensor,
    as_tuple: bool = True,
    index_type: type[Tensor[Any]] = ...,
) -> tuple[Tensor, ...]
nonzero(
    condition: Tensor,
    as_tuple: bool = True,
    index_type: type[tuple] = tuple,
) -> tuple[tuple[int, ...], ...]
nonzero(
    condition: Tensor,
    as_tuple: bool = True,
    index_type: type[StateSpace[Any]] = StateSpace,
) -> StateSpace[Any]
nonzero(
    condition: Tensor,
    as_tuple: bool = True,
    index_type: type[Any] = ...,
) -> (
    tuple[Tensor, ...]
    | tuple[tuple[int, ...], ...]
    | StateSpace[Any]
)

Return indices of non-zero or True entries.

This currently supports only as_tuple=True and follows torch.nonzero(condition.data, as_tuple=True) semantics.

Supported forms

nonzero(condition) Return one integer Tensor per axis.

nonzero(condition, index_type=tuple) Return Python coordinate tuples.

nonzero(condition, index_type=StateSpace) For rank-1 conditions only, return the selected symbolic subspace.

Parameters:

Name Type Description Default
condition Tensor

Input tensor.

required
as_tuple bool

Must be True.

True
index_type Type[Any]

Requested index representation. Supported values are Tensor, tuple / Tuple, and StateSpace.

Tensor

Returns:

Type Description
Union[Tuple[Tensor, ...], Tuple[Tuple[int, ...], ...], StateSpace]

Index representation selected by index_type.

Notes

This is the public nonzero helper. where(condition) provides the same index extraction behavior through the overloaded where API.

Raises:

Type Description
NotImplementedError

If as_tuple is False.

Source code in src/qten/linalg/tensors.py
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
def nonzero(
    condition: Tensor, as_tuple: bool = True, index_type: Type[Any] = Tensor
) -> Union[
    Tuple[Tensor, ...],
    Tuple[Tuple[int, ...], ...],
    StateSpace,
]:
    """
    Return indices of non-zero or `True` entries.

    This currently supports only `as_tuple=True` and follows
    `torch.nonzero(condition.data, as_tuple=True)` semantics.

    Supported forms
    ---------------
    [`nonzero(condition)`][qten.linalg.tensors.nonzero]
        Return one integer [`Tensor`][qten.linalg.tensors.Tensor] per axis.

    [`nonzero(condition, index_type=tuple)`][qten.linalg.tensors.nonzero]
        Return Python coordinate tuples.

    [`nonzero(condition, index_type=StateSpace)`][qten.linalg.tensors.nonzero]
        For rank-1 conditions only, return the selected symbolic subspace.

    Parameters
    ----------
    condition : Tensor
        Input tensor.
    as_tuple : bool, optional
        Must be `True`.
    index_type : Type[Any], optional
        Requested index representation. Supported values are [`Tensor`][qten.linalg.tensors.Tensor],
        `tuple` / `Tuple`, and [`StateSpace`][qten.symbolics.state_space.StateSpace].

    Returns
    -------
    Union[Tuple[Tensor, ...], Tuple[Tuple[int, ...], ...], StateSpace]
        Index representation selected by `index_type`.

    Notes
    -----
    This is the public nonzero helper. [`where(condition)`][qten.linalg.tensors.where]
    provides the same index extraction behavior through the overloaded `where`
    API.

    Raises
    ------
    NotImplementedError
        If `as_tuple` is `False`.
    """
    if not as_tuple:
        raise NotImplementedError("nonzero currently supports only as_tuple=True")

    rows = torch.nonzero(condition.data, as_tuple=False)
    indices = torch.nonzero(condition.data, as_tuple=True)
    nnz = indices[0].numel() if len(indices) > 0 else 0
    index_dim = IndexSpace.linear(nnz)
    origin = get_origin(index_type)
    if index_type is Tensor:
        return tuple(Tensor(data=idx, dims=(index_dim,)) for idx in indices)
    if index_type is tuple or origin is tuple:
        return tuple(tuple(int(v) for v in row.tolist()) for row in rows)
    if index_type is StateSpace:
        if condition.rank() != 1:
            raise ValueError(
                "StateSpace index output is only supported for rank-1 conditions"
            )
        selected = [int(row[0].item()) for row in rows]
        return condition.dims[0][selected]
    raise TypeError("index_type must be one of Tensor, tuple/Tuple, or StateSpace")

one_hot

one_hot(
    tensor: Tensor[LongTensor], dim: StateSpace
) -> Tensor[torch.LongTensor]

One-hot encode an integer-valued tensor using a provided class StateSpace.

The output appends dim as the last axis, and uses dim.dim as num_classes.

Parameters:

Name Type Description Default
tensor Tensor

Input tensor containing class indices.

required
dim StateSpace

Output class dimension. Class indices are assumed to be ordered as [0, 1, ..., dim.dim - 1].

required

Returns:

Type Description
Tensor

A new tensor with one extra trailing dimension for class channels.

Raises:

Type Description
TypeError

If tensor.data is not integer-valued.

ValueError

If any class index is outside the range 0 <= index < dim.dim.

Source code in src/qten/linalg/tensors.py
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
def one_hot(
    tensor: Tensor[torch.LongTensor], dim: StateSpace
) -> Tensor[torch.LongTensor]:
    """
    One-hot encode an integer-valued tensor using a provided class StateSpace.

    The output appends `dim` as the last axis, and uses `dim.dim` as
    `num_classes`.

    Parameters
    ----------
    tensor : Tensor
        Input tensor containing class indices.
    dim : StateSpace
        Output class dimension. Class indices are assumed to be ordered as
        `[0, 1, ..., dim.dim - 1]`.

    Returns
    -------
    Tensor
        A new tensor with one extra trailing dimension for class channels.

    Raises
    ------
    TypeError
        If `tensor.data` is not integer-valued.
    ValueError
        If any class index is outside the range `0 <= index < dim.dim`.
    """
    if tensor.data.is_floating_point() or tensor.data.is_complex():
        raise TypeError("one_hot expects integer-valued tensor data")

    indices = tensor.data.to(dtype=torch.long)
    if indices.numel() > 0:
        if torch.any(indices < 0) or torch.any(indices >= dim.dim):
            raise ValueError(f"one_hot index out of range for num_classes={dim.dim}")

    return Tensor(
        data=cast(
            torch.LongTensor, torch.nn.functional.one_hot(indices, num_classes=dim.dim)
        ),
        dims=tensor.dims + (dim,),
    )

imag

imag(tensor: TensorType) -> TensorType

Return the imaginary part of a tensor.

The symbolic dimensions are unchanged. For real-valued tensors this returns a zero tensor with the corresponding real dtype.

Source code in src/qten/linalg/tensors.py
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
def imag(tensor: TensorType) -> TensorType:
    """
    Return the imaginary part of a tensor.

    The symbolic dimensions are unchanged. For real-valued tensors this returns
    a zero tensor with the corresponding real dtype.
    """
    if tensor.data.is_complex():
        return replace(tensor, data=cast(T, tensor.data.imag))
    return replace(tensor, data=cast(T, torch.zeros_like(tensor.data)))

isclose

isclose(
    a: TensorType,
    b: Tensor | Scalar,
    rtol: float = 1e-05,
    atol: float = 1e-08,
    equal_nan: bool = False,
) -> TensorType

Perform element-wise approximate equality comparison with dimension-aware alignment and broadcasting.

This returns a bool Tensor mask, unlike allclose, which reduces to a Python bool.

Supported forms

isclose(a, b, ...) Functional form.

a.isclose(b, ...) Method form.

Parameter forms

b : Tensor Compare two tensors after symbolic alignment and broadcast handling.

b : Number The scalar is promoted through Tensor.scalar(b) before applying the same tensor-tensor comparison logic.

Parameters:

Name Type Description Default
a TensorType

Left-hand tensor operand.

required
b Tensor | Number

Right-hand comparison target. If b is a Tensor, it is aligned and broadcast against a. If b is a scalar number, it is promoted through Tensor.scalar(b) before comparison.

required
rtol float

Relative tolerance passed to torch.isclose.

1e-05
atol float

Absolute tolerance passed to torch.isclose.

1e-08
equal_nan bool

Whether NaN values are considered equal.

False

Returns:

Type Description
TensorType

Boolean tensor mask on the merged symbolic output dims.

See Also

torch.isclose Underlying PyTorch element-wise closeness check.

Use cases
  • build boolean masks for thresholding numerical errors,
  • compare a tensor against another tensor or a scalar tolerance target while preserving symbolic output dims.
Source code in src/qten/linalg/tensors.py
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
def isclose(
    a: TensorType,
    b: Union[Tensor, Number],
    rtol: float = 1e-05,
    atol: float = 1e-08,
    equal_nan: bool = False,
) -> TensorType:
    """
    Perform element-wise approximate equality comparison with dimension-aware
    alignment and broadcasting.

    This returns a bool [`Tensor`][qten.linalg.tensors.Tensor] mask, unlike `allclose`, which reduces to a
    Python bool.

    Supported forms
    ---------------
    [`isclose(a, b, ...)`][qten.linalg.tensors.isclose]
        Functional form.

    [`a.isclose(b, ...)`][qten.linalg.tensors.Tensor.isclose]
        Method form.

    Parameter forms
    ---------------
    `b : Tensor`
        Compare two tensors after symbolic alignment and broadcast handling.

    `b : Number`
        The scalar is promoted through `Tensor.scalar(b)` before applying the
        same tensor-tensor comparison logic.

    Parameters
    ----------
    a : TensorType
        Left-hand tensor operand.
    b : Tensor | Number
        Right-hand comparison target. If `b` is a
        [`Tensor`][qten.linalg.tensors.Tensor], it is aligned and broadcast
        against `a`. If `b` is a scalar number, it is promoted through
        `Tensor.scalar(b)` before comparison.
    rtol : float, optional
        Relative tolerance passed to `torch.isclose`.
    atol : float, optional
        Absolute tolerance passed to `torch.isclose`.
    equal_nan : bool, optional
        Whether `NaN` values are considered equal.

    Returns
    -------
    TensorType
        Boolean tensor mask on the merged symbolic output dims.

    See Also
    --------
    [`torch.isclose`](https://pytorch.org/docs/stable/generated/torch.isclose.html)
        Underlying PyTorch element-wise closeness check.

    Use cases
    ---------
    - build boolean masks for thresholding numerical errors,
    - compare a tensor against another tensor or a scalar tolerance target
      while preserving symbolic output dims.
    """
    if not isinstance(b, Tensor):
        b = Tensor.scalar(b)
    return _binary_elementwise_mask_op(
        a,
        b,
        lambda left, right: torch.isclose(
            left, right, rtol=rtol, atol=atol, equal_nan=equal_nan
        ),
    )

ones

ones(
    dims: tuple[StateSpace, ...],
    *,
    device: Device | None = None,
) -> Tensor

Create a one-filled tensor on the requested symbolic dimensions.

Parameters:

Name Type Description Default
dims Tuple[StateSpace, ...]

StateSpace dimensions defining the tensor shape.

required
device Optional[Device]

Device to place the tensor on, by default None (CPU).

None

Returns:

Type Description
Tensor

Tensor of ones with shape == tuple(dim.dim for dim in dims) and dims equal to dims.

Source code in src/qten/linalg/tensors.py
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
def ones(dims: Tuple[StateSpace, ...], *, device: Optional[Device] = None) -> Tensor:
    """
    Create a one-filled tensor on the requested symbolic dimensions.

    Parameters
    ----------
    dims : Tuple[StateSpace, ...]
        StateSpace dimensions defining the tensor shape.
    device : Optional[Device], optional
        Device to place the tensor on, by default None (CPU).

    Returns
    -------
    Tensor
        Tensor of ones with `shape == tuple(dim.dim for dim in dims)` and dims
        equal to `dims`.
    """
    shape = tuple(dim.dim for dim in dims)
    torch_device = device.torch_device() if device is not None else None
    return Tensor(data=torch.ones(shape, device=torch_device), dims=dims)

permute

permute(
    tensor: TensorType, *order: int | Sequence[int]
) -> TensorType

Reorder tensor axes and their symbolic dimensions.

This is the metadata-aware analogue of torch.Tensor.permute. It applies the same permutation to tensor.data and tensor.dims, so the returned tensor keeps its symbolic axes in sync with the raw data layout.

Parameters:

Name Type Description Default
tensor Tensor

Tensor whose axes will be reordered.

required
order Union[int, Sequence[int]]

Desired axis order. This may be passed either as variadic integers or as a single tuple/list.

()

Returns:

Type Description
TensorType

Tensor with permuted data and correspondingly permuted dims, preserving the input wrapper type.

Raises:

Type Description
ValueError

If the permutation length does not match tensor.rank().

Source code in src/qten/linalg/tensors.py
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
def permute(tensor: TensorType, *order: Union[int, Sequence[int]]) -> TensorType:
    """
    Reorder tensor axes and their symbolic dimensions.

    This is the metadata-aware analogue of `torch.Tensor.permute`. It applies
    the same permutation to `tensor.data` and `tensor.dims`, so the returned
    tensor keeps its symbolic axes in sync with the raw data layout.

    Parameters
    ----------
    tensor : Tensor
        Tensor whose axes will be reordered.
    order : Union[int, Sequence[int]]
        Desired axis order. This may be passed either as variadic integers or
        as a single tuple/list.

    Returns
    -------
    TensorType
        Tensor with permuted data and correspondingly permuted `dims`,
        preserving the input wrapper type.

    Raises
    ------
    ValueError
        If the permutation length does not match `tensor.rank()`.
    """
    _order: Tuple[int, ...]
    if len(order) == 1 and isinstance(order[0], (tuple, list)):
        _order = tuple(order[0])
    else:
        # We assume that if it's not a single list/tuple, it's a sequence of ints
        _order = cast(Tuple[int, ...], tuple(order))

    if len(_order) != tensor.rank():
        raise ValueError(
            f"Permutation order length {len(_order)} does not match tensor dimensions {tensor.rank()}!"
        )

    new_data = tensor.data.permute(_order)
    new_dims = tuple(tensor.dims[i] for i in _order)

    return replace(tensor, data=new_data, dims=new_dims)

product_dims

product_dims(
    tensor: TensorType, *indices_group: tuple[int, ...]
) -> TensorType

Combine selected tensor dimensions into product dimensions.

Each entry in indices_group defines one output product dimension. For a group (i0, i1, ..., ik), the returned tensor contains a single axis whose size is the product of the grouped axis sizes and whose StateSpace is self.dims[i0] @ self.dims[i1] @ ... @ self.dims[ik]. Dimensions not listed in any group are preserved as-is.

Negative indices are supported and follow Python indexing rules. Grouped dimensions do not need to be contiguous in the input tensor; the method reorders axes internally, performs one reshape, and returns the result in the canonical output order.

Use cases
  • flatten several symbolic axes into one composite Hilbert or state space,
  • prepare tensors for matrix decompositions or contractions that expect a single product axis.

Parameters:

Name Type Description Default
tensor Tensor

The tensor to modify.

required
indices_group Tuple[int, ...]

One or more non-empty groups of dimension indices to combine. Indices must be unique across all groups (a dimension can belong to at most one group).

()

Returns:

Type Description
TensorType

A new tensor where each requested group is replaced by one product dimension and all non-grouped dimensions are retained.

Raises:

Type Description
IndexError

If any provided index is out of range for the tensor rank.

ValueError

If any group is empty, if a group contains duplicate indices, or if the same index appears in more than one group.

Source code in src/qten/linalg/tensors.py
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
def product_dims(tensor: TensorType, *indices_group: Tuple[int, ...]) -> TensorType:
    """
    Combine selected tensor dimensions into product dimensions.

    Each entry in `indices_group` defines one output product dimension.
    For a group `(i0, i1, ..., ik)`, the returned tensor contains a single
    axis whose size is the product of the grouped axis sizes and whose
    [`StateSpace`][qten.symbolics.state_space.StateSpace] is `self.dims[i0] @ self.dims[i1] @ ... @ self.dims[ik]`.
    Dimensions not listed in any group are preserved as-is.

    Negative indices are supported and follow Python indexing rules.
    Grouped dimensions do not need to be contiguous in the input tensor; the
    method reorders axes internally, performs one reshape, and returns the
    result in the canonical output order.

    Use cases
    ---------
    - flatten several symbolic axes into one composite Hilbert or state space,
    - prepare tensors for matrix decompositions or contractions that expect a
      single product axis.

    Parameters
    ----------
    tensor : Tensor
        The tensor to modify.
    indices_group : Tuple[int, ...]
        One or more non-empty groups of dimension indices to combine.
        Indices must be unique across all groups (a dimension can belong to
        at most one group).

    Returns
    -------
    TensorType
        A new tensor where each requested group is replaced by one product
        dimension and all non-grouped dimensions are retained.

    Raises
    ------
    IndexError
        If any provided index is out of range for the tensor rank.
    ValueError
        If any group is empty, if a group contains duplicate indices, or if
        the same index appears in more than one group.
    """
    if not indices_group:
        return tensor

    rank = tensor.rank()
    normalized_groups, grouped_indices = _product_dims_normalize_groups(
        rank, indices_group
    )
    slots = _product_dims_build_slots(rank, normalized_groups, grouped_indices)

    permute_order = tuple(idx for _, group in slots for idx in group)
    permuted = tensor.permute(permute_order)

    new_shape: list[int] = []
    new_dims: list[StateSpace] = []
    cursor = 0

    def _accumulate_group_size(acc: int, offset: int) -> int:
        return acc * permuted.data.shape[cursor + offset]

    def _tensor_product_dims(acc: StateSpace, g_idx: int) -> StateSpace:
        return cast(StateSpace, acc @ tensor.dims[g_idx])

    for is_grouped, group in slots:
        if is_grouped:
            combined_size = reduce(_accumulate_group_size, range(len(group)), 1)
            combined_dim = reduce(
                _tensor_product_dims, group[1:], tensor.dims[group[0]]
            )
            new_shape.append(combined_size)
            new_dims.append(cast(StateSpace, combined_dim))
        else:
            idx = group[0]
            new_shape.append(permuted.data.shape[cursor])
            new_dims.append(tensor.dims[idx])
        cursor += len(group)

    return replace(
        tensor, data=permuted.data.reshape(tuple(new_shape)), dims=tuple(new_dims)
    )

promote_rank

promote_rank(tensor: Tensor, target_rank: int) -> Tensor

Return tensor with leading broadcast axes prepended to reach target_rank.

This function preserves the existing axis order and values while adding target_rank - tensor.rank() leading singleton axes in tensor.data. The corresponding leading entries in dims are BroadcastSpace().

Parameters:

Name Type Description Default
tensor Tensor

Input tensor.

required
target_rank int

Desired output rank. Must satisfy target_rank >= tensor.rank().

required

Returns:

Type Description
Tensor

tensor if no promotion is needed; otherwise a tensor with prepended broadcast axes and matching prepended BroadcastSpace dims.

Use cases
  • normalize ranks before symmetric binary operations,
  • make scalar/vector/tensor operands participate in one broadcast-aware code path without losing symbolic meaning.

Raises:

Type Description
ValueError

If target_rank < tensor.rank().

Source code in src/qten/linalg/tensors.py
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
def promote_rank(tensor: Tensor, target_rank: int) -> Tensor:
    """
    Return `tensor` with leading broadcast axes prepended to reach `target_rank`.

    This function preserves the existing axis order and values while adding
    `target_rank - tensor.rank()` leading singleton axes in `tensor.data`.
    The corresponding leading entries in `dims` are [`BroadcastSpace()`][qten.symbolics.state_space.BroadcastSpace].

    Parameters
    ----------
    tensor : Tensor
        Input tensor.
    target_rank : int
        Desired output rank. Must satisfy `target_rank >= tensor.rank()`.

    Returns
    -------
    Tensor
        `tensor` if no promotion is needed; otherwise a tensor with prepended
        broadcast axes and matching prepended [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace] dims.

    Use cases
    ---------
    - normalize ranks before symmetric binary operations,
    - make scalar/vector/tensor operands participate in one broadcast-aware
      code path without losing symbolic meaning.

    Raises
    ------
    ValueError
        If `target_rank < tensor.rank()`.
    """
    current_rank = tensor.rank()
    if target_rank < current_rank:
        raise ValueError(
            f"Cannot promote rank {current_rank} tensor to lower target rank {target_rank}"
        )
    if target_rank == current_rank:
        return tensor

    prepend_count = target_rank - current_rank
    new_dims = (BroadcastSpace(),) * prepend_count + tensor.dims
    new_shape = (1,) * prepend_count + tuple(tensor.data.shape)
    return Tensor(data=tensor.data.reshape(new_shape), dims=new_dims)

real

real(tensor: TensorType) -> TensorType

Return the real part of a tensor.

The symbolic dimensions are unchanged. The returned tensor uses the real dtype associated with the input data.

Source code in src/qten/linalg/tensors.py
2577
2578
2579
2580
2581
2582
2583
2584
def real(tensor: TensorType) -> TensorType:
    """
    Return the real part of a tensor.

    The symbolic dimensions are unchanged. The returned tensor uses the real
    dtype associated with the input data.
    """
    return replace(tensor, data=cast(T, tensor.data.real))

rank

rank(tensor: Tensor) -> int

Get the rank (number of dimensions) of the tensor.

Parameters:

Name Type Description Default
tensor Tensor

The tensor whose rank is to be determined.

required

Returns:

Type Description
int

The rank of the tensor.

Source code in src/qten/linalg/tensors.py
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
def rank(tensor: Tensor) -> int:
    """
    Get the rank (number of dimensions) of the tensor.

    Parameters
    ----------
    tensor : Tensor
        The tensor whose rank is to be determined.

    Returns
    -------
    int
        The rank of the tensor.
    """
    return len(tensor.dims)

replace_dim

replace_dim(
    tensor: TensorType, dim: int, new_dim: StateSpace
) -> TensorType

Replace one symbolic dimension without changing tensor data values.

This is a metadata-only operation. It is valid only when new_dim has the same size as the underlying data axis (or is BroadcastSpace() for a singleton axis).

Parameters:

Name Type Description Default
tensor Tensor

The tensor to modify.

required
dim int

The index of the dimension to replace.

required
new_dim StateSpace

The new StateSpace to assign to the dimension.

required

Returns:

Type Description
TensorType

Tensor with unchanged data and the requested replacement dimension.

Raises:

Type Description
IndexError

If dim is out of range for the tensor rank.

ValueError

If new_dim is not size-compatible with the selected data axis.

Source code in src/qten/linalg/tensors.py
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
def replace_dim(tensor: TensorType, dim: int, new_dim: StateSpace) -> TensorType:
    """
    Replace one symbolic dimension without changing tensor data values.

    This is a metadata-only operation. It is valid only when `new_dim` has the
    same size as the underlying data axis (or is
    [`BroadcastSpace()`][qten.symbolics.state_space.BroadcastSpace] for a
    singleton axis).

    Parameters
    ----------
    tensor : Tensor
        The tensor to modify.
    dim : int
        The index of the dimension to replace.
    new_dim : StateSpace
        The new StateSpace to assign to the dimension.

    Returns
    -------
    TensorType
        Tensor with unchanged data and the requested replacement dimension.

    Raises
    ------
    IndexError
        If `dim` is out of range for the tensor rank.
    ValueError
        If `new_dim` is not size-compatible with the selected data axis.
    """
    if dim < 0:
        dim += len(tensor.dims)

    if dim < 0 or dim >= len(tensor.dims):
        raise IndexError(
            f"Dimension index {dim} out of range for tensor of rank {len(tensor.dims)}"
        )

    current_size = tensor.data.shape[dim]

    # Check size compatibility.
    # BroadcastSpace represents a singleton axis and only matches size 1.
    if isinstance(new_dim, BroadcastSpace):
        if current_size != 1:
            raise ValueError(
                f"Cannot replace dimension of size {current_size} with BroadcastSpace (expects size 1)."
            )
    elif new_dim.dim != current_size:
        raise ValueError(
            f"New StateSpace size {new_dim.dim} does not match tensor data size {current_size} at dimension {dim}!"
        )

    new_dims = list(tensor.dims)
    new_dims[dim] = new_dim
    return replace(tensor, dims=tuple(new_dims))

squeeze

squeeze(tensor: TensorType, dim: int) -> TensorType

Remove a singleton broadcast axis from a tensor.

Only axes labeled by BroadcastSpace() are removed. If the specified axis is not a broadcast axis, the input tensor is returned unchanged.

Parameters:

Name Type Description Default
tensor Tensor

The tensor to squeeze.

required
dim int

The dimension to squeeze.

required

Returns:

Type Description
TensorType

Tensor with the requested broadcast axis removed, preserving the input wrapper type.

Source code in src/qten/linalg/tensors.py
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
def squeeze(tensor: TensorType, dim: int) -> TensorType:
    """
    Remove a singleton broadcast axis from a tensor.

    Only axes labeled by
    [`BroadcastSpace()`][qten.symbolics.state_space.BroadcastSpace] are
    removed. If the specified axis is not a broadcast axis, the input tensor is
    returned unchanged.

    Parameters
    ----------
    tensor : Tensor
        The tensor to squeeze.
    dim : int
        The dimension to squeeze.

    Returns
    -------
    TensorType
        Tensor with the requested broadcast axis removed, preserving the input
        wrapper type.
    """
    if dim < 0:
        dim = dim + len(tensor.dims)
    if not isinstance(tensor.dims[dim], BroadcastSpace):
        return tensor  # No squeezing needed if not BroadcastSpace

    new_data = tensor.data.squeeze(dim)
    new_dims = tensor.dims[:dim] + tensor.dims[dim + 1 :]

    return replace(tensor, data=new_data, dims=new_dims)

transpose

transpose(
    tensor: TensorType, dim0: int, dim1: int
) -> TensorType

Swap two tensor axes and their symbolic dimensions.

This is a two-axis specialization of permute. Both the raw data and the corresponding StateSpace metadata are transposed together.

Parameters:

Name Type Description Default
tensor Tensor

Tensor whose axes will be swapped.

required
dim0 int

The first dimension to transpose.

required
dim1 int

The second dimension to transpose.

required

Returns:

Type Description
TensorType

Tensor with the selected axes exchanged, preserving the input wrapper type.

Source code in src/qten/linalg/tensors.py
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
def transpose(tensor: TensorType, dim0: int, dim1: int) -> TensorType:
    """
    Swap two tensor axes and their symbolic dimensions.

    This is a two-axis specialization of
    [`permute`][qten.linalg.tensors.permute]. Both the raw data and the
    corresponding [`StateSpace`][qten.symbolics.state_space.StateSpace]
    metadata are transposed together.

    Parameters
    ----------
    tensor : Tensor
        Tensor whose axes will be swapped.
    dim0 : int
        The first dimension to transpose.
    dim1 : int
        The second dimension to transpose.

    Returns
    -------
    TensorType
        Tensor with the selected axes exchanged, preserving the input wrapper
        type.
    """
    new_data = tensor.data.transpose(dim0, dim1)

    # Convert tuple to list to modify
    new_dims_list = list(tensor.dims)
    # Swap elements
    new_dims_list[dim0], new_dims_list[dim1] = new_dims_list[dim1], new_dims_list[dim0]

    return replace(tensor, data=new_data, dims=tuple(new_dims_list))

union_dims

union_dims(
    *dims: tuple[StateSpace, ...], allow_merge: bool = False
) -> tuple[StateSpace, ...]

Compute a broadcast-compatible union of multiple dimension tuples.

Use cases
  • determine the target metadata layout for broadcasted arithmetic,
  • validate whether two or more symbolic tensor layouts can participate in a common operation,
  • build the merged dims later passed to align_all and expand_to_union.

This function merges dimension metadata axis-by-axis across one or more tuples of StateSpaces. All input tuples must have the same rank.

Merge rule per axis (allow_merge=False)
Merge rule per axis (allow_merge=True)
  • Uses StateSpace union semantics directly (left_dim + right_dim) after rank checks. This supports disjoint-axis union behavior used by tensor add.

Parameters:

Name Type Description Default
dims Tuple[StateSpace, ...]

One or more dimension tuples to merge.

()
allow_merge bool

If False, enforces strict compatibility for concrete dimensions. If True, merges concrete dimensions via +.

False

Returns:

Type Description
Tuple[StateSpace, ...]

Merged dimensions with the same rank as each input tuple.

Raises:

Type Description
ValueError

If no tuples are provided, ranks differ, or any axis is incompatible in strict mode.

Source code in src/qten/linalg/tensors.py
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
def union_dims(
    *dims: Tuple[StateSpace, ...], allow_merge: bool = False
) -> Tuple[StateSpace, ...]:
    """
    Compute a broadcast-compatible union of multiple dimension tuples.

    Use cases
    ---------
    - determine the target metadata layout for broadcasted arithmetic,
    - validate whether two or more symbolic tensor layouts can participate in a
      common operation,
    - build the merged dims later passed to
      [`align_all`][qten.linalg.tensors.align_all] and
      [`expand_to_union`][qten.linalg.tensors.expand_to_union].

    This function merges dimension metadata axis-by-axis across one or more
    tuples of [`StateSpace`][qten.symbolics.state_space.StateSpace]s. All input tuples must have the same rank.

    Merge rule per axis (`allow_merge=False`)
    -------------------
    - [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace] + concrete [`StateSpace`][qten.symbolics.state_space.StateSpace] -> concrete [`StateSpace`][qten.symbolics.state_space.StateSpace]
    - [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace] + [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace] -> [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace]
    - concrete + concrete:
      - if `same_rays(...)` is `True`, keeps the first (left-most) one
      - otherwise raises `ValueError`

    Merge rule per axis (`allow_merge=True`)
    -----------------------------------------------
    - Uses StateSpace union semantics directly (`left_dim + right_dim`) after
      rank checks. This supports disjoint-axis union behavior used by tensor add.

    Parameters
    ----------
    dims : Tuple[StateSpace, ...]
        One or more dimension tuples to merge.
    allow_merge : bool, optional
        If `False`, enforces strict compatibility for concrete dimensions.
        If `True`, merges concrete dimensions via `+`.

    Returns
    -------
    Tuple[StateSpace, ...]
        Merged dimensions with the same rank as each input tuple.

    Raises
    ------
    ValueError
        If no tuples are provided, ranks differ, or any axis is incompatible
        in strict mode.
    """
    if not dims:
        raise ValueError("union_dims expects at least one dims tuple")

    rank = len(dims[0])
    if any(len(current) != rank for current in dims):
        ranks = ", ".join(str(len(current)) for current in dims)
        raise ValueError(
            f"union_dims requires all dims tuples to have the same rank: got ranks=[{ranks}]"
        )

    merged = list(dims[0])
    for current in dims[1:]:
        for axis, (left_dim, right_dim) in enumerate(zip(merged, current)):
            if not allow_merge:
                if isinstance(left_dim, BroadcastSpace):
                    merged[axis] = right_dim
                    continue
                if isinstance(right_dim, BroadcastSpace):
                    continue
                if same_rays(left_dim, right_dim):
                    continue
                raise ValueError(
                    f"union_dims incompatible at axis {axis}: "
                    f"{type(left_dim).__name__}:{left_dim.dim} vs "
                    f"{type(right_dim).__name__}:{right_dim.dim}; "
                    f"left={_format_dims(tuple(merged))}, right={_format_dims(current)}"
                )
            merged[axis] = cast(StateSpace, left_dim + right_dim)

    return tuple(merged)

unsqueeze

unsqueeze(tensor: TensorType, dim: int) -> TensorType

Insert a singleton broadcast axis into a tensor.

This is the metadata-aware analogue of torch.unsqueeze. The new axis is labeled with BroadcastSpace() so later alignment and broadcasting operations can treat it as a symbolic singleton axis.

Parameters:

Name Type Description Default
tensor Tensor

The tensor to unsqueeze.

required
dim int

The dimension to unsqueeze.

required

Returns:

Type Description
TensorType

Tensor with one extra singleton axis and a matching inserted BroadcastSpace dim.

Source code in src/qten/linalg/tensors.py
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
def unsqueeze(tensor: TensorType, dim: int) -> TensorType:
    """
    Insert a singleton broadcast axis into a tensor.

    This is the metadata-aware analogue of `torch.unsqueeze`. The new axis is
    labeled with [`BroadcastSpace()`][qten.symbolics.state_space.BroadcastSpace]
    so later alignment and broadcasting operations can treat it as a symbolic
    singleton axis.

    Parameters
    ----------
    tensor : Tensor
        The tensor to unsqueeze.
    dim : int
        The dimension to unsqueeze.

    Returns
    -------
    TensorType
        Tensor with one extra singleton axis and a matching inserted
        [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace] dim.
    """
    if dim < 0:
        dim = dim + len(tensor.dims) + 1
    new_data = tensor.data.unsqueeze(dim)
    new_dims = tensor.dims[:dim] + (BroadcastSpace(),) + tensor.dims[dim:]

    return replace(tensor, data=new_data, dims=new_dims)

where

where(
    condition: Tensor[BoolTensor],
    input: Tensor,
    other: Tensor,
) -> Tensor
where(
    condition: Tensor[BoolTensor],
    index_type: type[Tensor[Any]] = ...,
) -> tuple[Tensor, ...]
where(
    condition: Tensor[BoolTensor],
    index_type: type[tuple] = tuple,
) -> tuple[tuple[int, ...], ...]
where(
    condition: Tensor[BoolTensor],
    index_type: type[StateSpace[Any]] = StateSpace,
) -> StateSpace[Any]
where(
    condition: Tensor[BoolTensor],
    index_type: type[Any] = ...,
) -> (
    tuple[Tensor, ...]
    | tuple[tuple[int, ...], ...]
    | StateSpace[Any]
)

Dispatch to the overloaded public where implementations.

Supported forms

where(condition, input, other) Element-wise selection, analogous to torch.where(condition, input, other).

where(condition, index_type=Tensor) Return nonzero locations as one integer Tensor per axis.

where(condition, index_type=tuple) Return nonzero locations as Python coordinate tuples.

where(condition, index_type=StateSpace) For rank-1 conditions only, return the selected StateSpace.

This wrapper exists so multimethod dispatch errors can be translated into user-facing TypeError exceptions when the underlying implementation rejects a particular call signature.

Parameters:

Name Type Description Default
*args Any

Positional arguments forwarded to the overloaded where variants.

()
**kwargs Any

Keyword arguments forwarded to the overloaded where variants.

{}

Returns:

Type Description
Any

Result produced by the matching overloaded where implementation.

Raises:

Type Description
TypeError

If multimethod dispatch fails because the matched implementation raised TypeError.

DispatchError

If dispatch fails for another reason.

Source code in src/qten/linalg/tensors.py
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
def where(*args, **kwargs):
    """
    Dispatch to the overloaded public [`where`][qten.linalg.tensors.where]
    implementations.

    Supported forms
    ---------------
    [`where(condition, input, other)`][qten.linalg.tensors.where]
        Element-wise selection, analogous to `torch.where(condition, input, other)`.

    [`where(condition, index_type=Tensor)`][qten.linalg.tensors.where]
        Return nonzero locations as one integer [`Tensor`][qten.linalg.tensors.Tensor]
        per axis.

    [`where(condition, index_type=tuple)`][qten.linalg.tensors.where]
        Return nonzero locations as Python coordinate tuples.

    [`where(condition, index_type=StateSpace)`][qten.linalg.tensors.where]
        For rank-1 conditions only, return the selected
        [`StateSpace`][qten.symbolics.state_space.StateSpace].

    This wrapper exists so multimethod dispatch errors can be translated into
    user-facing `TypeError` exceptions when the underlying implementation
    rejects a particular call signature.

    Parameters
    ----------
    *args : Any
        Positional arguments forwarded to the overloaded `where` variants.
    **kwargs : Any
        Keyword arguments forwarded to the overloaded `where` variants.

    Returns
    -------
    Any
        Result produced by the matching overloaded `where` implementation.

    Raises
    ------
    TypeError
        If multimethod dispatch fails because the matched implementation raised
        `TypeError`.
    DispatchError
        If dispatch fails for another reason.
    """
    try:
        return _where(*args, **kwargs)
    except DispatchError as ex:
        if isinstance(ex.__cause__, TypeError):
            raise ex.__cause__
        raise

zeros

zeros(
    dims: tuple[StateSpace, ...],
    *,
    device: Device | None = None,
) -> Tensor

Create a zero-filled tensor on the requested symbolic dimensions.

Parameters:

Name Type Description Default
dims Tuple[StateSpace, ...]

StateSpace dimensions defining the tensor shape.

required
device Optional[Device]

Device to place the tensor on, by default None (CPU).

None

Returns:

Type Description
Tensor

Tensor of zeros with shape == tuple(dim.dim for dim in dims) and dims equal to dims.

Source code in src/qten/linalg/tensors.py
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
def zeros(dims: Tuple[StateSpace, ...], *, device: Optional[Device] = None) -> Tensor:
    """
    Create a zero-filled tensor on the requested symbolic dimensions.

    Parameters
    ----------
    dims : Tuple[StateSpace, ...]
        StateSpace dimensions defining the tensor shape.
    device : Optional[Device], optional
        Device to place the tensor on, by default None (CPU).

    Returns
    -------
    Tensor
        Tensor of zeros with `shape == tuple(dim.dim for dim in dims)` and
        dims equal to `dims`.
    """
    shape = tuple(dim.dim for dim in dims)
    torch_device = device.torch_device() if device is not None else None
    return Tensor(data=torch.zeros(shape, device=torch_device), dims=dims)

Device dataclass

Device(
    name: Literal["cpu", "gpu"], index: Optional[int] = None
)

Lightweight immutable device descriptor used by QTen.

The public device model is intentionally small: - "cpu" represents host execution. - "gpu" represents accelerated execution.

For GPU devices, index optionally stores a CUDA device index. This index is only meaningful on CUDA-capable systems.

Parameters:

Name Type Description Default
name Literal['cpu', 'gpu']

The logical device family.

required
index Optional[int]

Optional CUDA device index. This should only be set when name is "gpu".

`None`

Attributes:

Name Type Description
name Literal['cpu', 'gpu']

Logical device family.

index Optional[int]

Optional CUDA device index for GPU execution.

name instance-attribute

name: Literal['cpu', 'gpu']

Logical device family. QTen uses "cpu" for host execution and "gpu" for CUDA-backed execution.

index class-attribute instance-attribute

index: Optional[int] = None

Optional CUDA device index for GPU execution. This is meaningful only when name == "gpu".

__repr__ class-attribute instance-attribute

__repr__ = __str__

new staticmethod

new(name: str) -> Device

Parse a user-facing device string into a Device.

Supported inputs
  • "cpu"
  • "gpu"
  • "gpu:<index>", where <index> is a non-negative integer

Parameters:

Name Type Description Default
name str

Device string to parse.

required

Returns:

Type Description
Device

Parsed immutable device descriptor.

Raises:

Type Description
ValueError

If the input does not match one of the supported formats.

Examples:

Device.new("cpu")
Device.new("gpu:0")
Source code in src/qten/utils/devices.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
@staticmethod
def new(name: str) -> "Device":
    """
    Parse a user-facing device string into a [`Device`][qten.utils.devices.Device].

    Supported inputs
    ----------------
    - `"cpu"`
    - `"gpu"`
    - `"gpu:<index>"`, where ``<index>`` is a non-negative integer

    Parameters
    ----------
    name : str
        Device string to parse.

    Returns
    -------
    Device
        Parsed immutable device descriptor.

    Raises
    ------
    ValueError
        If the input does not match one of the supported formats.

    Examples
    --------
    ```python
    Device.new("cpu")
    Device.new("gpu:0")
    ```
    """
    if name == "cpu":
        return Device(name="cpu")
    if name.startswith("gpu"):
        parts = name.split(":")
        if len(parts) == 1:
            return Device(name="gpu")
        elif len(parts) == 2 and parts[1].isdigit():
            return Device(name="gpu", index=int(parts[1]))
    raise ValueError(f"Invalid device name: {name}")

torch_device

torch_device() -> torch.device

Resolve this logical device into the concrete PyTorch backend device.

Resolution is runtime-dependent: - "cpu" always maps to torch.device("cpu"). - "gpu" prefers CUDA when available.

When CUDA is selected, an explicit index is used if present. Otherwise, the current CUDA device reported by PyTorch is used.

Returns:

Type Description
device

Concrete PyTorch device corresponding to this logical device.

Raises:

Type Description
ValueError

If self.name is not a supported logical device value.

RuntimeError

If a GPU device is requested but neither CUDA nor MPS is available in the current environment.

Source code in src/qten/utils/devices.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def torch_device(self) -> torch.device:
    """
    Resolve this logical device into the concrete PyTorch backend device.

    Resolution is runtime-dependent:
    - `"cpu"` always maps to ``torch.device("cpu")``.
    - `"gpu"` prefers CUDA when available.

    When CUDA is selected, an explicit ``index`` is used if present.
    Otherwise, the current CUDA device reported by PyTorch is used.

    Returns
    -------
    torch.device
        Concrete PyTorch device corresponding to this logical device.

    Raises
    ------
    ValueError
        If ``self.name`` is not a supported logical device value.
    RuntimeError
        If a GPU device is requested but neither CUDA nor MPS is available
        in the current environment.
    """
    if self.name == "cpu":
        return torch.device("cpu")
    if not self.name == "gpu":
        raise ValueError(f"Invalid device name: {self.name}")
    if torch.cuda.is_available():
        index = (
            self.index if self.index is not None else torch.cuda.current_device()
        )
        return torch.device("cuda", index)
    raise RuntimeError("The current system does not have GPU devices!")

__str__

__str__() -> str

Format the device using QTen's logical device syntax.

Returns:

Type Description
str

"cpu", "gpu", or "gpu:<index>".

Raises:

Type Description
ValueError

If self.name is not a supported logical device value.

Source code in src/qten/utils/devices.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def __str__(self) -> str:
    """
    Format the device using QTen's logical device syntax.

    Returns
    -------
    str
        "cpu", `"gpu"`, or `"gpu:<index>"`.

    Raises
    ------
    ValueError
        If ``self.name`` is not a supported logical device value.
    """
    match self.name:
        case "cpu":
            return "cpu"
        case "gpu":
            if self.index is not None:
                return f"gpu:{self.index}"
            return "gpu"
        case _:
            raise ValueError(f"Invalid device name: {self.name}")

io

Versioned pickle-based persistence helpers.

This module provides a lightweight filesystem store for experiment outputs and other trusted Python objects. Objects are saved under an IO root, grouped by an active environment name, and versioned automatically as version_<n>.pkl files.

Repository usage

Use iodir() to configure the root storage directory, env() to select a project or run namespace, and save() / load() to persist trusted objects.

Notes

The storage format uses Python pickle. Only load files produced by trusted code and from trusted locations.

Examples:

from qten.utils import io

io.iodir(".runs")
io.env("trial-a")

version = io.save({"energy": -1.0}, "results")
rows = io.list_saved("results")
latest = io.load("results")
same = io.load("results", version=version)

iodir

iodir(
    path: Optional[Union[str, PathLike[str]]] = None,
) -> str

Get or set the base directory for IO storage.

If a path is provided, it becomes the active IO directory. The directory is created if needed. If no path is provided, the current IO directory is returned; when unset, defaults to ".data".

Parameters:

Name Type Description Default
path str or PathLike[str]

Filesystem path to use as the IO root. If omitted, the existing root is returned, defaulting to .data for the current process.

None

Returns:

Type Description
str

The active IO directory path. The directory is created before returning.

Examples:

from qten.utils import io

io.iodir(".runs")
Source code in src/qten/utils/io.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def iodir(path: Optional[Union[str, os.PathLike[str]]] = None) -> str:
    """
    Get or set the base directory for IO storage.

    If a path is provided, it becomes the active IO directory. The directory
    is created if needed. If no path is provided, the current IO directory
    is returned; when unset, defaults to ".data".

    Parameters
    ----------
    path : str or os.PathLike[str], optional
        Filesystem path to use as the IO root. If omitted, the existing root is
        returned, defaulting to `.data` for the current process.

    Returns
    -------
    str
        The active IO directory path. The directory is created before returning.

    Examples
    --------
    ```python
    from qten.utils import io

    io.iodir(".runs")
    ```
    """
    global _io_dir
    if path is not None:
        _io_dir = os.path.abspath(os.fspath(path))
        _logger.debug("IO directory set to: %s", _io_dir)
    dir_path = _io_dir or ".data"
    os.makedirs(dir_path, exist_ok=True)
    return dir_path

env

env(name: Optional[str] = None) -> str

Get or set the active environment name under the IO directory.

When called without a name, returns the currently active environment if one was set during this process, otherwise raises a RuntimeError. When a name is provided, ensures a subdirectory exists under the IO directory and sets it as the active environment.

Parameters:

Name Type Description Default
name str

Environment name to activate, or None to query the current one.

None

Returns:

Type Description
str

The current or newly-set environment name.

Raises:

Type Description
RuntimeError

If no environment is set and name is None.

Examples:

from qten.utils import io

io.iodir(".runs")
io.env("trial-a")
Source code in src/qten/utils/io.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def env(name: Optional[str] = None) -> str:
    """
    Get or set the active environment name under the IO directory.

    When called without a name, returns the currently active environment if
    one was set during this process, otherwise raises a RuntimeError.
    When a name is provided, ensures a subdirectory exists under the IO
    directory and sets it as the active environment.

    Parameters
    ----------
    name : str, optional
        Environment name to activate, or `None` to query the current one.

    Returns
    -------
    str
        The current or newly-set environment name.

    Raises
    ------
    RuntimeError
        If no environment is set and `name` is `None`.

    Examples
    --------
    ```python
    from qten.utils import io

    io.iodir(".runs")
    io.env("trial-a")
    ```
    """
    global _all_env
    global _current_env
    if name is None:
        if _current_env is not None:
            return _current_env
        raise RuntimeError("No environment is currently set.")

    if _all_env is None:
        root = iodir()
        _all_env = {
            entry
            for entry in os.listdir(root)
            if os.path.isdir(os.path.join(root, entry))
        }

    if name not in _all_env:
        os.makedirs(os.path.join(iodir(), name), exist_ok=True)
        _all_env.add(name)
        _logger.debug("Environment created: %s", name)

    _current_env = name
    _logger.debug("Environment set to: %s", _current_env)
    return _current_env

save

save(obj: Any, name: str) -> int

Save an object to disk as a pickle with automatic versioning.

Parameters:

Name Type Description Default
obj Any

Object to serialize.

required
name str

Logical name used to group versions under the active environment.

required

Returns:

Type Description
int

The assigned version number.

Raises:

Type Description
PicklingError

If the object cannot be pickled.

RuntimeError

If no active environment has been selected with env().

Examples:

from qten.utils import io

io.env("trial-a")
version = io.save({"energy": -1.0}, "results")
Source code in src/qten/utils/io.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def save(obj: Any, name: str) -> int:
    """
    Save an object to disk as a pickle with automatic versioning.

    Parameters
    ----------
    obj : Any
        Object to serialize.
    name : str
        Logical name used to group versions under the active environment.

    Returns
    -------
    int
        The assigned version number.

    Raises
    ------
    pickle.PicklingError
        If the object cannot be pickled.
    RuntimeError
        If no active environment has been selected with [`env()`][qten.utils.io.env].

    Examples
    --------
    ```python
    from qten.utils import io

    io.env("trial-a")
    version = io.save({"energy": -1.0}, "results")
    ```
    """
    root = os.path.join(iodir(), env())
    name_dir = os.path.join(root, name)
    os.makedirs(name_dir, exist_ok=True)

    versions = _scan_versions(name_dir)
    version = max(versions) + 1 if versions else 1
    path = os.path.join(name_dir, f"version_{version}.pkl")
    try:
        with open(path, "wb") as file:
            pickle.dump(obj, file, protocol=pickle.HIGHEST_PROTOCOL)
    except Exception as exc:
        raise pickle.PicklingError("Object is not picklable.") from exc
    _logger.debug("Saved %s version %s to: %s", name, version, path)
    return version

load

load(name: str, version: int = -1) -> Any

Load a previously saved object by name and version.

Parameters:

Name Type Description Default
name str

Logical name used to group saved versions.

required
version int

Version to load; use -1 for the latest version.

-1

Returns:

Type Description
Any

The deserialized object.

Raises:

Type Description
FileNotFoundError

If the name or version does not exist.

UnpicklingError

If the pickle data is corrupted.

RuntimeError

If no active environment has been selected with env().

Notes

Only load data you trust; pickle is not secure against malicious data.

Examples:

from qten.utils import io

latest = io.load("results")
first = io.load("results", version=1)
Source code in src/qten/utils/io.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def load(name: str, version: int = -1) -> Any:
    """
    Load a previously saved object by name and version.

    Parameters
    ----------
    name : str
        Logical name used to group saved versions.
    version : int, default=-1
        Version to load; use `-1` for the latest version.

    Returns
    -------
    Any
        The deserialized object.

    Raises
    ------
    FileNotFoundError
        If the name or version does not exist.
    pickle.UnpicklingError
        If the pickle data is corrupted.
    RuntimeError
        If no active environment has been selected with [`env()`][qten.utils.io.env].

    Notes
    -----
    Only load data you trust; pickle is not secure against malicious data.

    Examples
    --------
    ```python
    from qten.utils import io

    latest = io.load("results")
    first = io.load("results", version=1)
    ```
    """
    root = os.path.join(iodir(), env())
    name_dir = os.path.join(root, name)
    versions = _scan_versions(name_dir)
    if not versions:
        raise FileNotFoundError(f"No saved versions for name: {name}")

    if version == -1:
        version = max(versions)
    elif version not in versions:
        raise FileNotFoundError(f"Version {version} not found for name: {name}")

    path = os.path.join(name_dir, f"version_{version}.pkl")
    with open(path, "rb") as file:
        obj = pickle.load(file)
    return obj

list_saved

list_saved(name: str) -> List[Dict[str, Any]]

List saved versions for a name.

Parameters:

Name Type Description Default
name str

Logical name used to group saved versions.

required

Returns:

Type Description
list[dict[str, Any]]

Rows with version, created, and size_mib entries for each saved version, sorted by version number.

Raises:

Type Description
FileNotFoundError

If the name does not exist.

RuntimeError

If no active environment has been selected with env().

Source code in src/qten/utils/io.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
def list_saved(name: str) -> List[Dict[str, Any]]:
    """
    List saved versions for a name.

    Parameters
    ----------
    name : str
        Logical name used to group saved versions.

    Returns
    -------
    list[dict[str, Any]]
        Rows with `version`, `created`, and `size_mib` entries for each saved
        version, sorted by version number.

    Raises
    ------
    FileNotFoundError
        If the name does not exist.
    RuntimeError
        If no active environment has been selected with [`env()`][qten.utils.io.env].
    """
    root = os.path.join(iodir(), env())
    name_dir = os.path.join(root, name)
    if not os.path.isdir(name_dir):
        raise FileNotFoundError(f"No saved versions for name: {name}")

    rows: List[Dict[str, Any]] = []
    with os.scandir(name_dir) as entries:
        for entry in entries:
            if not entry.is_file():
                continue
            fname = entry.name
            if not (fname.startswith("version_") and fname.endswith(".pkl")):
                continue
            ver_str = fname[len("version_") : -len(".pkl")]
            try:
                version = int(ver_str)
            except ValueError:
                continue
            stat = entry.stat()
            created = datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat()
            size_mib = stat.st_size / (1024 * 1024)
            rows.append(
                {
                    "version": version,
                    "created": created,
                    "size_mib": size_mib,
                }
            )

    rows.sort(key=lambda row: row["version"])
    return rows