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.
  • MomentumBlockTensor Momentum-pair-resolved block-matrix tensor for band-space transforms.
  • 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

MomentumBlockTensor dataclass

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

Bases: Tensor

Rank-3 tensor subtype for momentum-labelled matrix blocks.

A MomentumBlockTensor stores matrix blocks on its last two axes and a MomentumBlockSpace on axis 0. The common layout is (MomentumBlockSpace, StateSpace, StateSpace).

Operations such as transpose(1, 2) and h(1, 2) are specialized so the momentum-pair metadata is updated together with the matrix-leg swap.

Notes

This subtype does not support arbitrary axis-reordering operations.

Valid reorderings: transpose(1, 2), permute(0, 2, 1), h(1, 2), and h(-2, -1). Invalid reorderings: transpose(0, 1), transpose(0, 2), and any permute(...) that moves axis 0 away from the front.

The reason is semantic, not just shape-related: axis 0 stores momentum-pair labels whose orientation must track the left/right matrix legs. Only swapping the two matrix axes has a well-defined update rule for those labels.

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.

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.

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__

kron

kron(other: Tensor) -> Tensor

Compute the StateSpace-aware Kronecker product with another tensor.

This method delegates to kron(left, right). The Kronecker product is position-wise across axes: each output axis is built from the tensor product of the corresponding symbolic dimensions.

Parameters:

Name Type Description Default
other Tensor

Right operand of the Kronecker product.

required

Returns:

Type Description
Tensor

Tensor with data torch.kron(self.data, other.data) and position-wise tensor-product dimensions.

See Also

kron(left, right) Functional form with full semantics.

Source code in src/qten/linalg/tensors.py
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
@override
def kron(self, other: "Tensor") -> "Tensor":
    """
    Compute the StateSpace-aware Kronecker product with another tensor.

    This method delegates to [`kron(left, right)`][qten.linalg.tensors.kron].
    The Kronecker product is position-wise across axes: each output axis is
    built from the tensor product of the corresponding symbolic dimensions.

    Parameters
    ----------
    other : Tensor
        Right operand of the Kronecker product.

    Returns
    -------
    Tensor
        Tensor with data `torch.kron(self.data, other.data)` and
        position-wise tensor-product dimensions.

    See Also
    --------
    [`kron(left, right)`][qten.linalg.tensors.kron]
        Functional form with full semantics.
    """
    return kron(self, other)

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)

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
1382
1383
1384
1385
1386
1387
1388
1389
1390
@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)))

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)

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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
@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
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
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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
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
610
611
612
613
614
615
616
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
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
690
691
692
693
694
695
696
697
698
699
700
701
702
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
704
705
706
707
708
709
710
711
712
713
714
715
716
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
718
719
720
721
722
723
724
725
726
727
728
729
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
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
798
799
800
801
802
803
804
805
806
807
808
809
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 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
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
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 | Tensor

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
Union[Self, Tensor]

Boolean tensor after reduction. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

See Also

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

Source code in src/qten/linalg/tensors.py
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
def all(
    self, dim: Optional[Union[int, Tuple[int, ...]]] = None, keepdim: bool = False
) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        Boolean tensor after reduction. For subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may
        downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].

    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
 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
 936
 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
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
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
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
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 | Tensor

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
Union[Self, Tensor]

The unsqueezed tensor. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

Source code in src/qten/linalg/tensors.py
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
def unsqueeze(self, dim: int) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        The unsqueezed tensor. For subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may
        downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].
    """
    return unsqueeze(self, dim)

squeeze

squeeze(dim: int) -> Self | Tensor

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
Union[Self, Tensor]

The squeezed tensor. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

Source code in src/qten/linalg/tensors.py
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
def squeeze(self, dim: int) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        The squeezed tensor. For subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may
        downgrade to a plain
        [`Tensor`][qten.linalg.tensors.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
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
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
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
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
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
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 | Tensor

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
Union[Self, Tensor]

A new tensor with the specified dimensions reduced. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

Source code in src/qten/linalg/tensors.py
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
def mean(
    self, dim: Optional[Union[int, Tuple[int, ...]]] = None
) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        A new tensor with the specified dimensions reduced. For subclasses
        marked with [`strict_dims`][qten.linalg.tensors.strict_dims], this
        may downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].
    """
    return mean(self, dim)

norm

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

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
Union[Self, Tensor]

A new tensor with the specified dimensions reduced. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

See Also

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

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
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
def norm(
    self,
    ord: Optional[Union[int, float, str]] = None,
    dim: Optional[Union[int, Tuple[int, int]]] = None,
) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        A new tensor with the specified dimensions reduced. For subclasses
        marked with [`strict_dims`][qten.linalg.tensors.strict_dims], this
        may downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].

    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 | Tensor

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
Union[Self, Tensor]

A new tensor with the specified dimension reduced. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

Source code in src/qten/linalg/tensors.py
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
def argmax(self, dim: int) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        A new tensor with the specified dimension reduced. For subclasses
        marked with [`strict_dims`][qten.linalg.tensors.strict_dims], this
        may downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].
    """
    return argmax(self, dim)

argmin

argmin(dim: int) -> Self | Tensor

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
Union[Self, Tensor]

A new tensor with the specified dimension reduced. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

Source code in src/qten/linalg/tensors.py
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
def argmin(self, dim: int) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        A new tensor with the specified dimension reduced. For subclasses
        marked with [`strict_dims`][qten.linalg.tensors.strict_dims], this
        may downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].
    """
    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
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
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
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
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()

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
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
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
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
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
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
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
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
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
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
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)

update_dim

update_dim(
    dim: int, func: Callable[[StateSpace], StateSpace]
) -> Self

Transform the StateSpace at the specified dimension with a callback.

The callback receives the current dimension metadata and must return the replacement StateSpace. Size validation and index normalization follow the same rules as replace_dim.

See Also

update_dim(tensor, dim, func) Functional form with the full metadata update semantics.

Parameters:

Name Type Description Default
dim int

The index of the dimension to update.

required
func Callable[[StateSpace], StateSpace]

