simpler-torch 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- simpler_torch/__init__.py +18 -0
- simpler_torch/axis.py +180 -0
- simpler_torch/ops.py +166 -0
- simpler_torch/py.typed +0 -0
- simpler_torch/tensor.py +521 -0
- simpler_torch-0.1.0.dist-info/METADATA +105 -0
- simpler_torch-0.1.0.dist-info/RECORD +9 -0
- simpler_torch-0.1.0.dist-info/WHEEL +4 -0
- simpler_torch-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from .axis import Axes, Axis, AxisIndex, AxisPair, skip
|
|
2
|
+
from .ops import cat, contract, stack, unbind, where
|
|
3
|
+
from .tensor import NamedTensor, bind
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"Axis",
|
|
7
|
+
"Axes",
|
|
8
|
+
"AxisIndex",
|
|
9
|
+
"AxisPair",
|
|
10
|
+
"skip",
|
|
11
|
+
"NamedTensor",
|
|
12
|
+
"bind",
|
|
13
|
+
"contract",
|
|
14
|
+
"cat",
|
|
15
|
+
"stack",
|
|
16
|
+
"unbind",
|
|
17
|
+
"where",
|
|
18
|
+
]
|
simpler_torch/axis.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Iterator, Sequence
|
|
4
|
+
from typing import TYPE_CHECKING, Final, NoReturn, overload
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
|
|
8
|
+
_AXIS_POOL: dict[str, Axis] = {}
|
|
9
|
+
_PAIR_POOL: dict[tuple[str | None, ...], AxisPair] = {}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@torch.compiler.assume_constant_result
|
|
13
|
+
def _intern_axis(name: str) -> Axis:
|
|
14
|
+
axis = _AXIS_POOL.get(name)
|
|
15
|
+
if axis is None:
|
|
16
|
+
new = object.__new__(Axis)
|
|
17
|
+
object.__setattr__(new, "name", name)
|
|
18
|
+
axis = _AXIS_POOL.setdefault(name, new)
|
|
19
|
+
return axis
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@torch.compiler.assume_constant_result
|
|
23
|
+
def _intern_pair(names: tuple[str | None, ...]) -> AxisPair:
|
|
24
|
+
pair = _PAIR_POOL.get(names)
|
|
25
|
+
if pair is None:
|
|
26
|
+
new = object.__new__(AxisPair)
|
|
27
|
+
object.__setattr__(new, "items", tuple(_intern_axis(n) if n is not None else skip for n in names))
|
|
28
|
+
object.__setattr__(new, "_names", names)
|
|
29
|
+
pair = _PAIR_POOL.setdefault(names, new)
|
|
30
|
+
return pair
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _unpickle_skip() -> _Skip:
|
|
34
|
+
return skip
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _Skip:
|
|
38
|
+
__slots__ = ()
|
|
39
|
+
|
|
40
|
+
def __and__(self, other: Axis | _Skip | AxisPair) -> AxisPair:
|
|
41
|
+
if isinstance(other, AxisPair):
|
|
42
|
+
return _intern_pair((None, *other._names))
|
|
43
|
+
if isinstance(other, Axis):
|
|
44
|
+
return _intern_pair((None, other.name))
|
|
45
|
+
if isinstance(other, _Skip):
|
|
46
|
+
return _intern_pair((None, None))
|
|
47
|
+
return NotImplemented
|
|
48
|
+
|
|
49
|
+
def __reduce__(self) -> tuple[Callable[[], _Skip], tuple[()]]:
|
|
50
|
+
return (_unpickle_skip, ())
|
|
51
|
+
|
|
52
|
+
def __repr__(self) -> str:
|
|
53
|
+
return "skip"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
skip: Final[_Skip] = _Skip()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Axis:
|
|
60
|
+
__slots__ = ("name",)
|
|
61
|
+
name: str
|
|
62
|
+
|
|
63
|
+
def __new__(cls, name: str) -> Axis:
|
|
64
|
+
if not name.isidentifier():
|
|
65
|
+
raise ValueError(f"axis name must be a valid Python identifier, got {name!r}")
|
|
66
|
+
return _intern_axis(name)
|
|
67
|
+
|
|
68
|
+
def __setattr__(self, attr: str, value: object) -> NoReturn:
|
|
69
|
+
raise AttributeError(f"Axis is immutable; cannot set attribute {attr!r}")
|
|
70
|
+
|
|
71
|
+
def __delattr__(self, attr: str) -> NoReturn:
|
|
72
|
+
raise AttributeError(f"Axis is immutable; cannot delete attribute {attr!r}")
|
|
73
|
+
|
|
74
|
+
def __reduce__(self) -> tuple[Callable[[str], Axis], tuple[str]]:
|
|
75
|
+
return (_intern_axis, (self.name,))
|
|
76
|
+
|
|
77
|
+
def __getitem__(self, index: int | slice) -> AxisIndex:
|
|
78
|
+
return AxisIndex(self, index)
|
|
79
|
+
|
|
80
|
+
def __and__(self, other: Axis | _Skip | AxisPair) -> AxisPair:
|
|
81
|
+
if isinstance(other, AxisPair):
|
|
82
|
+
return _intern_pair((self.name, *other._names))
|
|
83
|
+
if isinstance(other, Axis):
|
|
84
|
+
return _intern_pair((self.name, other.name))
|
|
85
|
+
if isinstance(other, _Skip):
|
|
86
|
+
return _intern_pair((self.name, None))
|
|
87
|
+
return NotImplemented
|
|
88
|
+
|
|
89
|
+
def __repr__(self) -> str:
|
|
90
|
+
return self.name
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class AxisPair:
|
|
94
|
+
__slots__ = ("items", "_names")
|
|
95
|
+
items: tuple[Axis | _Skip, ...]
|
|
96
|
+
_names: tuple[str | None, ...]
|
|
97
|
+
|
|
98
|
+
def __new__(cls, *items: Axis | _Skip) -> AxisPair:
|
|
99
|
+
return _intern_pair(tuple(None if a is skip else a.name for a in items))
|
|
100
|
+
|
|
101
|
+
def __setattr__(self, attr: str, value: object) -> NoReturn:
|
|
102
|
+
raise AttributeError(f"AxisPair is immutable; cannot set attribute {attr!r}")
|
|
103
|
+
|
|
104
|
+
def __delattr__(self, attr: str) -> NoReturn:
|
|
105
|
+
raise AttributeError(f"AxisPair is immutable; cannot delete attribute {attr!r}")
|
|
106
|
+
|
|
107
|
+
def __reduce__(self) -> tuple[Callable[[tuple[str | None, ...]], AxisPair], tuple[tuple[str | None, ...]]]:
|
|
108
|
+
return (_intern_pair, (self._names,))
|
|
109
|
+
|
|
110
|
+
def __len__(self) -> int:
|
|
111
|
+
return len(self.items)
|
|
112
|
+
|
|
113
|
+
def __and__(self, other: Axis | _Skip | AxisPair) -> AxisPair:
|
|
114
|
+
if isinstance(other, AxisPair):
|
|
115
|
+
return _intern_pair((*self._names, *other._names))
|
|
116
|
+
if isinstance(other, Axis):
|
|
117
|
+
return _intern_pair((*self._names, other.name))
|
|
118
|
+
if isinstance(other, _Skip):
|
|
119
|
+
return _intern_pair((*self._names, None))
|
|
120
|
+
return NotImplemented
|
|
121
|
+
|
|
122
|
+
def __repr__(self) -> str:
|
|
123
|
+
return " & ".join(repr(item) for item in self.items)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class AxisIndex:
|
|
127
|
+
axis: Axis
|
|
128
|
+
index: int | slice
|
|
129
|
+
|
|
130
|
+
def __init__(self, axis: Axis, index: int | slice) -> None:
|
|
131
|
+
self.axis = axis
|
|
132
|
+
self.index = index
|
|
133
|
+
|
|
134
|
+
def __repr__(self) -> str:
|
|
135
|
+
return f"AxisIndex(axis={self.axis!r}, index={self.index!r})"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class Axes(Sequence[Axis]):
|
|
139
|
+
_axes: tuple[Axis, ...]
|
|
140
|
+
|
|
141
|
+
def __init__(self, *names: str) -> None:
|
|
142
|
+
parsed = [part for group in names for part in group.split()]
|
|
143
|
+
if not parsed:
|
|
144
|
+
raise ValueError("Axes requires at least one axis name")
|
|
145
|
+
if len(set(parsed)) != len(parsed):
|
|
146
|
+
raise ValueError(f"duplicate axis names in Axes({', '.join(repr(n) for n in names)})")
|
|
147
|
+
for name in parsed:
|
|
148
|
+
if name in _AXES_RESERVED:
|
|
149
|
+
raise ValueError(f"axis name {name!r} conflicts with Axes attribute")
|
|
150
|
+
axes = tuple(Axis(name) for name in parsed)
|
|
151
|
+
self._axes = axes
|
|
152
|
+
for name, axis in zip(parsed, axes):
|
|
153
|
+
setattr(self, name, axis)
|
|
154
|
+
|
|
155
|
+
if TYPE_CHECKING:
|
|
156
|
+
def __getattr__(self, name: str) -> Axis: ...
|
|
157
|
+
|
|
158
|
+
def __reduce__(self) -> tuple[type[Axes], tuple[str, ...]]:
|
|
159
|
+
return (Axes, tuple(a.name for a in self._axes))
|
|
160
|
+
|
|
161
|
+
@overload
|
|
162
|
+
def __getitem__(self, index: int) -> Axis: ...
|
|
163
|
+
@overload
|
|
164
|
+
def __getitem__(self, index: slice) -> tuple[Axis, ...]: ...
|
|
165
|
+
def __getitem__(self, index: int | slice) -> Axis | tuple[Axis, ...]:
|
|
166
|
+
return self._axes[index]
|
|
167
|
+
|
|
168
|
+
def __len__(self) -> int:
|
|
169
|
+
return len(self._axes)
|
|
170
|
+
|
|
171
|
+
def __iter__(self) -> Iterator[Axis]:
|
|
172
|
+
return iter(self._axes)
|
|
173
|
+
|
|
174
|
+
def __repr__(self) -> str:
|
|
175
|
+
return f"Axes({' '.join(a.name for a in self._axes)!r})"
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
_AXES_RESERVED: Final[frozenset[str]] = frozenset(
|
|
179
|
+
{"_axes", *(name for cls in Axes.__mro__ for name in cls.__dict__)}
|
|
180
|
+
)
|
simpler_torch/ops.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
from typing import Any, overload
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
|
|
8
|
+
from .axis import Axis, AxisPair
|
|
9
|
+
from .tensor import _SCALAR, NamedTensor, Operand, Scalar, TensorLike, _union_axes, as_named_tensor
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _pair_sort_key(ops: list[NamedTensor], pair: AxisPair) -> tuple[int, tuple[tuple[int, int, str], ...]]:
|
|
13
|
+
positions = tuple(
|
|
14
|
+
(i, ops[i]._axes.index(a) if a in ops[i]._axes else -1, a.name)
|
|
15
|
+
for i, a in enumerate(pair.items)
|
|
16
|
+
if i < len(ops) and isinstance(a, Axis)
|
|
17
|
+
)
|
|
18
|
+
return (len(pair.items), positions)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _axis_sort_key(ops: list[NamedTensor], axis: Axis) -> tuple[tuple[tuple[int, int], ...], str]:
|
|
22
|
+
positions = tuple((i, x._axes.index(axis)) for i, x in enumerate(ops) if axis in x._axes)
|
|
23
|
+
return (positions, axis.name)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def contract(*operands: TensorLike, over: Axis | AxisPair | Iterable[Axis | AxisPair]) -> NamedTensor:
|
|
27
|
+
if not operands:
|
|
28
|
+
raise ValueError("contract requires at least one operand")
|
|
29
|
+
ops = [as_named_tensor(x) for x in operands]
|
|
30
|
+
items: list[Axis | AxisPair] = [over] if isinstance(over, (Axis, AxisPair)) else list(over)
|
|
31
|
+
pairs: list[AxisPair] = []
|
|
32
|
+
shared: list[Axis] = []
|
|
33
|
+
for item in items:
|
|
34
|
+
if isinstance(item, AxisPair):
|
|
35
|
+
pairs.append(item)
|
|
36
|
+
elif isinstance(item, Axis):
|
|
37
|
+
shared.append(item)
|
|
38
|
+
else:
|
|
39
|
+
raise TypeError(f"contract over item must be Axis or AxisPair, got {item!r}")
|
|
40
|
+
pairs.sort(key=lambda p: _pair_sort_key(ops, p))
|
|
41
|
+
shared.sort(key=lambda a: _axis_sort_key(ops, a))
|
|
42
|
+
groups: list[AxisPair | Axis] = [*pairs, *shared]
|
|
43
|
+
remaining = [list(x._axes) for x in ops]
|
|
44
|
+
ids: list[list[int | None]] = [[None] * len(x._axes) for x in ops]
|
|
45
|
+
next_id = 0
|
|
46
|
+
for group in groups:
|
|
47
|
+
if isinstance(group, Axis):
|
|
48
|
+
axis = group
|
|
49
|
+
holders = [i for i, rest in enumerate(remaining) if axis in rest]
|
|
50
|
+
if len(holders) < min(2, len(ops)):
|
|
51
|
+
raise ValueError(
|
|
52
|
+
f"shared axis {axis} must be held by at least {min(2, len(ops))} operands, found in operands {holders}"
|
|
53
|
+
)
|
|
54
|
+
members = [(i, axis) for i in holders]
|
|
55
|
+
else:
|
|
56
|
+
members = [(i, a) for i, a in enumerate(group.items) if isinstance(a, Axis)]
|
|
57
|
+
if len(group.items) != len(ops) or len(members) < 2:
|
|
58
|
+
raise ValueError(
|
|
59
|
+
f"paired axes {group} must have one entry per operand ({len(ops)}) with at least 2 axes"
|
|
60
|
+
)
|
|
61
|
+
first: tuple[int, Axis, int] | None = None
|
|
62
|
+
for i, axis in members:
|
|
63
|
+
if axis not in remaining[i]:
|
|
64
|
+
raise ValueError(f"axis {axis} of operand {i} is missing or already consumed")
|
|
65
|
+
pos = ops[i]._axes.index(axis)
|
|
66
|
+
n = ops[i]._tensor.shape[pos]
|
|
67
|
+
if first is None:
|
|
68
|
+
first = (i, axis, n)
|
|
69
|
+
elif n != first[2]:
|
|
70
|
+
raise ValueError(
|
|
71
|
+
f"contracted axis {axis} of operand {i} has length {n}, but axis {first[1]} of operand {first[0]} has length {first[2]}"
|
|
72
|
+
)
|
|
73
|
+
remaining[i].remove(axis)
|
|
74
|
+
ids[i][pos] = next_id
|
|
75
|
+
next_id += 1
|
|
76
|
+
free: dict[Axis, tuple[int, int, int]] = {}
|
|
77
|
+
for i, x in enumerate(ops):
|
|
78
|
+
for pos, axis in enumerate(x._axes):
|
|
79
|
+
if ids[i][pos] is not None:
|
|
80
|
+
continue
|
|
81
|
+
n = x._tensor.shape[pos]
|
|
82
|
+
if axis in free:
|
|
83
|
+
j, m, k = free[axis]
|
|
84
|
+
if m != n:
|
|
85
|
+
raise ValueError(f"free axis {axis} length mismatch: operand {j} has {m}, operand {i} has {n}")
|
|
86
|
+
ids[i][pos] = k
|
|
87
|
+
else:
|
|
88
|
+
free[axis] = (i, n, next_id)
|
|
89
|
+
ids[i][pos] = next_id
|
|
90
|
+
next_id += 1
|
|
91
|
+
args: list[Any] = []
|
|
92
|
+
for x, sub in zip(ops, ids):
|
|
93
|
+
args.extend((x._tensor, sub))
|
|
94
|
+
args.append([k for _, _, k in free.values()])
|
|
95
|
+
return NamedTensor(torch.einsum(*args), list(free))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@overload
|
|
99
|
+
def cat(*operands: TensorLike, on: Axis, to: Axis | None = None) -> NamedTensor: ...
|
|
100
|
+
@overload
|
|
101
|
+
def cat(*operands: TensorLike, on: AxisPair, to: Axis) -> NamedTensor: ...
|
|
102
|
+
def cat(*operands: TensorLike, on: Axis | AxisPair, to: Axis | None = None) -> NamedTensor:
|
|
103
|
+
if not operands:
|
|
104
|
+
raise ValueError("cat requires at least one operand")
|
|
105
|
+
ops = [as_named_tensor(x) for x in operands]
|
|
106
|
+
if isinstance(on, AxisPair):
|
|
107
|
+
if len(on.items) != len(ops):
|
|
108
|
+
raise ValueError(f"cat on pair length {len(on.items)} must match operand count {len(ops)}")
|
|
109
|
+
cat_axes = [a for a in on.items if isinstance(a, Axis)]
|
|
110
|
+
if len(cat_axes) != len(on.items):
|
|
111
|
+
raise ValueError(f"cat on pair {on} cannot contain skip")
|
|
112
|
+
if to is None:
|
|
113
|
+
raise ValueError(f"cat over differently named axes {on} requires to")
|
|
114
|
+
else:
|
|
115
|
+
cat_axes = [on] * len(ops)
|
|
116
|
+
ref = ops[0]
|
|
117
|
+
first_axis = cat_axes[0]
|
|
118
|
+
if first_axis not in ref._axes:
|
|
119
|
+
raise ValueError(f"cat operand 0 does not have axis {first_axis}")
|
|
120
|
+
base = ref.shape
|
|
121
|
+
del base[first_axis]
|
|
122
|
+
tensors: list[torch.Tensor] = []
|
|
123
|
+
for i, (x, axis) in enumerate(zip(ops, cat_axes)):
|
|
124
|
+
if axis not in x._axes:
|
|
125
|
+
raise ValueError(f"cat operand {i} does not have axis {axis}")
|
|
126
|
+
rest = x.shape
|
|
127
|
+
del rest[axis]
|
|
128
|
+
if rest != base:
|
|
129
|
+
raise ValueError(f"cat operand {i} has non-concatenated axes {rest}, expected {base}")
|
|
130
|
+
order = [axis if a is first_axis else a for a in ref._axes]
|
|
131
|
+
tensors.append(x._tensor.permute([x._axes.index(a) for a in order]))
|
|
132
|
+
pos = ref._axes.index(first_axis)
|
|
133
|
+
axes = list(ref._axes)
|
|
134
|
+
axes[pos] = first_axis if to is None else to
|
|
135
|
+
return NamedTensor(torch.cat(tensors, dim=pos), axes)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def stack(*operands: TensorLike, to: Axis) -> NamedTensor:
|
|
139
|
+
if not operands:
|
|
140
|
+
raise ValueError("stack requires at least one operand")
|
|
141
|
+
ops = [as_named_tensor(x) for x in operands]
|
|
142
|
+
ref = ops[0]
|
|
143
|
+
base = ref.shape
|
|
144
|
+
for i, x in enumerate(ops):
|
|
145
|
+
if x.shape != base:
|
|
146
|
+
raise ValueError(f"stack operand {i} has axes {x.shape}, expected {base}")
|
|
147
|
+
tensors = [x._tensor.permute([x._axes.index(a) for a in ref._axes]) for x in ops]
|
|
148
|
+
return NamedTensor(torch.stack(tensors, dim=0), [to, *ref._axes])
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def unbind(x: TensorLike, on: Axis) -> tuple[NamedTensor, ...]:
|
|
152
|
+
return as_named_tensor(x).unbind(on)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def where(cond: TensorLike, x: Operand, y: Operand) -> NamedTensor:
|
|
156
|
+
c = as_named_tensor(cond)
|
|
157
|
+
if c.dtype is not torch.bool:
|
|
158
|
+
raise TypeError(f"where condition must have dtype torch.bool, got {c.dtype}")
|
|
159
|
+
vx: NamedTensor | Scalar = x if isinstance(x, _SCALAR) else as_named_tensor(x)
|
|
160
|
+
vy: NamedTensor | Scalar = y if isinstance(y, _SCALAR) else as_named_tensor(y)
|
|
161
|
+
tensors = [t for t in (c, vx, vy) if isinstance(t, NamedTensor)]
|
|
162
|
+
axes = _union_axes(tensors)
|
|
163
|
+
cx = c._align_to(axes)
|
|
164
|
+
tx = vx._align_to(axes) if isinstance(vx, NamedTensor) else vx
|
|
165
|
+
ty = vy._align_to(axes) if isinstance(vy, NamedTensor) else vy
|
|
166
|
+
return NamedTensor(torch.where(cx, tx, ty), axes)
|
simpler_torch/py.typed
ADDED
|
File without changes
|
simpler_torch/tensor.py
ADDED
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
4
|
+
import math
|
|
5
|
+
import operator
|
|
6
|
+
from typing import Any, TypeGuard, cast, overload
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
from .axis import Axis, AxisIndex
|
|
11
|
+
|
|
12
|
+
type Scalar = int | float | bool
|
|
13
|
+
type TensorLike = NamedTensor | tuple[torch.Tensor, Sequence[Axis]]
|
|
14
|
+
type Operand = TensorLike | Scalar
|
|
15
|
+
type SubscriptItem = AxisIndex | slice
|
|
16
|
+
|
|
17
|
+
_SCALAR = (int, float, bool)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _parse_axes(axes: tuple[Axis | Sequence[Axis], ...]) -> list[Axis]:
|
|
21
|
+
if len(axes) == 1 and not isinstance(axes[0], Axis):
|
|
22
|
+
return list(axes[0])
|
|
23
|
+
return list(cast(tuple[Axis, ...], axes))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _as_axis_list(axes: Axis | Sequence[Axis]) -> list[Axis]:
|
|
27
|
+
return [axes] if isinstance(axes, Axis) else list(axes)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@overload
|
|
31
|
+
def bind(tensor: torch.Tensor, axes: Sequence[Axis], /) -> NamedTensor: ...
|
|
32
|
+
@overload
|
|
33
|
+
def bind(tensor: torch.Tensor, *axes: Axis) -> NamedTensor: ...
|
|
34
|
+
def bind(tensor: torch.Tensor, *axes: Axis | Sequence[Axis]) -> NamedTensor:
|
|
35
|
+
return NamedTensor(tensor, _parse_axes(axes))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def as_named_tensor(x: TensorLike) -> NamedTensor:
|
|
39
|
+
if isinstance(x, NamedTensor):
|
|
40
|
+
return x
|
|
41
|
+
tensor, axes = x
|
|
42
|
+
return NamedTensor(tensor, axes)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _union_axes(operands: Sequence[NamedTensor]) -> list[Axis]:
|
|
46
|
+
sizes: dict[Axis, tuple[int, int]] = {}
|
|
47
|
+
for i, x in enumerate(operands):
|
|
48
|
+
for axis, n in zip(x._axes, x._tensor.shape):
|
|
49
|
+
if axis in sizes:
|
|
50
|
+
j, m = sizes[axis]
|
|
51
|
+
if m != n:
|
|
52
|
+
raise ValueError(f"axis {axis} length mismatch: operand {j} has {m}, operand {i} has {n}")
|
|
53
|
+
else:
|
|
54
|
+
sizes[axis] = (i, n)
|
|
55
|
+
return list(sizes)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _is_operand(other: object) -> TypeGuard[Operand]:
|
|
59
|
+
return isinstance(other, (*_SCALAR, NamedTensor)) or (
|
|
60
|
+
isinstance(other, tuple) and len(other) == 2 and isinstance(other[0], torch.Tensor)
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _as_index(value: Any) -> int:
|
|
65
|
+
return value if isinstance(value, (int, torch.SymInt)) else operator.index(value)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _reverse_slice_to_forward(start: int | None, stop: int | None, step: int, n: int) -> slice:
|
|
69
|
+
k = torch.sym_min(-step, torch.sym_max(n, 1))
|
|
70
|
+
if start is None and stop is None:
|
|
71
|
+
if step == -1:
|
|
72
|
+
return slice(None)
|
|
73
|
+
return slice((n - 1) % k, None, k)
|
|
74
|
+
if start is None:
|
|
75
|
+
s = n - 1
|
|
76
|
+
elif start < 0:
|
|
77
|
+
s = torch.sym_max(start + n, -1)
|
|
78
|
+
else:
|
|
79
|
+
s = torch.sym_min(start, n - 1)
|
|
80
|
+
if stop is None:
|
|
81
|
+
e = -1
|
|
82
|
+
elif stop < 0:
|
|
83
|
+
e = torch.sym_max(stop + n, -1)
|
|
84
|
+
else:
|
|
85
|
+
e = torch.sym_min(stop, n - 1)
|
|
86
|
+
span = torch.sym_max(s - e, 0)
|
|
87
|
+
count = (span + k - 1) // k
|
|
88
|
+
lo = torch.sym_min(torch.sym_max(s - torch.sym_max(count - 1, 0) * k, 0), n)
|
|
89
|
+
hi = torch.sym_min(lo + count * k, torch.sym_max(s + 1, 0))
|
|
90
|
+
return slice(lo, hi, k)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class NamedTensor:
|
|
94
|
+
_tensor: torch.Tensor
|
|
95
|
+
_axes: list[Axis]
|
|
96
|
+
|
|
97
|
+
@overload
|
|
98
|
+
def __init__(self, tensor: torch.Tensor, axes: Sequence[Axis], /) -> None: ...
|
|
99
|
+
@overload
|
|
100
|
+
def __init__(self, tensor: torch.Tensor, *axes: Axis) -> None: ...
|
|
101
|
+
def __init__(self, tensor: torch.Tensor, *axes: Axis | Sequence[Axis]) -> None:
|
|
102
|
+
resolved = _parse_axes(axes)
|
|
103
|
+
if tensor.ndim != len(resolved):
|
|
104
|
+
raise ValueError(
|
|
105
|
+
f"tensor of shape {tuple(tensor.shape)} has {tensor.ndim} dims but got {len(resolved)} axes {resolved}"
|
|
106
|
+
)
|
|
107
|
+
if len(set(resolved)) != len(resolved):
|
|
108
|
+
raise ValueError(f"duplicate axes {resolved} for tensor of shape {tuple(tensor.shape)}")
|
|
109
|
+
self._tensor = tensor
|
|
110
|
+
self._axes = resolved
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def axes(self) -> frozenset[Axis]:
|
|
114
|
+
return frozenset(self._axes)
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def shape(self) -> dict[Axis, int]:
|
|
118
|
+
return dict(zip(self._axes, self._tensor.shape))
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def ndim(self) -> int:
|
|
122
|
+
return self._tensor.ndim
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def dtype(self) -> torch.dtype:
|
|
126
|
+
return self._tensor.dtype
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def device(self) -> torch.device:
|
|
130
|
+
return self._tensor.device
|
|
131
|
+
|
|
132
|
+
def item(self) -> Scalar:
|
|
133
|
+
return self._tensor.item()
|
|
134
|
+
|
|
135
|
+
def __bool__(self) -> bool:
|
|
136
|
+
return bool(self._tensor)
|
|
137
|
+
|
|
138
|
+
def __repr__(self) -> str:
|
|
139
|
+
content: object = self._tensor.item() if self._tensor.ndim == 0 else self.shape
|
|
140
|
+
return f"NamedTensor({content}, dtype={self._tensor.dtype})"
|
|
141
|
+
|
|
142
|
+
@overload
|
|
143
|
+
def tensor(self, axes: Sequence[Axis], /) -> torch.Tensor: ...
|
|
144
|
+
@overload
|
|
145
|
+
def tensor(self, *axes: Axis) -> torch.Tensor: ...
|
|
146
|
+
def tensor(self, *axes: Axis | Sequence[Axis]) -> torch.Tensor:
|
|
147
|
+
target = _parse_axes(axes)
|
|
148
|
+
if len(target) != len(set(target)):
|
|
149
|
+
raise ValueError(f"duplicate export axes {target} for tensor axes {self._axes}")
|
|
150
|
+
if set(target) != set(self._axes):
|
|
151
|
+
missing = [a for a in self._axes if a not in target]
|
|
152
|
+
extra = [a for a in target if a not in self._axes]
|
|
153
|
+
raise ValueError(
|
|
154
|
+
f"export axes {target} do not match tensor axes {self._axes}: missing {missing}, unexpected {extra}"
|
|
155
|
+
)
|
|
156
|
+
return self._tensor.permute([self._axes.index(a) for a in target])
|
|
157
|
+
|
|
158
|
+
def _align_to(self, target: Sequence[Axis]) -> torch.Tensor:
|
|
159
|
+
if self._tensor.ndim == 0:
|
|
160
|
+
return self._tensor
|
|
161
|
+
order = [a for a in target if a in self._axes]
|
|
162
|
+
t = self._tensor.permute([self._axes.index(a) for a in order])
|
|
163
|
+
return t.reshape([t.shape[order.index(a)] if a in self._axes else 1 for a in target])
|
|
164
|
+
|
|
165
|
+
def _apply_binary(self, other: Operand, op: Callable[[Any, Any], torch.Tensor]) -> NamedTensor:
|
|
166
|
+
if isinstance(other, _SCALAR):
|
|
167
|
+
return NamedTensor(op(self._tensor, other), self._axes)
|
|
168
|
+
rhs = as_named_tensor(other)
|
|
169
|
+
axes = _union_axes([self, rhs])
|
|
170
|
+
return NamedTensor(op(self._align_to(axes), rhs._align_to(axes)), axes)
|
|
171
|
+
|
|
172
|
+
def __getitem__(self, items: SubscriptItem | tuple[SubscriptItem, ...]) -> NamedTensor:
|
|
173
|
+
entries = items if isinstance(items, tuple) else (items,)
|
|
174
|
+
index: list[int | slice] = [slice(None)] * len(self._axes)
|
|
175
|
+
renames: dict[int, Axis] = {}
|
|
176
|
+
flips: set[int] = set()
|
|
177
|
+
seen: set[int] = set()
|
|
178
|
+
for item in entries:
|
|
179
|
+
new: Axis | None = None
|
|
180
|
+
if isinstance(item, slice):
|
|
181
|
+
if item.step is not None:
|
|
182
|
+
raise ValueError(f"rename syntax does not accept step, got {item!r}")
|
|
183
|
+
source, new = item.start, item.stop
|
|
184
|
+
if new is None:
|
|
185
|
+
raise ValueError(f"rename requires a target Axis after ':', got {item!r}")
|
|
186
|
+
if isinstance(source, AxisIndex):
|
|
187
|
+
if not isinstance(source.index, slice):
|
|
188
|
+
raise ValueError(
|
|
189
|
+
f"renaming {source.axis} to {new} requires a slice index, got {source.index!r}"
|
|
190
|
+
)
|
|
191
|
+
axis, idx = source.axis, source.index
|
|
192
|
+
else:
|
|
193
|
+
axis, idx = source, slice(None)
|
|
194
|
+
else:
|
|
195
|
+
axis, idx = item.axis, item.index
|
|
196
|
+
if not isinstance(idx, slice) and (isinstance(idx, bool) or not isinstance(idx, (int, torch.SymInt))):
|
|
197
|
+
raise TypeError(f"index on axis {axis} must be a slice or int, got {idx!r}")
|
|
198
|
+
pos = self._axes.index(axis)
|
|
199
|
+
if pos in seen:
|
|
200
|
+
raise ValueError(f"axis {axis} is specified more than once")
|
|
201
|
+
seen.add(pos)
|
|
202
|
+
if isinstance(idx, slice):
|
|
203
|
+
start = None if idx.start is None else _as_index(idx.start)
|
|
204
|
+
stop = None if idx.stop is None else _as_index(idx.stop)
|
|
205
|
+
step = None if idx.step is None else _as_index(idx.step)
|
|
206
|
+
if step == 0:
|
|
207
|
+
raise ValueError("slice step cannot be zero")
|
|
208
|
+
if step is not None and step < 0:
|
|
209
|
+
idx = _reverse_slice_to_forward(start, stop, step, self._tensor.shape[pos])
|
|
210
|
+
flips.add(pos)
|
|
211
|
+
else:
|
|
212
|
+
if step is not None and step > 1:
|
|
213
|
+
step = torch.sym_min(step, torch.sym_max(self._tensor.shape[pos], 1))
|
|
214
|
+
idx = slice(start, stop, step)
|
|
215
|
+
index[pos] = idx
|
|
216
|
+
if new is not None:
|
|
217
|
+
renames[pos] = new
|
|
218
|
+
t = self._tensor[tuple(index)]
|
|
219
|
+
axes: list[Axis] = []
|
|
220
|
+
flip_dims: list[int] = []
|
|
221
|
+
for p, a in enumerate(self._axes):
|
|
222
|
+
if isinstance(index[p], slice):
|
|
223
|
+
if p in flips:
|
|
224
|
+
flip_dims.append(len(axes))
|
|
225
|
+
axes.append(renames.get(p, a))
|
|
226
|
+
if flip_dims:
|
|
227
|
+
t = torch.flip(t, dims=flip_dims)
|
|
228
|
+
return NamedTensor(t, axes)
|
|
229
|
+
|
|
230
|
+
def merge(self, by: Axis | Sequence[Axis], to: Axis) -> NamedTensor:
|
|
231
|
+
sources = _as_axis_list(by)
|
|
232
|
+
if not sources:
|
|
233
|
+
raise ValueError("merge requires at least one axis in by")
|
|
234
|
+
if len(set(sources)) != len(sources):
|
|
235
|
+
raise ValueError(f"duplicate axes {sources} in merge")
|
|
236
|
+
pos = [self._axes.index(a) for a in sources]
|
|
237
|
+
first = min(pos)
|
|
238
|
+
before = [p for p in range(first) if p not in pos]
|
|
239
|
+
after = [p for p in range(first, len(self._axes)) if p not in pos]
|
|
240
|
+
size = self._tensor.shape
|
|
241
|
+
t = self._tensor.permute(before + pos + after)
|
|
242
|
+
shape = [size[p] for p in before] + [math.prod([size[p] for p in pos])] + [size[p] for p in after]
|
|
243
|
+
axes = [self._axes[p] for p in before] + [to] + [self._axes[p] for p in after]
|
|
244
|
+
return NamedTensor(t.reshape(shape), axes)
|
|
245
|
+
|
|
246
|
+
def split(self, on: Axis, to: Mapping[Axis, int]) -> NamedTensor:
|
|
247
|
+
if not to:
|
|
248
|
+
raise ValueError("split requires at least one target axis in to")
|
|
249
|
+
pos = self._axes.index(on)
|
|
250
|
+
dim_size = self._tensor.shape[pos]
|
|
251
|
+
target_sizes = list(to.values())
|
|
252
|
+
inferred_idx: int | None = None
|
|
253
|
+
known_prod = 1
|
|
254
|
+
for i, s in enumerate(target_sizes):
|
|
255
|
+
if isinstance(s, bool):
|
|
256
|
+
raise TypeError(f"split target size must be int, got {s!r}")
|
|
257
|
+
if s == -1:
|
|
258
|
+
if inferred_idx is not None:
|
|
259
|
+
raise ValueError(f"split can infer at most one axis size, got {dict(to)}")
|
|
260
|
+
inferred_idx = i
|
|
261
|
+
elif s < 0:
|
|
262
|
+
raise ValueError(f"split target size must be non-negative or -1, got {dict(to)}")
|
|
263
|
+
else:
|
|
264
|
+
known_prod *= s
|
|
265
|
+
if inferred_idx is not None:
|
|
266
|
+
if known_prod == 0 or dim_size % known_prod != 0:
|
|
267
|
+
raise ValueError(f"cannot split axis {on} of size {dim_size} into {dict(to)}")
|
|
268
|
+
target_sizes[inferred_idx] = dim_size // known_prod
|
|
269
|
+
elif known_prod != dim_size:
|
|
270
|
+
raise ValueError(f"cannot split axis {on} of size {dim_size} into {dict(to)}")
|
|
271
|
+
axes = list(self._axes)
|
|
272
|
+
axes[pos : pos + 1] = to.keys()
|
|
273
|
+
if len(set(axes)) != len(axes):
|
|
274
|
+
raise ValueError(f"duplicate axes {axes} after splitting {on} into {list(to)}")
|
|
275
|
+
shape = list(self._tensor.shape)
|
|
276
|
+
shape[pos : pos + 1] = target_sizes
|
|
277
|
+
return NamedTensor(self._tensor.reshape(shape), axes)
|
|
278
|
+
|
|
279
|
+
def unbind(self, on: Axis) -> tuple[NamedTensor, ...]:
|
|
280
|
+
pos = self._axes.index(on)
|
|
281
|
+
axes = [a for a in self._axes if a is not on]
|
|
282
|
+
return tuple(NamedTensor(t, axes) for t in self._tensor.unbind(pos))
|
|
283
|
+
|
|
284
|
+
@overload
|
|
285
|
+
def apply(
|
|
286
|
+
self,
|
|
287
|
+
fn: Callable[..., torch.Tensor],
|
|
288
|
+
*args: Any,
|
|
289
|
+
on: Axis | Iterable[Axis] | None = None,
|
|
290
|
+
to: Axis | None = None,
|
|
291
|
+
**kwargs: Any,
|
|
292
|
+
) -> NamedTensor: ...
|
|
293
|
+
@overload
|
|
294
|
+
def apply(
|
|
295
|
+
self,
|
|
296
|
+
fn: Callable[..., tuple[torch.Tensor, ...]],
|
|
297
|
+
*args: Any,
|
|
298
|
+
on: Axis | Iterable[Axis] | None = None,
|
|
299
|
+
to: Axis | None = None,
|
|
300
|
+
**kwargs: Any,
|
|
301
|
+
) -> tuple[NamedTensor, ...]: ...
|
|
302
|
+
def apply(
|
|
303
|
+
self,
|
|
304
|
+
fn: Callable[..., Any],
|
|
305
|
+
*args: Any,
|
|
306
|
+
on: Axis | Iterable[Axis] | None = None,
|
|
307
|
+
to: Axis | None = None,
|
|
308
|
+
**kwargs: Any,
|
|
309
|
+
) -> NamedTensor | tuple[NamedTensor, ...]:
|
|
310
|
+
if "keepdim" in kwargs:
|
|
311
|
+
raise ValueError("apply does not accept keepdim; use missing-axis broadcasting after reduction")
|
|
312
|
+
for forbidden in ("dim", "dims", "axis"):
|
|
313
|
+
if forbidden in kwargs:
|
|
314
|
+
raise ValueError(f"apply does not accept {forbidden}; specify target axes with on=")
|
|
315
|
+
if on is None:
|
|
316
|
+
if to is not None:
|
|
317
|
+
raise ValueError("apply with to requires a single Axis in on")
|
|
318
|
+
dims: list[int] | None = None
|
|
319
|
+
out = fn(self._tensor, *args, **kwargs)
|
|
320
|
+
elif isinstance(on, Axis):
|
|
321
|
+
dims = [self._axes.index(on)]
|
|
322
|
+
if to is not None:
|
|
323
|
+
out_axes = list(self._axes)
|
|
324
|
+
out_axes[dims[0]] = to
|
|
325
|
+
if len(set(out_axes)) != len(out_axes):
|
|
326
|
+
raise ValueError(f"duplicate axes {out_axes} after applying on {on} to {to}")
|
|
327
|
+
out = fn(self._tensor, *args, dim=dims[0], **kwargs)
|
|
328
|
+
else:
|
|
329
|
+
targets = list(on)
|
|
330
|
+
if not targets:
|
|
331
|
+
raise ValueError("apply requires at least one axis in on")
|
|
332
|
+
if len(set(targets)) != len(targets):
|
|
333
|
+
raise ValueError(f"duplicate axes {targets} in apply")
|
|
334
|
+
if to is not None:
|
|
335
|
+
raise ValueError("apply with to requires a single Axis in on")
|
|
336
|
+
dims = sorted(self._axes.index(a) for a in targets)
|
|
337
|
+
out = fn(self._tensor, *args, dim=dims, **kwargs)
|
|
338
|
+
if isinstance(out, tuple):
|
|
339
|
+
return tuple(self._wrap_apply(o, dims, to) for o in out)
|
|
340
|
+
return self._wrap_apply(out, dims, to)
|
|
341
|
+
|
|
342
|
+
def _wrap_apply(self, out: torch.Tensor, dims: list[int] | None, to: Axis | None) -> NamedTensor:
|
|
343
|
+
size = self._tensor.shape
|
|
344
|
+
if dims is None:
|
|
345
|
+
if out.shape != size:
|
|
346
|
+
raise ValueError(f"elementwise fn changed shape from {tuple(size)} to {tuple(out.shape)}")
|
|
347
|
+
return NamedTensor(out, self._axes)
|
|
348
|
+
keep = [p for p in range(len(self._axes)) if p not in dims]
|
|
349
|
+
kept = tuple(size[p] for p in keep)
|
|
350
|
+
if out.ndim == len(self._axes) and tuple(out.shape[p] for p in keep) == kept:
|
|
351
|
+
axes = list(self._axes)
|
|
352
|
+
if to is not None:
|
|
353
|
+
axes[dims[0]] = to
|
|
354
|
+
return NamedTensor(out, axes)
|
|
355
|
+
if to is None and out.ndim == len(keep) and tuple(out.shape) == kept:
|
|
356
|
+
return NamedTensor(out, [self._axes[p] for p in keep])
|
|
357
|
+
raise ValueError(
|
|
358
|
+
f"fn output shape {tuple(out.shape)} is incompatible with input {self.shape} on {[self._axes[p] for p in dims]}"
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
@overload
|
|
362
|
+
def via(
|
|
363
|
+
self,
|
|
364
|
+
fn: Callable[..., torch.Tensor],
|
|
365
|
+
*args: Any,
|
|
366
|
+
by: Axis | Sequence[Axis] = (),
|
|
367
|
+
to: Axis | Sequence[Axis] | None = None,
|
|
368
|
+
**kwargs: Any,
|
|
369
|
+
) -> NamedTensor: ...
|
|
370
|
+
@overload
|
|
371
|
+
def via(
|
|
372
|
+
self,
|
|
373
|
+
fn: Callable[..., tuple[torch.Tensor, ...]],
|
|
374
|
+
*args: Any,
|
|
375
|
+
by: Axis | Sequence[Axis] = (),
|
|
376
|
+
to: Axis | Sequence[Axis] | None = None,
|
|
377
|
+
**kwargs: Any,
|
|
378
|
+
) -> tuple[NamedTensor, ...]: ...
|
|
379
|
+
def via(
|
|
380
|
+
self,
|
|
381
|
+
fn: Callable[..., Any],
|
|
382
|
+
*args: Any,
|
|
383
|
+
by: Axis | Sequence[Axis] = (),
|
|
384
|
+
to: Axis | Sequence[Axis] | None = None,
|
|
385
|
+
**kwargs: Any,
|
|
386
|
+
) -> NamedTensor | tuple[NamedTensor, ...]:
|
|
387
|
+
by_axes = _as_axis_list(by)
|
|
388
|
+
if len(set(by_axes)) != len(by_axes):
|
|
389
|
+
raise ValueError(f"duplicate axes {by_axes} in via")
|
|
390
|
+
to_axes = by_axes if to is None else _as_axis_list(to)
|
|
391
|
+
by_pos = [self._axes.index(a) for a in by_axes]
|
|
392
|
+
free_pos = [p for p in range(len(self._axes)) if p not in by_pos]
|
|
393
|
+
out_axes = [self._axes[p] for p in free_pos] + to_axes
|
|
394
|
+
if len(set(out_axes)) != len(out_axes):
|
|
395
|
+
raise ValueError(f"duplicate output axes {out_axes} in via")
|
|
396
|
+
size = self._tensor.shape
|
|
397
|
+
free_sizes = [size[p] for p in free_pos]
|
|
398
|
+
by_sizes = [size[p] for p in by_pos]
|
|
399
|
+
n = math.prod(free_sizes)
|
|
400
|
+
order = free_pos + by_pos
|
|
401
|
+
t = self._tensor if order == list(range(len(self._axes))) else self._tensor.permute(order)
|
|
402
|
+
out = fn(t.reshape([n, *by_sizes]), *args, **kwargs)
|
|
403
|
+
if isinstance(out, tuple):
|
|
404
|
+
return tuple(self._wrap_via(o, n, free_sizes, out_axes, len(to_axes)) for o in out)
|
|
405
|
+
return self._wrap_via(out, n, free_sizes, out_axes, len(to_axes))
|
|
406
|
+
|
|
407
|
+
def _wrap_via(
|
|
408
|
+
self,
|
|
409
|
+
out: torch.Tensor,
|
|
410
|
+
n: int,
|
|
411
|
+
free_sizes: list[int],
|
|
412
|
+
out_axes: list[Axis],
|
|
413
|
+
to_len: int,
|
|
414
|
+
) -> NamedTensor:
|
|
415
|
+
if out.ndim != 1 + to_len or out.shape[0] != n:
|
|
416
|
+
raise ValueError(
|
|
417
|
+
f"via fn output shape {tuple(out.shape)} must have {1 + to_len} dims and leading size {n}"
|
|
418
|
+
)
|
|
419
|
+
return NamedTensor(out.reshape([*free_sizes, *out.shape[1:]]), out_axes)
|
|
420
|
+
|
|
421
|
+
def __add__(self, other: Operand) -> NamedTensor:
|
|
422
|
+
return self._apply_binary(other, operator.add)
|
|
423
|
+
|
|
424
|
+
def __radd__(self, other: Operand) -> NamedTensor:
|
|
425
|
+
return self._apply_binary(other, lambda a, b: b + a)
|
|
426
|
+
|
|
427
|
+
def __sub__(self, other: Operand) -> NamedTensor:
|
|
428
|
+
return self._apply_binary(other, operator.sub)
|
|
429
|
+
|
|
430
|
+
def __rsub__(self, other: Operand) -> NamedTensor:
|
|
431
|
+
return self._apply_binary(other, lambda a, b: b - a)
|
|
432
|
+
|
|
433
|
+
def __mul__(self, other: Operand) -> NamedTensor:
|
|
434
|
+
return self._apply_binary(other, operator.mul)
|
|
435
|
+
|
|
436
|
+
def __rmul__(self, other: Operand) -> NamedTensor:
|
|
437
|
+
return self._apply_binary(other, lambda a, b: b * a)
|
|
438
|
+
|
|
439
|
+
def __truediv__(self, other: Operand) -> NamedTensor:
|
|
440
|
+
return self._apply_binary(other, operator.truediv)
|
|
441
|
+
|
|
442
|
+
def __rtruediv__(self, other: Operand) -> NamedTensor:
|
|
443
|
+
return self._apply_binary(other, lambda a, b: b / a)
|
|
444
|
+
|
|
445
|
+
def __floordiv__(self, other: Operand) -> NamedTensor:
|
|
446
|
+
return self._apply_binary(other, operator.floordiv)
|
|
447
|
+
|
|
448
|
+
def __rfloordiv__(self, other: Operand) -> NamedTensor:
|
|
449
|
+
return self._apply_binary(other, lambda a, b: b // a)
|
|
450
|
+
|
|
451
|
+
def __mod__(self, other: Operand) -> NamedTensor:
|
|
452
|
+
return self._apply_binary(other, operator.mod)
|
|
453
|
+
|
|
454
|
+
def __rmod__(self, other: Operand) -> NamedTensor:
|
|
455
|
+
return self._apply_binary(other, lambda a, b: b % a)
|
|
456
|
+
|
|
457
|
+
def __pow__(self, other: Operand) -> NamedTensor:
|
|
458
|
+
return self._apply_binary(other, operator.pow)
|
|
459
|
+
|
|
460
|
+
def __rpow__(self, other: Operand) -> NamedTensor:
|
|
461
|
+
return self._apply_binary(other, lambda a, b: b**a)
|
|
462
|
+
|
|
463
|
+
def __and__(self, other: Operand) -> NamedTensor:
|
|
464
|
+
return self._apply_binary(other, operator.and_)
|
|
465
|
+
|
|
466
|
+
def __rand__(self, other: Operand) -> NamedTensor:
|
|
467
|
+
return self._apply_binary(other, lambda a, b: b & a)
|
|
468
|
+
|
|
469
|
+
def __or__(self, other: Operand) -> NamedTensor:
|
|
470
|
+
return self._apply_binary(other, operator.or_)
|
|
471
|
+
|
|
472
|
+
def __ror__(self, other: Operand) -> NamedTensor:
|
|
473
|
+
return self._apply_binary(other, lambda a, b: b | a)
|
|
474
|
+
|
|
475
|
+
def __xor__(self, other: Operand) -> NamedTensor:
|
|
476
|
+
return self._apply_binary(other, operator.xor)
|
|
477
|
+
|
|
478
|
+
def __rxor__(self, other: Operand) -> NamedTensor:
|
|
479
|
+
return self._apply_binary(other, lambda a, b: b ^ a)
|
|
480
|
+
|
|
481
|
+
def __lt__(self, other: Operand) -> NamedTensor:
|
|
482
|
+
return self._apply_binary(other, operator.lt)
|
|
483
|
+
|
|
484
|
+
def __le__(self, other: Operand) -> NamedTensor:
|
|
485
|
+
return self._apply_binary(other, operator.le)
|
|
486
|
+
|
|
487
|
+
def __gt__(self, other: Operand) -> NamedTensor:
|
|
488
|
+
return self._apply_binary(other, operator.gt)
|
|
489
|
+
|
|
490
|
+
def __ge__(self, other: Operand) -> NamedTensor:
|
|
491
|
+
return self._apply_binary(other, operator.ge)
|
|
492
|
+
|
|
493
|
+
@overload # type: ignore[override]
|
|
494
|
+
def __eq__(self, other: Operand) -> NamedTensor: ...
|
|
495
|
+
@overload
|
|
496
|
+
def __eq__(self, other: object) -> bool: ...
|
|
497
|
+
def __eq__(self, other: object) -> NamedTensor | bool:
|
|
498
|
+
if _is_operand(other):
|
|
499
|
+
return self._apply_binary(other, operator.eq)
|
|
500
|
+
return NotImplemented
|
|
501
|
+
|
|
502
|
+
@overload # type: ignore[override]
|
|
503
|
+
def __ne__(self, other: Operand) -> NamedTensor: ...
|
|
504
|
+
@overload
|
|
505
|
+
def __ne__(self, other: object) -> bool: ...
|
|
506
|
+
def __ne__(self, other: object) -> NamedTensor | bool:
|
|
507
|
+
if _is_operand(other):
|
|
508
|
+
return self._apply_binary(other, operator.ne)
|
|
509
|
+
return NotImplemented
|
|
510
|
+
|
|
511
|
+
def __neg__(self) -> NamedTensor:
|
|
512
|
+
return NamedTensor(-self._tensor, self._axes)
|
|
513
|
+
|
|
514
|
+
def __pos__(self) -> NamedTensor:
|
|
515
|
+
return NamedTensor(+self._tensor, self._axes)
|
|
516
|
+
|
|
517
|
+
def __abs__(self) -> NamedTensor:
|
|
518
|
+
return NamedTensor(abs(self._tensor), self._axes)
|
|
519
|
+
|
|
520
|
+
def __invert__(self) -> NamedTensor:
|
|
521
|
+
return NamedTensor(~self._tensor, self._axes)
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: simpler-torch
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Named-axis tensors on top of PyTorch
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Dist: torch>=2.15
|
|
8
|
+
Requires-Python: >=3.12
|
|
9
|
+
Project-URL: Homepage, https://github.com/light-cyan/SimplerTorch
|
|
10
|
+
Project-URL: Repository, https://github.com/light-cyan/SimplerTorch
|
|
11
|
+
Project-URL: Documentation, https://github.com/light-cyan/SimplerTorch/blob/main/docs/en/tutorial.md
|
|
12
|
+
Project-URL: Issues, https://github.com/light-cyan/SimplerTorch/issues
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# simpler-torch
|
|
16
|
+
English | [简体中文](README.zh.md)
|
|
17
|
+
|
|
18
|
+
A named-axis tensor library built on PyTorch. It models tensor dimensions internally as a named set and length mapping, confining explicit positional ordering to the entry/exit boundaries with native PyTorch and `nn.Module`, while supporting `autograd` and `torch.compile(..., fullgraph=True, dynamic=True)` (see [Compilation, Autograd, and Caveats](docs/en/compile-and-caveats.md) for compilation conditions).
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
## What It Solves
|
|
22
|
+
`simpler-torch` does not reduce underlying math flops; its core value is eliminating the mental overhead of high-dimensional tensor code and turning silent shape bugs into immediate errors:
|
|
23
|
+
- **Eliminate positional gymnastics**: Say goodbye to sprawling `unsqueeze`, `transpose`, `permute`, and hardcoded `dim=-2`. Operators align automatically by axis name, and missing axes broadcast via outer product (for example, 1D `q_pos >= k_pos` directly produces an `{L, S}` mask). When you introduce a new time axis `T` or group axis `G` mid-pipeline, code that does not touch that axis requires zero changes.
|
|
24
|
+
- **Turn silent bugs into immediate errors**: Shared axis names enforce strict equal lengths—even a size-`1` axis refuses implicit broadcasting, preventing silent shape inflation from forgotten `squeeze` calls. Separating square-matrix roles at the boundary with distinct `Axis` objects (such as `L` and `S`) eliminates silent transposes under named contraction and raises immediately whenever an operator requires `S` that is missing or misused (if both roles are bound to `L` at entry, the library will not guess your intent).
|
|
25
|
+
- **Self-verifying documentation in code**: Replace easily outdated `# shape: [B, H, L, D]` comments with runtime-checked named semantics so code and dimension contracts always stay in sync.
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
## Scope and Trade-offs
|
|
29
|
+
- **Highest payoff in 4D+ workloads**: Best suited for multi-head / GQA / MLA attention, video and 3D vision, MoE routing, scientific computing, and new architecture prototyping. For simple 2D/3D networks, plain PyTorch is often lighter.
|
|
30
|
+
- **Best paired with `torch.compile`**: In eager mode, each operation validates axis metadata and allocates a wrapper object; pairing with `torch.compile` compiles away the wrapper overhead.
|
|
31
|
+
- **Explicit layout control at custom-kernel boundaries**: Name-based alignment may trigger `permute` and memory-reordering copies under the hood. When interfacing with layout-sensitive custom kernels such as FlashAttention or Triton, export with `.tensor(*axes)` and manage `.contiguous()` explicitly.
|
|
32
|
+
|
|
33
|
+
For details on compilation, performance, and API constraints, see [Compilation, Autograd, and Caveats](docs/en/compile-and-caveats.md).
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
## Quickstart
|
|
37
|
+
|
|
38
|
+
### 5-Line Intro to Named Operations
|
|
39
|
+
Reductions drop axes automatically and missing axes broadcast automatically—no `keepdim=True`, `unsqueeze`, or hardcoded `dim=-1`:
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
import torch
|
|
43
|
+
import simpler_torch as storch
|
|
44
|
+
|
|
45
|
+
B, L, S = storch.Axes("B L S")
|
|
46
|
+
scores = storch.bind(torch.randn(2, 6, 10), B, L, S)
|
|
47
|
+
|
|
48
|
+
# Mean along S leaves {B, L}; subtraction broadcasts automatically over missing S
|
|
49
|
+
centered = scores - scores.apply(torch.mean, on=S)
|
|
50
|
+
|
|
51
|
+
# Comparing {L} and {S} produces an {L, S} causal mask via outer-product broadcast
|
|
52
|
+
causal = storch.bind(torch.arange(6), L) >= storch.bind(torch.arange(10), S)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Advanced Example: 5D Grouped-Query Attention (GQA)
|
|
56
|
+
The higher the dimensionality, the greater the payoff of name-based alignment. Below is a 5D GQA block (`Q` with `{B, L, H_kv, G, D}`, `K`/`V` with `{B, S, H_kv, D}`) with a batched `(B, L, S)` bias—with zero `repeat_interleave`, `unsqueeze`, or manual `transpose`:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
import math
|
|
60
|
+
import torch
|
|
61
|
+
import torch.nn as nn
|
|
62
|
+
import torch.nn.functional as F
|
|
63
|
+
import simpler_torch as storch
|
|
64
|
+
|
|
65
|
+
B, L, S, H_kv, G, D, E, In, Out = storch.Axes("B L S H_kv G D E In Out")
|
|
66
|
+
|
|
67
|
+
x_raw = torch.randn(2, 6, 64)
|
|
68
|
+
w_q = torch.randn(64, 64) # (E, H_kv * G * D)
|
|
69
|
+
w_k = torch.randn(64, 16) # (E, H_kv * D)
|
|
70
|
+
w_v = torch.randn(64, 16) # (E, H_kv * D)
|
|
71
|
+
bias_raw = torch.randn(2, 6, 6) # (B, L, S)
|
|
72
|
+
ln = nn.LayerNorm(64)
|
|
73
|
+
|
|
74
|
+
# 1. Bind at entry, call nn.LayerNorm non-invasively, and rebind the KV sequence axis to S
|
|
75
|
+
x = storch.bind(x_raw, B, L, E).via(ln, by=E)
|
|
76
|
+
x_kv = x[L: S]
|
|
77
|
+
|
|
78
|
+
# 2. Cross-name contraction + split Out: Q is 5D {B, L, H_kv, G, D}, K/V are 4D {B, S, H_kv, D}
|
|
79
|
+
q = storch.contract(x, (w_q, [In, Out]), over=E & In).split(on=Out, to={H_kv: 2, G: 4, D: -1})
|
|
80
|
+
k = storch.contract(x_kv, (w_k, [In, Out]), over=E & In).split(on=Out, to={H_kv: 2, D: -1})
|
|
81
|
+
v = storch.contract(x_kv, (w_v, [In, Out]), over=E & In).split(on=Out, to={H_kv: 2, D: -1})
|
|
82
|
+
|
|
83
|
+
# 3. GQA scoring without repeat_interleave, 3D bias broadcast to 5D, outer-product mask, and ordered exit
|
|
84
|
+
bias = storch.bind(bias_raw, B, L, S)
|
|
85
|
+
scores = storch.contract(q, k, over=D) / math.sqrt(q.shape[D]) + bias
|
|
86
|
+
causal = storch.bind(torch.arange(x.shape[L]), L) >= storch.bind(torch.arange(x_kv.shape[S]), S)
|
|
87
|
+
attn = storch.where(causal, scores, -math.inf).apply(F.softmax, on=S)
|
|
88
|
+
out = storch.contract(attn, v, over=S).merge(by=(H_kv, G, D), to=E).tensor(B, L, E)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
## Requirements and Installation
|
|
93
|
+
- Python `>=3.12`
|
|
94
|
+
- `torch>=2.15`
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
pip install simpler-torch
|
|
98
|
+
# or
|
|
99
|
+
uv add simpler-torch
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
## Documentation
|
|
104
|
+
- [Tutorial](docs/en/tutorial.md): Complete guide covering `Axis` / `Axes`, the four-keyword syntax (`over` / `on` / `by` / `to`), `[]` per-axis transforms, aligned broadcasting, contraction and structural ops, `apply` / `via` ecosystem bridges, an end-to-end example, and a public API quick reference.
|
|
105
|
+
- [Compilation, Autograd, and Caveats](docs/en/compile-and-caveats.md): Best practices for `torch.compile(fullgraph=True, dynamic=True)`, autograd and performance trade-offs, API constraints, and common pitfalls.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
simpler_torch/__init__.py,sha256=g586I-70t8i6WirpBk5RzyI6jaNd822xVn3f71zjcic,329
|
|
2
|
+
simpler_torch/axis.py,sha256=RmfZaIX9gU_0-yHA-OjHDuLobpmbyO6wczYxHOvVX_0,5843
|
|
3
|
+
simpler_torch/ops.py,sha256=7l8iQQM0Zhhy1QA_GWqQLeyzTP06VGdfx8QtWjs-t6M,7179
|
|
4
|
+
simpler_torch/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
simpler_torch/tensor.py,sha256=wphtVr9yP5O_HHw2tnl97FG65qDDkBK9z76C4qH9It0,20954
|
|
6
|
+
simpler_torch-0.1.0.dist-info/licenses/LICENSE,sha256=oaphPoMrTB9vRA2OKqHlk2tCz0htYBR_BqqOtcWpKTU,1067
|
|
7
|
+
simpler_torch-0.1.0.dist-info/WHEEL,sha256=G_-rrEibZr7OEM7zdH1dSO6s-VdjfnS5PA4CLAdI9Vw,80
|
|
8
|
+
simpler_torch-0.1.0.dist-info/METADATA,sha256=x-79emy_MWFK9F1xRJLR3ueLWLdgPoNv3Vws08cB0DE,6329
|
|
9
|
+
simpler_torch-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 light-cyan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|