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
TensorStateSpace-aware tensor wrapper overtorch.Tensor.MomentumBlockTensorMomentum-pair-resolved block-matrix tensor for band-space transforms.DeviceLogical device descriptor used by QTen objects.set_precisionConfigure numeric precision defaults for the library.
Tensor construction and manipulation
Tensor algebra and queries
Linear-algebra helpers
Devices and I/O
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"or32: usetorch.float32,torch.complex64,np.float32, andnp.complex64."64"or64: usetorch.float64,torch.complex128,np.float64, andnp.complex128.- A supported real or complex
torch.dtypeselects its matching dtype family. - A supported real or complex
np.dtypeor 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
|
Returns:
| Type | Description |
|---|---|
None
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 | |
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 |
__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 |
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 | |
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 | |
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 | |
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 | |
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 | |
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
|
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 | |
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 |
required |
backend
|
str
|
Backend name that selects the implementation. The |
'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 | |
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 |
'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 | |
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 | |
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 |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new tensor of the same wrapper type whose data has 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 | |
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.dimstoself.dimsusingalign_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 |
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 | |
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.dimstoself.dimsusingalign_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 |
1e-05
|
atol
|
float
|
Absolute tolerance used by |
1e-08
|
equal_nan
|
bool
|
Whether |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
True if tensors are close after alignment; otherwise |
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 | |
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.
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 |
required |
rtol
|
float
|
Relative tolerance passed to |
1e-05
|
atol
|
float
|
Absolute tolerance passed to |
1e-08
|
equal_nan
|
bool
|
Whether |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
h
h(dim0: int, dim1: int) -> Self
Hermitian transpose (conjugate transpose) of the specified dimensions.
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 | |
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 | |
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 |
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 | |
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
|
keepdim
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
Union[Self, Tensor]
|
Boolean tensor after reduction. For subclasses marked with
|
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 | |
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 betweeninputandother.condition.where(): returns index tensors ofTrueentries.condition.where(index_type=...): returns the requested index representation forTrueentries.
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 |
None
|
other
|
Optional[Tensor]
|
Tensor selected where |
None
|
index_type
|
Type[Any]
|
Only used for the condition-only form Supported values are
|
None
|
Returns:
| Type | Description |
|---|---|
Union[Tensor, Tuple[Tensor, ...], Tuple[Tuple[int, ...], ...], StateSpace]
|
Return value depends on call form. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
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 | |
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
|
index_type
|
Type[Any]
|
Requested index representation. Supported values are
|
None
|
Returns:
| Type | Description |
|---|---|
Union[Tuple[Tensor, ...], Tuple[Tuple[int, ...], ...], StateSpace]
|
Index representation selected by |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
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 | |
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
|
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 | |
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
|
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 | |
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
|
required |
source
|
Tensor
|
Tensor of update values. It must have the same rank as |
required |
alpha
|
Union[int, float, complex]
|
Scalar multiplier applied to |
1
|
Alignment rules
indexmust be a rank-1 integer tensor.sourcemust have the same rank asself.- On non-indexed axes,
sourceis aligned toself. - On the indexed axis,
sourceis aligned toindex.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 |
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 | |
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 |
required |
alpha
|
Union[int, float, complex]
|
Scalar multiplier applied to |
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 | |
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 | |
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
|
Returns:
| Type | Description |
|---|---|
Union[Self, Tensor]
|
A new tensor with the specified dimensions reduced. For subclasses
marked with |
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 | |
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:
dimis anint: vector norm. Supportedordvalues includeNone,0, any finiteintorfloat,float("inf"), and-float("inf").dimis a 2-tuple: matrix norm. Supportedordvalues includeNone,"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 onord. See the linkedtorch.linalg.normreference for the exact dispatch rules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ord
|
Optional[Union[int, float, str]]
|
Norm order forwarded to Common choices are |
None
|
dim
|
Optional[Union[int, Tuple[int, int]]]
|
Reduction axis or axes. Use an |
None
|
Returns:
| Type | Description |
|---|---|
Union[Self, Tensor]
|
A new tensor with the specified dimensions reduced. For subclasses
marked with |
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 | |
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 |
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 | |
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 |
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 | |
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 | |
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 | |
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 | |
attach
attach() -> Self
Enable gradient tracking for the tensor data and return the attached Tensor instance.
Behavior
- If
requires_gradis alreadyTrue, this returnsselfunchanged. - Otherwise, this detaches the underlying data from any existing autograd graph,
clones it to ensure a fresh leaf tensor, and sets
requires_gradtoTrue. - 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 | |
detach
detach() -> Self
Disable gradient tracking for the tensor data and create a new Tensor instance.
Behavior
- Always returns a new
Tensorwhose 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 | |
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 | |
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 | |
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 | |
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 |
required |
Returns:
| Type | Description |
|---|---|
Union[Self, Tensor]
|
A new tensor with the specified dimension factorized. For
subclasses marked with
|
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 | |
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
|
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 | |
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 | |
__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 | |
__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 | |
__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 | |
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
datastores the underlying numeric values as atorch.Tensor.dimsstores oneStateSpaceper axis.tensor.data.shapemust equaltuple(dim.dim for dim in tensor.dims).- Axes are aligned by
StateSpacecompatibility 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 |
dims |
Tuple[StateSpace, ...]
|
Symbolic dimension metadata, with one
|
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
BroadcastSpaceaxes. - 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 + candc + atreataas a matrix or batch of matrices over its last two axes and compute \(A + cI\).a - ccomputes \(A - cI\).c - acomputes \(cI - A\).- These operations therefore require metadata that can construct
eyeon 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
-anegates the tensor element-wise while preserving dims.a * candc * aperform element-wise scalar multiplication.a / cperforms 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
Tensoron the merged dims.
Scalar comparisons promote the scalar through Tensor.scalar(...), so:
a < c,a <= c,a > c,a >= cfollow the same tensor-tensor comparison pipeline,c < a,c <= a,c > a,c >= ause 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
permute(*order): reorder axes.transpose(dim0, dim1): swap two axes.h(dim0, dim1): conjugate transpose across two axes.unsqueeze(dim): insert a singletonBroadcastSpaceaxis.squeeze(dim): remove aBroadcastSpaceaxis if present.replace_dim(dim, new_dim): replace metadata for one axis with size validation.update_dim(dim, func): transform one axis metadata with a callback before validation.factorize_dim(dim, rule): split one axis into multiple factor spaces.product_dims(*groups): combine groups of axes into tensor-product axes.promote_rank(tensor, target_rank): prepend broadcast axes.
Reductions and element queries
all(dim=None, keepdim=False): logical AND reduction.mean(dim=None): arithmetic mean reduction.argmax(dim),argmin(dim): index reductions.item(): extract the Python scalar from a rank-0 tensor.equal(other): exact equality after metadata alignment, returning Pythonbool.allclose(other, ...): approximate equality after metadata alignment, returning Pythonbool.
Boolean-mask helpers
where(input, other): use this tensor as a bool mask and select between two tensors.where(): return index tensors forTrueentries.nonzero(as_tuple=True): return index tensors for nonzero /Trueentries.
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 withrequires_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 |
__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 | |
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 | |
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 | |
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
|
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 | |
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 |
required |
backend
|
str
|
Backend name that selects the implementation. The |
'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 | |
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 |
'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 | |
__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 | |
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 | |
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 |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new tensor of the same wrapper type whose data has 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 | |
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.dimstoself.dimsusingalign_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 |
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 | |
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.dimstoself.dimsusingalign_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 |
1e-05
|
atol
|
float
|
Absolute tolerance used by |
1e-08
|
equal_nan
|
bool
|
Whether |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
True if tensors are close after alignment; otherwise |
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 | |
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.
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 |
required |
rtol
|
float
|
Relative tolerance passed to |
1e-05
|
atol
|
float
|
Absolute tolerance passed to |
1e-08
|
equal_nan
|
bool
|
Whether |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
h
h(dim0: int, dim1: int) -> Self
Hermitian transpose (conjugate transpose) of the specified dimensions.
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 | |
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 | |
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 |
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 | |
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
|
keepdim
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
Union[Self, Tensor]
|
Boolean tensor after reduction. For subclasses marked with
|
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 | |
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 betweeninputandother.condition.where(): returns index tensors ofTrueentries.condition.where(index_type=...): returns the requested index representation forTrueentries.
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 |
None
|
other
|
Optional[Tensor]
|
Tensor selected where |
None
|
index_type
|
Type[Any]
|
Only used for the condition-only form Supported values are
|
None
|
Returns:
| Type | Description |
|---|---|
Union[Tensor, Tuple[Tensor, ...], Tuple[Tuple[int, ...], ...], StateSpace]
|
Return value depends on call form. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
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 | |
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
|
index_type
|
Type[Any]
|
Requested index representation. Supported values are
|
None
|
Returns:
| Type | Description |
|---|---|
Union[Tuple[Tensor, ...], Tuple[Tuple[int, ...], ...], StateSpace]
|
Index representation selected by |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
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 | |
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
|
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 | |
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
|
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 | |
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
|
required |
source
|
Tensor
|
Tensor of update values. It must have the same rank as |
required |
alpha
|
Union[int, float, complex]
|
Scalar multiplier applied to |
1
|
Alignment rules
indexmust be a rank-1 integer tensor.sourcemust have the same rank asself.- On non-indexed axes,
sourceis aligned toself. - On the indexed axis,
sourceis aligned toindex.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 |
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 | |
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 |
required |
alpha
|
Union[int, float, complex]
|
Scalar multiplier applied to |
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 | |
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 | |
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
|
Returns:
| Type | Description |
|---|---|
Union[Self, Tensor]
|
A new tensor with the specified dimensions reduced. For subclasses
marked with |
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 | |
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:
dimis anint: vector norm. Supportedordvalues includeNone,0, any finiteintorfloat,float("inf"), and-float("inf").dimis a 2-tuple: matrix norm. Supportedordvalues includeNone,"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 onord. See the linkedtorch.linalg.normreference for the exact dispatch rules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ord
|
Optional[Union[int, float, str]]
|
Norm order forwarded to Common choices are |
None
|
dim
|
Optional[Union[int, Tuple[int, int]]]
|
Reduction axis or axes. Use an |
None
|
Returns:
| Type | Description |
|---|---|
Union[Self, Tensor]
|
A new tensor with the specified dimensions reduced. For subclasses
marked with |
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 | |
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 |
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 | |
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 |
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 | |
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 | |
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 | |
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 | |
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 | |
attach
attach() -> Self
Enable gradient tracking for the tensor data and return the attached Tensor instance.
Behavior
- If
requires_gradis alreadyTrue, this returnsselfunchanged. - Otherwise, this detaches the underlying data from any existing autograd graph,
clones it to ensure a fresh leaf tensor, and sets
requires_gradtoTrue. - 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 | |
detach
detach() -> Self
Disable gradient tracking for the tensor data and create a new Tensor instance.
Behavior
- Always returns a new
Tensorwhose 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 | |
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 | |
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 | |
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 | |
__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, |
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-Noneentries).- 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 currentStateSpace, - non-full slice uses
self.dims[axis][slice], exceptBroadcastSpaceaxes where metadata follows sliced size: size1keepsBroadcastSpace, size0becomesIndexSpace.linear(0). None: inserts a new output axis withBroadcastSpaceand does not consume a source axis.StateSpace/Convertible:- indexing a
BroadcastSpaceaxis with any non-BroadcastSpaceStateSpaceis 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. Tensorindex:booldtype 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
Tensorindices withStateSpace/Convertibleindices is rejected (ValueError). - If at least one
Tensorindex 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
StateSpacetuple 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 |
ValueError
|
If tensor indices are mixed with |
NotImplementedError
|
If boolean tensor indices are used in a mode that QTen does not
support through |
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 | |
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 |
required |
Returns:
| Type | Description |
|---|---|
Union[Self, Tensor]
|
A new tensor with the specified dimension factorized. For
subclasses marked with
|
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 | |
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
|
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 | |
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 |
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 | |
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 | |
__repr__
__repr__() -> str
Return a compact developer-facing representation of the tensor.
The representation summarizes:
- the execution device class (
CPUorGPU), - whether gradients are tracked,
- and one
TypeName:sizeentry per axis indims.
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 | |
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 oftarget_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 |
Raises:
| Type | Description |
|---|---|
IndexError
|
If |
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 | |
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 |
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 | |
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
|
keepdim
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
Union[TensorType, Tensor]
|
Boolean tensor with reduced dimensions. For subclasses marked with
|
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 | |
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 |
required |
rtol
|
float
|
Relative tolerance used by |
1e-05
|
atol
|
float
|
Absolute tolerance used by |
1e-08
|
equal_nan
|
bool
|
Whether |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
True if values are close after successful alignment; |
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 | |
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 | |
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 | |
__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 |
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 | |
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 |
Raises:
| Type | Description |
|---|---|
IndexError
|
If |
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 | |
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 |
Raises:
| Type | Description |
|---|---|
IndexError
|
If |
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 | |
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 | |
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 |
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 | |
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 |
IndexError
|
If |
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 | |
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 | |
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 |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if values are exactly equal after successful alignment; |
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 | |
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....ijmeans "match the last two labeled axes and let...absorb the preceding axes";i...jmeans "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 internaltorch.einsumequation. 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 (viaunsqueeze(0)) and uses the leading-ellipsis form in the normalizedtorch.einsumequation. For example,"i...j,ij->i...j"is internally reconciled by treating theijoperand 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 sharedjaxis."abc,dbe->acde"means multiply over the sharedbaxis and keep the surviving axes in the explicit output order(a, c, d, e)."...ij,ij->...ij"means "broadcast theijoperand across the leading unnamed axes of the other operand, then keep those axes in the output"."i...j,ij->i...j"means "broadcast theijoperand across the unnamed middle axes betweeniandj".
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
|
required |
*operands
|
Tensor
|
Input tensors whose ranks must match the equation terms after any
|
()
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor whose data is computed by |
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 | |
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
|
required |
Returns:
| Type | Description |
|---|---|
TensorType
|
Tensor whose broadcast axes have been expanded to the corresponding
concrete sizes in |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 | |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 | |
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 intofactorized.
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
|
Raises:
| Type | Description |
|---|---|
IndexError
|
If |
ValueError
|
If the product of |
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 | |
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
|
required |
dims
|
Tuple[StateSpace, ...]
|
Output tensor dimensions. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor with |
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 |
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 | |
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 dimiisleft.dims[i] @ right.dims[i]. - Axis pairs are matched by position, not by name or irrep content. The
i-th dim ofleftis combined only with thei-th dim ofright. - 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 becauseintappears on both sides. BroadcastSpaceis treated as a neutral singleton axis, soBroadcastSpace @ XandX @ BroadcastSpaceboth map toX.
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
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
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 |
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 | |
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 |
required |
factors
|
Optional[Dict[Tuple[Any, Any], int | float | complex]]
|
Optional per-entry factors. Keys are |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Rank-2 tensor with dimensions |
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 | |
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 |
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 | |
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
|
Returns:
| Type | Description |
|---|---|
Union[TensorType, Tensor]
|
Tensor with the requested axes reduced and removed from |
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 | |
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:
dimis anint: compute a vector norm along that axis.dimis a 2-tuple: compute a matrix norm over those two axes.dim is None: follow PyTorch'storch.linalg.normrules. In particular,ord=Noneflattens the tensor and computes a vector 2-norm, whileord != Noneexpects 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 Common examples:
- |
None
|
dim
|
Optional[Union[int, Tuple[int, int]]]
|
Reduction axis or axes.
|
None
|
Returns:
| Type | Description |
|---|---|
Union[TensorType, Tensor]
|
Tensor containing the requested norm values with reduced axes removed
from |
Raises:
| Type | Description |
|---|---|
IndexError
|
If any requested reduction axis is out of range for the tensor rank. |
ValueError
|
If |
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 | |
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
|
index_type
|
Type[Any]
|
Requested index representation. Supported values are |
Tensor
|
Returns:
| Type | Description |
|---|---|
Union[Tuple[Tensor, ...], Tuple[Tuple[int, ...], ...], StateSpace]
|
Index representation selected by |
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 |
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 | |
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
|
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
A new tensor with one extra trailing dimension for class channels. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If any class index is outside the range |
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 | |
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 | |
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.
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 |
required |
rtol
|
float
|
Relative tolerance passed to |
1e-05
|
atol
|
float
|
Absolute tolerance passed to |
1e-08
|
equal_nan
|
bool
|
Whether |
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 | |
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 |
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 | |
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 The public signature is |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the permutation length does not match |
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 | |
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 |
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 | |
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 |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
|
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 |
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 | |
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 | |
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 | |
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 |
ValueError
|
If |
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 | |
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 |
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 | |
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 |
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 | |
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_allandexpand_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)
BroadcastSpace+ concreteStateSpace-> concreteStateSpaceBroadcastSpace+BroadcastSpace->BroadcastSpace- concrete + concrete:
- if
same_rays(...)isTrue, 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:
| Name | Type | Description | Default |
|---|---|---|---|
dims
|
Tuple[StateSpace, ...]
|
One or more dimension tuples to merge. |
()
|
allow_merge
|
bool
|
If |
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 | |
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 |
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 | |
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
|
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 | |
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 |
()
|
**kwargs
|
Any
|
Keyword arguments forwarded to the overloaded |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
Result produced by the matching overloaded |
Raises:
| Type | Description |
|---|---|
TypeError
|
If multimethod dispatch fails because the matched implementation raised
|
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 | |
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 |
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 | |
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 |
`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 | |
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 |
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 | |
__str__
__str__() -> str
Format the device using QTen's logical device syntax.
Returns:
| Type | Description |
|---|---|
str
|
"cpu", |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 | |