Callback that maps the current StateSpace to a replacement.

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
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
def update_dim(self, dim: int, func: Callable[[StateSpace], StateSpace]) -> Self:
    """
    Transform the StateSpace at the specified dimension with a callback.

    The callback receives the current dimension metadata and must return
    the replacement [`StateSpace`][qten.symbolics.state_space.StateSpace].
    Size validation and index normalization follow the same rules as
    [`replace_dim`][qten.linalg.tensors.Tensor.replace_dim].

    See Also
    --------
    [`update_dim(tensor, dim, func)`][qten.linalg.tensors.update_dim]
        Functional form with the full metadata update semantics.

    Parameters
    ----------
    dim : int
        The index of the dimension to update.
    func : Callable[[StateSpace], StateSpace]
        Callback that maps the current StateSpace to a replacement.

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

factorize_dim

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

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
Union[Self, Tensor]

A new tensor with the specified dimension factorized. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

See Also

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

Source code in src/qten/linalg/tensors.py
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
def factorize_dim(
    self, dim: int, rule: StateSpaceFactorization
) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        A new tensor with the specified dimension factorized. For
        subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may
        downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].

    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 | Tensor

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
Union[Self, Tensor]

A new tensor where each requested group is replaced by one product dimension and all non-grouped dimensions are retained. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

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
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
def product_dims(self, *indices_group: Tuple[int, ...]) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        A new tensor where each requested group is replaced by one product
        dimension and all non-grouped dimensions are retained. For
        subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may
        downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].

    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
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
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)

__post_init__

__post_init__()

Finalize construction.

The base Tensor post-init is executed so any forced-device construction logic still applies.

Source code in src/qten/linalg/_mb_tensor.py
204
205
206
207
208
209
210
211
def __post_init__(self):
    """
    Finalize construction.

    The base [`Tensor`][qten.linalg.tensors.Tensor] post-init is executed
    so any forced-device construction logic still applies.
    """
    super().__post_init__()

__getitem__

__getitem__(key: Any) -> Tensor

Index the tensor and preserve the block subtype when the layout survives.

This delegates all indexing semantics to Tensor.__getitem__, then re-wraps the result as a MomentumBlockTensor only when the indexed output still satisfies the fixed (MomentumBlockSpace, StateSpace, StateSpace) layout. Selections that drop an axis or otherwise break that invariant still return a plain Tensor.

Source code in src/qten/linalg/_mb_tensor.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def __getitem__(self, key: Any) -> Tensor:
    """
    Index the tensor and preserve the block subtype when the layout survives.

    This delegates all indexing semantics to
    [`Tensor.__getitem__`][qten.linalg.tensors.Tensor.__getitem__], then
    re-wraps the result as a [`MomentumBlockTensor`][qten.MomentumBlockTensor]
    only when the indexed output still satisfies the fixed
    `(MomentumBlockSpace, StateSpace, StateSpace)` layout. Selections that
    drop an axis or otherwise break that invariant still return a plain
    [`Tensor`][qten.linalg.tensors.Tensor].
    """
    result = super().__getitem__(key)
    try:
        return MomentumBlockTensor(data=result.data, dims=result.dims)
    except ValueError:
        return result

__repr__

__repr__() -> str

Return a compact developer-facing representation of the tensor.

This mirrors Tensor.__repr__ while preserving the concrete subtype name.

Source code in src/qten/linalg/_mb_tensor.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def __repr__(self) -> str:
    """
    Return a compact developer-facing representation of the tensor.

    This mirrors [`Tensor.__repr__`][qten.linalg.tensors.Tensor.__repr__]
    while preserving the concrete subtype name.
    """
    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} {type(self).__name__} "
        f"grad={self.data.requires_grad} shape={shape_repr}>"
    )

Tensor dataclass

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

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

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.

Strict-dims subclasses

Some tensor subclasses represent a fixed symbolic layout rather than an arbitrary tuple of axes. For those subclasses, preserving the Python type after every generic tensor operation would be incorrect. Examples include wrappers whose first axis must have a special semantic meaning, or whose rank is fixed by construction.

Such subclasses should opt into the strict_dims policy. Once marked:

  • layout-preserving operations may still return the same subclass,
  • operations that would break the subclass invariant should downgrade the result to a plain Tensor,
  • callers may therefore rely on the subclass type only while the defining structural invariant is still present in dims.

This policy keeps generic tensor code reusable while preventing accidental survival of a misleading subtype after reductions, reshapes, or other structure-changing transformations.

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, update_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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
@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
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
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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
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
610
611
612
613
614
615
616
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
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
690
691
692
693
694
695
696
697
698
699
700
701
702
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
704
705
706
707
708
709
710
711
712
713
714
715
716
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
718
719
720
721
722
723
724
725
726
727
728
729
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
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
798
799
800
801
802
803
804
805
806
807
808
809
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 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
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
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 | Tensor

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
Union[Self, Tensor]

Boolean tensor after reduction. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

See Also

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

Source code in src/qten/linalg/tensors.py
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
def all(
    self, dim: Optional[Union[int, Tuple[int, ...]]] = None, keepdim: bool = False
) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        Boolean tensor after reduction. For subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may
        downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].

    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
 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
 936
 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
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
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
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
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 | Tensor

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
Union[Self, Tensor]

The unsqueezed tensor. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

Source code in src/qten/linalg/tensors.py
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
def unsqueeze(self, dim: int) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        The unsqueezed tensor. For subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may
        downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].
    """
    return unsqueeze(self, dim)

squeeze

squeeze(dim: int) -> Self | Tensor

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
Union[Self, Tensor]

The squeezed tensor. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

Source code in src/qten/linalg/tensors.py
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
def squeeze(self, dim: int) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        The squeezed tensor. For subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may
        downgrade to a plain
        [`Tensor`][qten.linalg.tensors.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
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
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
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
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
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
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 | Tensor

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
Union[Self, Tensor]

A new tensor with the specified dimensions reduced. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

Source code in src/qten/linalg/tensors.py
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
def mean(
    self, dim: Optional[Union[int, Tuple[int, ...]]] = None
) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        A new tensor with the specified dimensions reduced. For subclasses
        marked with [`strict_dims`][qten.linalg.tensors.strict_dims], this
        may downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].
    """
    return mean(self, dim)

norm

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

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
Union[Self, Tensor]

A new tensor with the specified dimensions reduced. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

See Also

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

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
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
def norm(
    self,
    ord: Optional[Union[int, float, str]] = None,
    dim: Optional[Union[int, Tuple[int, int]]] = None,
) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        A new tensor with the specified dimensions reduced. For subclasses
        marked with [`strict_dims`][qten.linalg.tensors.strict_dims], this
        may downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].

    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 | Tensor

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
Union[Self, Tensor]

A new tensor with the specified dimension reduced. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

Source code in src/qten/linalg/tensors.py
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
def argmax(self, dim: int) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        A new tensor with the specified dimension reduced. For subclasses
        marked with [`strict_dims`][qten.linalg.tensors.strict_dims], this
        may downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].
    """
    return argmax(self, dim)

argmin

argmin(dim: int) -> Self | Tensor

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
Union[Self, Tensor]

A new tensor with the specified dimension reduced. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

Source code in src/qten/linalg/tensors.py
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
def argmin(self, dim: int) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        A new tensor with the specified dimension reduced. For subclasses
        marked with [`strict_dims`][qten.linalg.tensors.strict_dims], this
        may downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].
    """
    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
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
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
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
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
1382
1383
1384
1385
1386
1387
1388
1389
1390
@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
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
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
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
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
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
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
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
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
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
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)

update_dim

update_dim(
    dim: int, func: Callable[[StateSpace], StateSpace]
) -> Self

Transform the StateSpace at the specified dimension with a callback.

The callback receives the current dimension metadata and must return the replacement StateSpace. Size validation and index normalization follow the same rules as replace_dim.

See Also

update_dim(tensor, dim, func) Functional form with the full metadata update semantics.

Parameters:

Name Type Description Default
dim int

The index of the dimension to update.

required
func Callable[[StateSpace], StateSpace]

Callback that maps the current StateSpace to a replacement.

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
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
def update_dim(self, dim: int, func: Callable[[StateSpace], StateSpace]) -> Self:
    """
    Transform the StateSpace at the specified dimension with a callback.

    The callback receives the current dimension metadata and must return
    the replacement [`StateSpace`][qten.symbolics.state_space.StateSpace].
    Size validation and index normalization follow the same rules as
    [`replace_dim`][qten.linalg.tensors.Tensor.replace_dim].

    See Also
    --------
    [`update_dim(tensor, dim, func)`][qten.linalg.tensors.update_dim]
        Functional form with the full metadata update semantics.

    Parameters
    ----------
    dim : int
        The index of the dimension to update.
    func : Callable[[StateSpace], StateSpace]
        Callback that maps the current StateSpace to a replacement.

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

__getitem__

__getitem__(key: Any) -> Tensor

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
1552
1553
1554
1555
1556
1557
1558
1559
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
1589
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
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
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 | Tensor

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
Union[Self, Tensor]

A new tensor with the specified dimension factorized. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

See Also

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

Source code in src/qten/linalg/tensors.py
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
def factorize_dim(
    self, dim: int, rule: StateSpaceFactorization
) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        A new tensor with the specified dimension factorized. For
        subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may
        downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].

    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 | Tensor

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
Union[Self, Tensor]

A new tensor where each requested group is replaced by one product dimension and all non-grouped dimensions are retained. For subclasses marked with strict_dims, this may downgrade to a plain Tensor.

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
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
def product_dims(self, *indices_group: Tuple[int, ...]) -> Union[Self, "Tensor"]:
    """
    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
    -------
    Union[Self, Tensor]
        A new tensor where each requested group is replaced by one product
        dimension and all non-grouped dimensions are retained. For
        subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may
        downgrade to a plain
        [`Tensor`][qten.linalg.tensors.Tensor].

    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)

kron

kron(other: Tensor) -> Tensor

Compute the StateSpace-aware Kronecker product with another tensor.

This method delegates to kron(left, right). The Kronecker product is position-wise across axes: each output axis is built from the tensor product of the corresponding symbolic dimensions.

Parameters:

Name Type Description Default
other Tensor

Right operand of the Kronecker product.

required

Returns:

Type Description
Tensor

Tensor with data torch.kron(self.data, other.data) and position-wise tensor-product dimensions.

See Also

kron(left, right) Functional form with full semantics.

Source code in src/qten/linalg/tensors.py
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
@override
def kron(self, other: "Tensor") -> "Tensor":
    """
    Compute the StateSpace-aware Kronecker product with another tensor.

    This method delegates to [`kron(left, right)`][qten.linalg.tensors.kron].
    The Kronecker product is position-wise across axes: each output axis is
    built from the tensor product of the corresponding symbolic dimensions.

    Parameters
    ----------
    other : Tensor
        Right operand of the Kronecker product.

    Returns
    -------
    Tensor
        Tensor with data `torch.kron(self.data, other.data)` and
        position-wise tensor-product dimensions.

    See Also
    --------
    [`kron(left, right)`][qten.linalg.tensors.kron]
        Functional form with full semantics.
    """
    return kron(self, other)

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
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
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
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
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
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
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
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
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
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 | Tensor

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
Union[TensorType, Tensor]

Boolean tensor with reduced dimensions. For subclasses marked with strict_dims, this may return a plain Tensor.

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
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
3846
3847
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
3883
3884
3885
3886
3887
3888
3889
def all(
    tensor: TensorType,
    dim: Optional[Union[int, Tuple[int, ...]]] = None,
    keepdim: bool = False,
) -> Union[TensorType, Tensor]:
    """
    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
    -------
    Union[TensorType, Tensor]
        Boolean tensor with reduced dimensions. For subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may return a
        plain [`Tensor`][qten.linalg.tensors.Tensor].

    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 cast(
            TensorType,
            _wrap_tensor_result(
                tensor,
                data=torch.all(tensor.data),
                dims=(),
                preserve_strict=False,
            ),
        )

    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 cast(
        TensorType,
        _wrap_tensor_result(
            tensor,
            data=reduced,
            dims=new_dims,
            preserve_strict=False,
        ),
    )

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
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
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
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
145
146
def __init__(self, device: Device | str):
    self.device = Device.new(device) if isinstance(device, str) else device

device instance-attribute

device: 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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
165
166
167
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
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 | Tensor

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
Union[TensorType, Tensor]

Integer-valued tensor with the reduced axis removed from dims. For subclasses marked with strict_dims, this may return a plain Tensor.

Raises:

Type Description
IndexError

If dim is out of range for the tensor rank.

Source code in src/qten/linalg/tensors.py
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
def argmax(tensor: TensorType, dim: int) -> Union[TensorType, Tensor]:
    """
    Return indices of maximum values along one tensor axis.

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

    Returns
    -------
    Union[TensorType, Tensor]
        Integer-valued tensor with the reduced axis removed from `dims`. For
        subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may return a
        plain [`Tensor`][qten.linalg.tensors.Tensor].

    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 cast(
        TensorType,
        _wrap_tensor_result(
            tensor,
            data=tensor.data.argmax(dim=dim),
            dims=tensor.dims[:dim] + tensor.dims[dim + 1 :],
            preserve_strict=False,
        ),
    )

argmin

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

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
Union[TensorType, Tensor]

Integer-valued tensor with the reduced axis removed from dims. For subclasses marked with strict_dims, this may return a plain Tensor.

Raises:

Type Description
IndexError

If dim is out of range for the tensor rank.

Source code in src/qten/linalg/tensors.py
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
def argmin(tensor: TensorType, dim: int) -> Union[TensorType, Tensor]:
    """
    Return indices of minimum values along one tensor axis.

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

    Returns
    -------
    Union[TensorType, Tensor]
        Integer-valued tensor with the reduced axis removed from `dims`. For
        subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may return a
        plain [`Tensor`][qten.linalg.tensors.Tensor].

    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 cast(
        TensorType,
        _wrap_tensor_result(
            tensor,
            data=tensor.data.argmin(dim=dim),
            dims=tensor.dims[:dim] + tensor.dims[dim + 1 :],
            preserve_strict=False,
        ),
    )

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
3435
3436
3437
3438
3439
3440
3441
3442
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
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
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
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
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
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
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
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
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
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)

einsum

einsum(equation: str, *operands: Tensor) -> Tensor

Contract tensors with Einstein summation while aligning symbolic dims.

This mirrors torch.einsum at the numeric level, but first reconciles every labeled axis through QTen's StateSpace semantics:

  • same labeled axes must be symbolically compatible,
  • BroadcastSpace() may expand to a concrete labeled space,
  • axes with the same rays but different ordering are permuted into a shared target ordering before contraction.
Equation guide

The equation uses the same label syntax as torch.einsum, with labels restricted to ASCII letters [A-Za-z].

  • Each input operand is described by one comma-separated label term.
  • Labels that appear in multiple operands identify axes that should be multiplied together.
  • Labels omitted from the output are summed out.
  • Labels kept in the output determine the order of the output dims.
  • ... is supported and follows torch's broadcast convention for unnamed axes. It may appear at the start, middle, or end of a term.
  • ...ij means "match the last two labeled axes and let ... absorb the preceding axes"; i...j means "match the first labeled axis, the last labeled axis, and let ... absorb the axes in between".
  • If any input term uses ..., QTen normalizes any input term that omits it by prepending a leading ellipsis in the internal torch.einsum equation. This lets mixed equations such as "...ij,ij->...ij" behave like torch-style broadcasted contractions.
  • When a term originally omits ..., QTen pads that operand with leading singleton broadcast axes (via unsqueeze(0)) and uses the leading-ellipsis form in the normalized torch.einsum equation. For example, "i...j,ij->i...j" is internally reconciled by treating the ij operand as a leading-ellipsis term rather than inserting singleton axes into the middle of that operand.
  • QTen only normalizes input terms. The explicit output term, if present, is preserved as written.
  • Repeating a label within one operand follows diagonal semantics. Those axes must already have matching sizes before any cross-operand alignment, and QTen does not expand a singleton BroadcastSpace() axis just to satisfy a repeated subscript within the same operand.

For example:

  • "ij,ij->ij" means elementwise multiplication.
  • "ij,jk->ik" means matrix multiplication over the shared j axis.
  • "abc,dbe->acde" means multiply over the shared b axis and keep the surviving axes in the explicit output order (a, c, d, e).
  • "...ij,ij->...ij" means "broadcast the ij operand across the leading unnamed axes of the other operand, then keep those axes in the output".
  • "i...j,ij->i...j" means "broadcast the ij operand across the unnamed middle axes between i and j".
Symbolic alignment rules

Before dispatching to torch.einsum, QTen aligns axes label-by-label:

  • if two axes with the same label already share the same StateSpace, nothing changes,
  • if they have the same rays in a different order, the operand is permuted to the first compatible non-BroadcastSpace() ordering encountered for that label,
  • if one side is BroadcastSpace(), it is expanded to the concrete shared space,
  • if two same-labeled concrete axes are not symbolically compatible, the call raises ValueError.

When multiple same-ray orderings are possible, swapping operand order can therefore change the output dims ordering for shared labels.

This means einsum compatibility is stricter than raw shape-only tensor math: matching sizes alone are not enough when a label represents a symbolic axis.

Examples:

Elementwise product with broadcast:

left = Tensor(data=torch.randn(2, 1), dims=(row_space, BroadcastSpace()))
right = Tensor(data=torch.randn(1, 3), dims=(BroadcastSpace(), col_space))

out = einsum("ij,ij->ij", left, right)
# out.dims == (row_space, col_space)

Matrix multiplication:

left = Tensor(data=torch.randn(m.dim, k.dim), dims=(m, k))
right = Tensor(data=torch.randn(k.dim, n.dim), dims=(k, n))

out = einsum("ij,jk->ik", left, right)
# out.dims == (m, n)

Mixed leading ellipsis:

batch = IndexSpace.linear(5)
i = IndexSpace.linear(2)
j = IndexSpace.linear(3)

left = Tensor(data=torch.randn(batch.dim, i.dim, j.dim), dims=(batch, i, j))
right = Tensor(data=torch.randn(i.dim, j.dim), dims=(i, j))

out = einsum("...ij,ij->...ij", left, right)
# Equivalent numeric contraction: torch.einsum("...ij,...ij->...ij", ...)
# out.dims == (batch, i, j)

Mixed middle ellipsis:

i = IndexSpace.linear(2)
middle = IndexSpace.linear(4)
j = IndexSpace.linear(3)

left = Tensor(data=torch.randn(i.dim, middle.dim, j.dim), dims=(i, middle, j))
right = Tensor(data=torch.randn(i.dim, j.dim), dims=(i, j))

out = einsum("i...j,ij->i...j", left, right)
# Equivalent numeric contraction: torch.einsum("i...j,i...j->i...j", ...)
# out.dims == (i, middle, j)

Mixed trailing ellipsis:

i = IndexSpace.linear(2)
j = IndexSpace.linear(3)
tail = IndexSpace.linear(4)

left = Tensor(data=torch.randn(i.dim, j.dim, tail.dim), dims=(i, j, tail))
right = Tensor(data=torch.randn(i.dim, j.dim), dims=(i, j))

out = einsum("ij...,ij->ij...", left, right)
# Equivalent numeric contraction: torch.einsum("ij...,ij...->ij...", ...)
# out.dims == (i, j, tail)

Repeated labels within one operand:

tensor = Tensor(
    data=torch.randn(space_ab.dim, space_ba.dim),
    dims=(space_ab, space_ba),
)

out = einsum("ii->i", tensor)
# The second axis is aligned to the first before taking the diagonal.
# out.dims == (space_ab,)

Repeated labels do not use BroadcastSpace expansion:

tensor = Tensor(
    data=torch.randn(1, shared.dim),
    dims=(BroadcastSpace(), shared),
)

# Raises ValueError because repeated-label axes must already match in size.
out = einsum("ii->i", tensor)

Higher-rank contraction over one shared index:

out = einsum("abc,dbe->acde", x, y)

This computes \(out[a, c, d, e] = \sum_b x[a, b, c] \; y[d, b, e]\).

Higher-rank contraction over multiple shared indices:

out = einsum("abcd,bcde->ae", x, y)

This sums over the shared b, c, and d labels and keeps only the surviving a and e axes in the output.

Parameters:

Name Type Description Default
equation str

Einstein summation equation in the same format accepted by torch.einsum. Label characters must be ASCII letters [A-Za-z].

required
*operands Tensor

Input tensors whose ranks must match the equation terms after any ... expansion.

()

Returns:

Type Description
Tensor

Tensor whose data is computed by torch.einsum on the aligned operand data and whose dims follow the einsum output labels.

Raises:

Type Description
ValueError

If the equation uses unsupported label characters, does not match the operand ranks, or if any shared label maps to incompatible symbolic dimensions.

See Also

matmul Specialized contraction helper for standard matrix multiplication. align Axis-alignment primitive used to reconcile same-labeled symbolic dims.

Source code in src/qten/linalg/tensors.py
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
def einsum(equation: str, *operands: Tensor) -> Tensor:
    r"""
    Contract tensors with Einstein summation while aligning symbolic dims.

    This mirrors `torch.einsum` at the numeric level, but first reconciles
    every labeled axis through QTen's [`StateSpace`][qten.symbolics.state_space.StateSpace]
    semantics:

    - same labeled axes must be symbolically compatible,
    - [`BroadcastSpace()`][qten.symbolics.state_space.BroadcastSpace] may
      expand to a concrete labeled space,
    - axes with the same rays but different ordering are permuted into a
      shared target ordering before contraction.

    Equation guide
    --------------
    The equation uses the same label syntax as `torch.einsum`, with labels
    restricted to ASCII letters `[A-Za-z]`.

    - Each input operand is described by one comma-separated label term.
    - Labels that appear in multiple operands identify axes that should be
      multiplied together.
    - Labels omitted from the output are summed out.
    - Labels kept in the output determine the order of the output `dims`.
    - `...` is supported and follows torch's broadcast convention for unnamed
      axes. It may appear at the start, middle, or end of a term.
    - `...ij` means "match the last two labeled axes and let `...` absorb the
      preceding axes"; `i...j` means "match the first labeled axis, the last
      labeled axis, and let `...` absorb the axes in between".
    - If any input term uses `...`, QTen normalizes any input term that omits
      it by prepending a leading ellipsis in the internal `torch.einsum`
      equation. This lets mixed equations such as `"...ij,ij->...ij"` behave
      like torch-style broadcasted contractions.
    - When a term originally omits `...`, QTen pads that operand with leading
      singleton broadcast axes (via `unsqueeze(0)`) and uses the leading-ellipsis
      form in the normalized `torch.einsum` equation. For example,
      `"i...j,ij->i...j"` is internally reconciled by treating the `ij` operand
      as a leading-ellipsis term rather than inserting singleton axes into the
      middle of that operand.
    - QTen only normalizes input terms. The explicit output term, if present,
      is preserved as written.
    - Repeating a label within one operand follows diagonal semantics. Those
      axes must already have matching sizes before any cross-operand
      alignment, and QTen does not expand a singleton
      [`BroadcastSpace()`][qten.symbolics.state_space.BroadcastSpace] axis just
      to satisfy a repeated subscript within the same operand.

    For example:

    - `"ij,ij->ij"` means elementwise multiplication.
    - `"ij,jk->ik"` means matrix multiplication over the shared `j` axis.
    - `"abc,dbe->acde"` means multiply over the shared `b` axis and keep the
      surviving axes in the explicit output order `(a, c, d, e)`.
    - `"...ij,ij->...ij"` means "broadcast the `ij` operand across the leading
      unnamed axes of the other operand, then keep those axes in the output".
    - `"i...j,ij->i...j"` means "broadcast the `ij` operand across the unnamed
      middle axes between `i` and `j`".

    Symbolic alignment rules
    ------------------------
    Before dispatching to `torch.einsum`, QTen aligns axes label-by-label:

    - if two axes with the same label already share the same
      [`StateSpace`][qten.symbolics.state_space.StateSpace], nothing changes,
    - if they have the same rays in a different order, the operand is
      permuted to the first compatible non-[`BroadcastSpace()`][qten.symbolics.state_space.BroadcastSpace]
      ordering encountered for that label,
    - if one side is [`BroadcastSpace()`][qten.symbolics.state_space.BroadcastSpace],
      it is expanded to the concrete shared space,
    - if two same-labeled concrete axes are not symbolically compatible, the
      call raises `ValueError`.

    When multiple same-ray orderings are possible, swapping operand order can
    therefore change the output `dims` ordering for shared labels.

    This means einsum compatibility is stricter than raw shape-only tensor
    math: matching sizes alone are not enough when a label represents a
    symbolic axis.

    Examples
    --------
    Elementwise product with broadcast:

    ```python
    left = Tensor(data=torch.randn(2, 1), dims=(row_space, BroadcastSpace()))
    right = Tensor(data=torch.randn(1, 3), dims=(BroadcastSpace(), col_space))

    out = einsum("ij,ij->ij", left, right)
    # out.dims == (row_space, col_space)
    ```

    Matrix multiplication:

    ```python
    left = Tensor(data=torch.randn(m.dim, k.dim), dims=(m, k))
    right = Tensor(data=torch.randn(k.dim, n.dim), dims=(k, n))

    out = einsum("ij,jk->ik", left, right)
    # out.dims == (m, n)
    ```

    Mixed leading ellipsis:

    ```python
    batch = IndexSpace.linear(5)
    i = IndexSpace.linear(2)
    j = IndexSpace.linear(3)

    left = Tensor(data=torch.randn(batch.dim, i.dim, j.dim), dims=(batch, i, j))
    right = Tensor(data=torch.randn(i.dim, j.dim), dims=(i, j))

    out = einsum("...ij,ij->...ij", left, right)
    # Equivalent numeric contraction: torch.einsum("...ij,...ij->...ij", ...)
    # out.dims == (batch, i, j)
    ```

    Mixed middle ellipsis:

    ```python
    i = IndexSpace.linear(2)
    middle = IndexSpace.linear(4)
    j = IndexSpace.linear(3)

    left = Tensor(data=torch.randn(i.dim, middle.dim, j.dim), dims=(i, middle, j))
    right = Tensor(data=torch.randn(i.dim, j.dim), dims=(i, j))

    out = einsum("i...j,ij->i...j", left, right)
    # Equivalent numeric contraction: torch.einsum("i...j,i...j->i...j", ...)
    # out.dims == (i, middle, j)
    ```

    Mixed trailing ellipsis:

    ```python
    i = IndexSpace.linear(2)
    j = IndexSpace.linear(3)
    tail = IndexSpace.linear(4)

    left = Tensor(data=torch.randn(i.dim, j.dim, tail.dim), dims=(i, j, tail))
    right = Tensor(data=torch.randn(i.dim, j.dim), dims=(i, j))

    out = einsum("ij...,ij->ij...", left, right)
    # Equivalent numeric contraction: torch.einsum("ij...,ij...->ij...", ...)
    # out.dims == (i, j, tail)
    ```

    Repeated labels within one operand:

    ```python
    tensor = Tensor(
        data=torch.randn(space_ab.dim, space_ba.dim),
        dims=(space_ab, space_ba),
    )

    out = einsum("ii->i", tensor)
    # The second axis is aligned to the first before taking the diagonal.
    # out.dims == (space_ab,)
    ```

    Repeated labels do not use BroadcastSpace expansion:

    ```python
    tensor = Tensor(
        data=torch.randn(1, shared.dim),
        dims=(BroadcastSpace(), shared),
    )

    # Raises ValueError because repeated-label axes must already match in size.
    out = einsum("ii->i", tensor)
    ```

    Higher-rank contraction over one shared index:

    ```python
    out = einsum("abc,dbe->acde", x, y)
    ```

    This computes
    \(out[a, c, d, e] = \sum_b x[a, b, c] \; y[d, b, e]\).

    Higher-rank contraction over multiple shared indices:

    ```python
    out = einsum("abcd,bcde->ae", x, y)
    ```

    This sums over the shared `b`, `c`, and `d` labels and keeps only the
    surviving `a` and `e` axes in the output.

    Parameters
    ----------
    equation : str
        Einstein summation equation in the same format accepted by
        `torch.einsum`. Label characters must be ASCII letters `[A-Za-z]`.
    *operands : Tensor
        Input tensors whose ranks must match the equation terms after any
        `...` expansion.

    Returns
    -------
    Tensor
        Tensor whose data is computed by `torch.einsum` on the aligned operand
        data and whose `dims` follow the einsum output labels.

    Raises
    ------
    ValueError
        If the equation uses unsupported label characters, does not match the
        operand ranks, or if any shared label maps to incompatible symbolic
        dimensions.

    See Also
    --------
    [`matmul`][qten.linalg.tensors.matmul]
        Specialized contraction helper for standard matrix multiplication.
    [`align`][qten.linalg.tensors.align]
        Axis-alignment primitive used to reconcile same-labeled symbolic dims.
    """
    (
        normalized_equation,
        expanded_terms,
        output_labels,
        normalized_operands,
    ) = _normalize_einsum_operands(equation, operands)

    for term, operand in zip(expanded_terms, normalized_operands):
        _validate_einsum_repeated_labels(term, operand)

    label_dims: Dict[str, StateSpace] = {}
    for term, operand in zip(expanded_terms, normalized_operands):
        for axis, label in enumerate(term):
            label_dims[label] = _merge_einsum_dim(
                label_dims.get(label), operand.dims[axis], label
            )

    aligned_operands: list[Tensor] = []
    for term, operand in zip(expanded_terms, normalized_operands):
        current = operand
        for axis, label in enumerate(term):
            current = current.align(axis, label_dims[label])
        aligned_operands.append(current)

    promoted_operands = _promote_einsum_operands(aligned_operands)
    data = torch.einsum(
        normalized_equation, *(operand.data for operand in promoted_operands)
    )
    dims = tuple(label_dims[label] for label in output_labels)
    return Tensor(data=data, dims=dims)

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
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
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
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 tensor on the requested symbolic dimensions.

This helper interprets dims[-2:] as the matrix axes. When leading dimensions are present, it broadcasts the identity across those axes so the returned tensor preserves the full dims tuple.

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

Identity tensor with dims equal to dims.

Raises:

Type Description
ValueError

If dims has rank less than 2.

Source code in src/qten/linalg/tensors.py
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
def eye(dims: Tuple[StateSpace, ...], *, device: Optional[Device] = None) -> Tensor:
    """
    Create an identity tensor on the requested symbolic dimensions.

    This helper interprets `dims[-2:]` as the matrix axes. When leading
    dimensions are present, it broadcasts the identity across those axes so the
    returned tensor preserves the full `dims` tuple.

    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
        Identity tensor with dims equal to `dims`.

    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)}!"
        )
    rows = dims[-2].dim
    cols = dims[-1].dim
    leading_shape = tuple(dim.dim for dim in dims[:-2])
    torch_device = device.torch_device() if device is not None else None
    data = torch.eye(rows, cols, device=torch_device)
    if leading_shape:
        data = data.reshape((1,) * len(leading_shape) + (rows, cols)).expand(
            leading_shape + (rows, cols)
        )
    return Tensor(data=data, dims=dims)

factorize_dim

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

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
Union[TensorType, Tensor]

Tensor with the requested axis replaced by multiple factor axes. For subclasses marked with strict_dims, this may return a plain Tensor.

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
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
def factorize_dim(
    tensor: TensorType, dim: int, rule: StateSpaceFactorization
) -> Union[TensorType, Tensor]:
    """
    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
    -------
    Union[TensorType, Tensor]
        Tensor with the requested axis replaced by multiple factor axes. For
        subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may return a
        plain [`Tensor`][qten.linalg.tensors.Tensor].

    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 cast(
        TensorType,
        _wrap_tensor_result(
            tensor,
            data=new_data,
            dims=new_dims,
            preserve_strict=False,
        ),
    )

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
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
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)

kron

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

Compute the StateSpace-aware Kronecker product between two tensors.

Semantics

This function applies torch.kron(left.data, right.data) and propagates symbolic metadata axis-by-axis:

  • The operands must have the same rank.
  • For each axis i, output dim i is left.dims[i] @ right.dims[i].
  • Axis pairs are matched by position, not by name or irrep content. The i-th dim of left is combined only with the i-th dim of right.
  • Non-broadcast axes must implement HasKroneckerProduct.
  • For Hilbert-space-like dims, the basis-level tensor product requires disjoint concrete irrep types between the paired dims. For example, a dim whose basis states contain irrep types (int, str) can be combined with one containing (float,), but combining it with one containing (int,) is rejected because int appears on both sides.
  • BroadcastSpace is treated as a neutral singleton axis, so BroadcastSpace @ X and X @ BroadcastSpace both map to X.
Allowed dim products

Let \(L_i = \mathrm{left.dims}[i]\) and \(R_i = \mathrm{right.dims}[i]\). The metadata part of kron(left, right) is allowed only when every paired dim product

\[ L_i \otimes R_i \]

is defined. For Hilbert-space-like dims, write \(\operatorname{types}(D)\) for the concrete irrep types present in dim \(D\). Then the paired product requires

\[ \operatorname{types}(L_i) \cap \operatorname{types}(R_i) = \varnothing. \]

For example, a dim with irrep types \((\mathrm{int}, \mathrm{str})\) can be paired with one whose irrep types are \((\mathrm{float},)\), but not with one whose irrep types are \((\mathrm{int},)\), because the shared \(\mathrm{int}\) type would give multiplicity greater than one in the tensor-product basis.

Parameters:

Name Type Description Default
left Tensor

Left operand.

required
right Tensor

Right operand.

required

Returns:

Type Description
Tensor

Tensor with Kronecker-product data and axis-wise tensor-product dims.

Raises:

Type Description
ValueError

If left and right do not have the same rank, or if a dim-level Kronecker product rejects overlapping irrep types.

TypeError

If any axis pair is not compatible with Kronecker-product semantics (except neutral broadcast axes).

Source code in src/qten/linalg/tensors.py
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
2523
2524
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
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
@auto_promote
def kron(left: Tensor, right: Tensor) -> Tensor:
    r"""
    Compute the StateSpace-aware Kronecker product between two tensors.

    Semantics
    ---------
    This function applies `torch.kron(left.data, right.data)` and propagates
    symbolic metadata axis-by-axis:

    - The operands must have the same rank.
    - For each axis `i`, output dim `i` is `left.dims[i] @ right.dims[i]`.
    - Axis pairs are matched by position, not by name or irrep content. The
      `i`-th dim of `left` is combined only with the `i`-th dim of `right`.
    - Non-broadcast axes must implement
      [`HasKroneckerProduct`][qten.abstracts.HasKroneckerProduct].
    - For Hilbert-space-like dims, the basis-level tensor product requires
      disjoint concrete irrep types between the paired dims. For example, a
      dim whose basis states contain irrep types `(int, str)` can be combined
      with one containing `(float,)`, but combining it with one containing
      `(int,)` is rejected because `int` appears on both sides.
    - [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace] is treated
      as a neutral singleton axis, so `BroadcastSpace @ X` and
      `X @ BroadcastSpace` both map to `X`.

    Allowed dim products
    --------------------
    Let \(L_i = \mathrm{left.dims}[i]\) and
    \(R_i = \mathrm{right.dims}[i]\). The metadata part of
    [`kron(left, right)`][qten.linalg.tensors.kron] is allowed only when every
    paired dim product

    \[
        L_i \otimes R_i
    \]

    is defined. For Hilbert-space-like dims, write
    \(\operatorname{types}(D)\) for the concrete irrep types present in dim
    \(D\). Then the paired product requires

    \[
        \operatorname{types}(L_i) \cap \operatorname{types}(R_i) = \varnothing.
    \]

    For example, a dim with irrep types \((\mathrm{int}, \mathrm{str})\) can
    be paired with one whose irrep types are \((\mathrm{float},)\), but not
    with one whose irrep types are \((\mathrm{int},)\), because the shared
    \(\mathrm{int}\) type would give multiplicity greater than one in the
    tensor-product basis.

    Parameters
    ----------
    left : Tensor
        Left operand.
    right : Tensor
        Right operand.

    Returns
    -------
    Tensor
        Tensor with Kronecker-product data and axis-wise tensor-product dims.

    Raises
    ------
    ValueError
        If `left` and `right` do not have the same rank, or if a dim-level
        Kronecker product rejects overlapping irrep types.
    TypeError
        If any axis pair is not compatible with Kronecker-product semantics
        (except neutral broadcast axes).
    """
    if left.rank() != right.rank():
        raise ValueError(
            "kron expects tensors with the same rank: "
            f"got {left.rank()} and {right.rank()}."
        )

    new_dims = tuple(
        _kron_dim(left_dim, right_dim)
        for left_dim, right_dim in zip(left.dims, right.dims)
    )
    return Tensor(data=torch.kron(left.data, right.data), dims=new_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
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
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
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
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
2637
2638
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
@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 | Tensor

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
Union[TensorType, Tensor]

Tensor with the requested axes reduced and removed from dims. For subclasses marked with strict_dims, this may return a plain Tensor.

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
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
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
def mean(
    tensor: TensorType, dim: Optional[Union[int, Tuple[int, ...]]] = None
) -> Union[TensorType, Tensor]:
    """
    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
    -------
    Union[TensorType, Tensor]
        Tensor with the requested axes reduced and removed from `dims`. For
        subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may return a
        plain [`Tensor`][qten.linalg.tensors.Tensor].

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

    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 cast(
        TensorType,
        _wrap_tensor_result(
            tensor,
            data=reduced,
            dims=new_dims,
            preserve_strict=False,
        ),
    )

norm

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

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
Union[TensorType, Tensor]

Tensor containing the requested norm values with reduced axes removed from dims. For subclasses marked with strict_dims, this may return a plain Tensor.

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
3982
3983
3984
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
4040
4041
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
def norm(
    tensor: TensorType,
    ord: Optional[Union[int, float, str]] = None,
    dim: Optional[Union[int, Tuple[int, int]]] = None,
) -> Union[TensorType, Tensor]:
    """
    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
    -------
    Union[TensorType, Tensor]
        Tensor containing the requested norm values with reduced axes removed
        from `dims`. For subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this may return a
        plain [`Tensor`][qten.linalg.tensors.Tensor].

    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 cast(
            TensorType,
            _wrap_tensor_result(
                tensor,
                data=reduced,
                dims=(),
                preserve_strict=False,
            ),
        )

    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 cast(
        TensorType,
        _wrap_tensor_result(
            tensor,
            data=reduced,
            dims=new_dims,
            preserve_strict=False,
        ),
    )

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
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
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
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
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
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
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
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
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
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
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
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
Tensor

Tensor with permuted data and correspondingly permuted dims.

The public signature is Tensor because permute is exposed through multimethod dispatch on the base Tensor type. At runtime, when no strict-dims downgrade is required and the concrete subtype remains valid, the implementation still preserves the input wrapper type via replace(tensor, ...).

Raises:

Type Description
ValueError

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

Source code in src/qten/linalg/tensors.py
3309
3310
3311
3312
3313
3314
3315
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
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
@multimethod
def permute(tensor: Tensor, *order: Union[int, Sequence[int]]) -> Tensor:
    """
    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
    -------
    Tensor
        Tensor with permuted data and correspondingly permuted `dims`.

        The public signature is `Tensor` because `permute` is exposed through
        multimethod dispatch on the base `Tensor` type. At runtime, when no
        strict-dims downgrade is required and the concrete subtype remains
        valid, the implementation still preserves the input wrapper type via
        `replace(tensor, ...)`.

    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 | Tensor

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
Union[TensorType, Tensor]

A new tensor where each requested group is replaced by one product dimension and all non-grouped dimensions are retained. For subclasses marked with strict_dims, this may return a plain Tensor.

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
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
def product_dims(
    tensor: TensorType, *indices_group: Tuple[int, ...]
) -> Union[TensorType, Tensor]:
    """
    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
    -------
    Union[TensorType, Tensor]
        A new tensor where each requested group is replaced by one product
        dimension and all non-grouped dimensions are retained. For subclasses
        marked with [`strict_dims`][qten.linalg.tensors.strict_dims], this may
        return a plain [`Tensor`][qten.linalg.tensors.Tensor].

    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 _kron_dim(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 cast(
        TensorType,
        _wrap_tensor_result(
            tensor,
            data=permuted.data.reshape(tuple(new_shape)),
            dims=tuple(new_dims),
            preserve_strict=False,
        ),
    )

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
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
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
3413
3414
3415
3416
3417
3418
3419
3420
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
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
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
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
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.
    """
    dim = _normalize_dim_index(len(tensor.dims), dim)

    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 | Tensor

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
Union[TensorType, Tensor]

Tensor with the requested broadcast axis removed. For subclasses marked with strict_dims, this may return a plain Tensor.

Source code in src/qten/linalg/tensors.py
3486
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
def squeeze(tensor: TensorType, dim: int) -> Union[TensorType, Tensor]:
    """
    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
    -------
    Union[TensorType, Tensor]
        Tensor with the requested broadcast axis removed. For subclasses
        marked with [`strict_dims`][qten.linalg.tensors.strict_dims], this may
        return a plain [`Tensor`][qten.linalg.tensors.Tensor].
    """
    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 cast(
        TensorType,
        _wrap_tensor_result(
            tensor,
            data=new_data,
            dims=new_dims,
            preserve_strict=False,
        ),
    )

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
Tensor

Tensor with the selected axes exchanged.

The public signature is Tensor because transpose is exposed through multimethod dispatch on the base Tensor type. At runtime, when no strict-dims downgrade is required and the concrete subtype remains valid, the implementation still preserves the input wrapper type via replace(tensor, ...) through permute.

Source code in src/qten/linalg/tensors.py
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
@multimethod
def transpose(tensor: Tensor, dim0: int, dim1: int) -> Tensor:
    """
    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
    -------
    Tensor
        Tensor with the selected axes exchanged.

        The public signature is `Tensor` because `transpose` is exposed through
        multimethod dispatch on the base `Tensor` type. At runtime, when no
        strict-dims downgrade is required and the concrete subtype remains
        valid, the implementation still preserves the input wrapper type via
        `replace(tensor, ...)` through
        [`permute`][qten.linalg.tensors.permute].
    """
    order = list(range(tensor.rank()))
    order[dim0], order[dim1] = order[dim1], order[dim0]
    return permute(tensor, tuple(order))

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
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
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
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)

update_dim

update_dim(
    tensor: TensorType,
    dim: int,
    func: Callable[[StateSpace], StateSpace],
) -> TensorType

Update one symbolic dimension by applying a callback to the current metadata.

This is a metadata-only operation. The callback is applied to tensor.dims[dim], and the returned StateSpace is then validated through replace_dim.

Parameters:

Name Type Description Default
tensor Tensor

The tensor to modify.

required
dim int

The index of the dimension to update.

required
func Callable[[StateSpace], StateSpace]

Callback that maps the current StateSpace to a replacement.

required

Returns:

Type Description
TensorType

Tensor with unchanged data and the requested updated dimension.

Raises:

Type Description
IndexError

If dim is out of range for the tensor rank.

ValueError

If the callback returns a size-incompatible StateSpace.

Source code in src/qten/linalg/tensors.py
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
def update_dim(
    tensor: TensorType,
    dim: int,
    func: Callable[[StateSpace], StateSpace],
) -> TensorType:
    """
    Update one symbolic dimension by applying a callback to the current metadata.

    This is a metadata-only operation. The callback is applied to
    `tensor.dims[dim]`, and the returned StateSpace is then validated through
    [`replace_dim`][qten.linalg.tensors.replace_dim].

    Parameters
    ----------
    tensor : Tensor
        The tensor to modify.
    dim : int
        The index of the dimension to update.
    func : Callable[[StateSpace], StateSpace]
        Callback that maps the current StateSpace to a replacement.

    Returns
    -------
    TensorType
        Tensor with unchanged data and the requested updated dimension.

    Raises
    ------
    IndexError
        If `dim` is out of range for the tensor rank.
    ValueError
        If the callback returns a size-incompatible StateSpace.
    """
    dim = _normalize_dim_index(len(tensor.dims), dim)
    return replace_dim(tensor, dim, func(tensor.dims[dim]))

unsqueeze

unsqueeze(
    tensor: TensorType, dim: int
) -> TensorType | Tensor

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
Union[TensorType, Tensor]

Tensor with one extra singleton axis and a matching inserted BroadcastSpace dim. For subclasses marked with strict_dims, this returns a plain Tensor.

Source code in src/qten/linalg/tensors.py
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
def unsqueeze(tensor: TensorType, dim: int) -> Union[TensorType, Tensor]:
    """
    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
    -------
    Union[TensorType, Tensor]
        Tensor with one extra singleton axis and a matching inserted
        [`BroadcastSpace`][qten.symbolics.state_space.BroadcastSpace] dim. For
        subclasses marked with
        [`strict_dims`][qten.linalg.tensors.strict_dims], this returns a plain
        [`Tensor`][qten.linalg.tensors.Tensor].
    """
    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 cast(
        TensorType,
        _wrap_tensor_result(
            tensor,
            data=new_data,
            dims=new_dims,
            preserve_strict=False,
        ),
    )

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
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
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
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
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}")