torch-einops-kit 0.1.8__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.
@@ -0,0 +1,300 @@
1
+ from __future__ import annotations
2
+
3
+ from torch import Tensor
4
+ from torch_einops_kit import exists
5
+ import torch
6
+
7
+ def shape_with_replace(t: Tensor, replace_dict: dict[int, int] | None = None) -> torch.Size:
8
+ """Return the shape of a tensor with selected dimension sizes replaced by new values.
9
+
10
+ You can use this function to compute a target shape derived from an existing tensor, substituting
11
+ one or more dimension sizes without modifying the tensor itself. A common use case is
12
+ constructing a zero-padding tensor whose shape matches a source tensor except along the time or
13
+ sequence dimension, as in `dreamer4` [1] and `mimic-video` [2].
14
+
15
+ When `replace_dict` is `None` or empty, this function returns `t.shape` unchanged.
16
+
17
+ Parameters
18
+ ----------
19
+ t : Tensor
20
+ The reference tensor whose shape is used as the base.
21
+ replace_dict : dict[int, int] | None = None
22
+ A mapping from dimension index to the replacement size for that dimension. All keys must be
23
+ non-negative integers less than `t.ndim`. Negative dimension indices are not supported; pass
24
+ a non-negative index instead.
25
+
26
+ Returns
27
+ -------
28
+ shape : torch.Size
29
+ The shape of `t` with each dimension listed in `replace_dict` substituted with the
30
+ corresponding value.
31
+
32
+ Raises
33
+ ------
34
+ ValueError
35
+ Raised when any key in `replace_dict` is greater than or equal to `t.ndim`.
36
+
37
+ See Also
38
+ --------
39
+ slice_at_dim : Apply an arbitrary slice to one dimension.
40
+
41
+ Examples
42
+ --------
43
+ From `dreamer4.trainers` [1] and the test suite:
44
+
45
+ ```python
46
+ import torch
47
+ from torch_einops_kit import shape_with_replace
48
+
49
+ t = torch.randn(3, 4, 5)
50
+
51
+ # Replace the size of dimension 1 with 2
52
+ assert shape_with_replace(t, {1: 2}) == (3, 2, 5)
53
+
54
+ # Build a zero-padding tensor matching a video tensor's shape
55
+ # except along the time dimension (dim 2) — from dreamer4.trainers
56
+ pad_shape = shape_with_replace(generated_video, {2: real_len - gen_len})
57
+ padding = generated_video.new_zeros(pad_shape)
58
+ generated_video = torch.cat((generated_video, padding), dim=2)
59
+
60
+ # Allocate future-frame noise with the latent shape — from mimic-video
61
+ pred_shape = shape_with_replace(latents, {2: predict_num_future_latents})
62
+ future_noise = torch.randn(pred_shape, device=latents.device)
63
+ ```
64
+
65
+ References
66
+ ----------
67
+ [1] dreamer4.trainers.BehaviorCloneTrainer
68
+ https://github.com/lucidrains/dreamer4
69
+ [2] mimic_video.cosmos_predict.CosmosPredictWrapper
70
+ https://github.com/lucidrains/mimic-video
71
+ [3] torch_einops_kit.exists
72
+
73
+ """
74
+ shape: torch.Size = t.shape
75
+
76
+ if not exists(replace_dict):
77
+ return shape
78
+
79
+ shape_list: list[int] = list(shape)
80
+
81
+ for index, value in replace_dict.items():
82
+ if index >= len(shape_list):
83
+ message: str = f'I received `{index = }`, but I need `index` to be less than `{len(shape_list) = }`.'
84
+ raise ValueError(message)
85
+ shape_list[index] = value
86
+
87
+ return torch.Size(shape_list)
88
+
89
+ def slice_at_dim(t: Tensor, slc: slice, dim: int = -1) -> Tensor:
90
+ """Apply a slice to a single dimension of a tensor while preserving all other dimensions.
91
+
92
+ You can use this function to extract a contiguous or strided sub-range along one axis without
93
+ affecting any other axis. The function normalizes negative `dim` values before constructing the
94
+ full index tuple, so both positive and negative dimension indices produce the same result.
95
+
96
+ Parameters
97
+ ----------
98
+ t : Tensor
99
+ The input tensor to slice.
100
+ slc : slice
101
+ The slice object describing the range to extract along `dim`. Any valid Python `slice` is
102
+ accepted, including open-ended slices such as `slice(None, length)` or `slice(-length,
103
+ None)`.
104
+ dim : int = -1
105
+ The dimension along which to apply `slc`. Negative values are converted to their positive
106
+ equivalents before indexing.
107
+
108
+ Returns
109
+ -------
110
+ sliced : Tensor
111
+ A tensor with the same number of dimensions as `t`, where the size of `dim` equals the length
112
+ selected by `slc` and all other dimensions are unchanged.
113
+
114
+ See Also
115
+ --------
116
+ slice_left_at_dim : Select a prefix of a given length along one dimension.
117
+ slice_right_at_dim : Select a suffix of a given length along one dimension.
118
+
119
+ Examples
120
+ --------
121
+ From the test suite and external usage in `alphafold3_pytorch` [1] and `rotary_embedding_torch`
122
+ [2]:
123
+
124
+ ```python
125
+ import torch
126
+ from torch_einops_kit import slice_at_dim
127
+
128
+ t = torch.randn(3, 4, 5)
129
+
130
+ # Slice the last dimension (default dim=-1)
131
+ res = slice_at_dim(t, slice(1, 3))
132
+ assert res.shape == (3, 4, 2)
133
+
134
+ # Slice the first two elements of dimension 1
135
+ res = slice_at_dim(t, slice(None, 2), dim=1)
136
+ assert res.shape == (3, 2, 5)
137
+
138
+ # Slice from position 2 onward along dim -2
139
+ res = slice_at_dim(t, slice(2, None), dim=-2)
140
+ assert res.shape == (3, 2, 5)
141
+
142
+ # Trim positional frequencies to match a query length (rotary embeddings)
143
+ freqs = slice_at_dim(freqs, slice(-seq_len, None), dim=freqs_seq_dim)
144
+
145
+ # Shift-and-concatenate for windowed attention (alphafold3)
146
+ left = slice_at_dim(t, slice(None, -1), dim=dim_seq)
147
+ right = slice_at_dim(t, slice(1, None), dim=dim_seq)
148
+ ```
149
+
150
+ References
151
+ ----------
152
+ [1] alphafold3_pytorch.attention.slice_at_dim
153
+ https://github.com/lucidrains/alphafold3-pytorch
154
+ [2] rotary_embedding_torch.rotary_embedding_torch.slice_at_dim
155
+ https://github.com/lucidrains/rotary-embedding-torch
156
+ """
157
+ dims: int = t.ndim
158
+ dim = (dim + dims) if dim < 0 else dim
159
+
160
+ full_slice: list[slice] = [slice(None)] * dims
161
+ full_slice[dim] = slc
162
+
163
+ return t[tuple(full_slice)]
164
+
165
+ def slice_left_at_dim(t: Tensor, length: int, dim: int = -1) -> Tensor:
166
+ """Select a prefix of a given length from one dimension of a tensor.
167
+
168
+ You can use this function to keep only the first `length` elements along `dim`, discarding the
169
+ remainder. When `length` is zero, the function returns an empty tensor with size zero along `dim`
170
+ rather than the full tensor.
171
+
172
+ Parameters
173
+ ----------
174
+ t : Tensor
175
+ The input tensor to slice.
176
+ length : int
177
+ The number of elements to retain from the start of `dim`. When `length` is zero, the returned
178
+ tensor has size zero along `dim`.
179
+ dim : int = -1
180
+ The dimension along which to take the prefix.
181
+
182
+ Returns
183
+ -------
184
+ sliced : Tensor
185
+ A tensor whose size along `dim` is `min(length, t.shape[dim])`, with all other dimensions
186
+ unchanged.
187
+
188
+ See Also
189
+ --------
190
+ slice_at_dim : Apply an arbitrary slice to one dimension.
191
+ slice_right_at_dim : Select a suffix of a given length along one dimension.
192
+
193
+ Examples
194
+ --------
195
+ From the test suite:
196
+
197
+ ```python
198
+ import torch
199
+ from torch_einops_kit import slice_left_at_dim
200
+
201
+ t = torch.randn(3, 4, 5)
202
+
203
+ res = slice_left_at_dim(t, 2, dim=1)
204
+ assert res.shape == (3, 2, 5)
205
+ ```
206
+
207
+ References
208
+ ----------
209
+ [1] torch_einops_kit.slice_at_dim
210
+
211
+ """
212
+ if length == 0:
213
+ return slice_at_dim(t, slice(0, 0), dim=dim)
214
+
215
+ return slice_at_dim(t, slice(None, length), dim=dim)
216
+
217
+ def slice_right_at_dim(t: Tensor, length: int, dim: int = -1) -> Tensor:
218
+ """Select a suffix of a given length from one dimension of a tensor.
219
+
220
+ You can use this function to keep only the last `length` elements along `dim`, discarding the
221
+ earlier elements. A common use case is aligning positional frequency tensors to a shorter query
222
+ length during inference, as in `PoPE` [1]. When `length` is zero, the function returns an empty
223
+ tensor with size zero along `dim` rather than the full tensor.
224
+
225
+ Parameters
226
+ ----------
227
+ t : Tensor
228
+ The input tensor to slice.
229
+ length : int
230
+ The number of elements to retain from the end of `dim`. When `length` is zero, the returned
231
+ tensor has size zero along `dim`.
232
+ dim : int = -1
233
+ The dimension along which to take the suffix.
234
+
235
+ Returns
236
+ -------
237
+ sliced : Tensor
238
+ A tensor whose size along `dim` is `min(length, t.shape[dim])`, with all other dimensions
239
+ unchanged.
240
+
241
+ See Also
242
+ --------
243
+ slice_at_dim : Apply an arbitrary slice to one dimension.
244
+ slice_left_at_dim : Select a prefix of a given length along one dimension.
245
+
246
+ Examples
247
+ --------
248
+ From the test suite and `PoPE_pytorch` [1]:
249
+
250
+ ```python
251
+ import torch
252
+ from torch_einops_kit import slice_right_at_dim
253
+
254
+ t = torch.randn(3, 4, 5)
255
+
256
+ # Keep the last two elements of dimension 1
257
+ res = slice_right_at_dim(t, 2, dim=1)
258
+ assert res.shape == (3, 2, 5)
259
+
260
+ # Trim precomputed positional frequencies to the query length (PoPE)
261
+ freqs = slice_right_at_dim(freqs, q_len, dim=-2)
262
+ ```
263
+
264
+ References
265
+ ----------
266
+ [1] PoPE_pytorch.pope.apply_pope_to_qk
267
+ https://github.com/lucidrains/PoPE-pytorch
268
+ [2] torch_einops_kit.slice_at_dim
269
+
270
+ """
271
+ if length == 0:
272
+ return slice_at_dim(t, slice(0, 0), dim=dim)
273
+
274
+ return slice_at_dim(t, slice(-length, None), dim=dim)
275
+
276
+ """
277
+ Some or all of the logic in this module may be protected by the following.
278
+
279
+ MIT License
280
+
281
+ Copyright (c) 2026 Phil Wang
282
+
283
+ Permission is hereby granted, free of charge, to any person obtaining a copy
284
+ of this software and associated documentation files (the "Software"), to deal
285
+ in the Software without restriction, including without limitation the rights
286
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
287
+ copies of the Software, and to permit persons to whom the Software is
288
+ furnished to do so, subject to the following conditions:
289
+
290
+ The above copyright notice and this permission notice shall be included in all
291
+ copies or substantial portions of the Software.
292
+
293
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
294
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
295
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
296
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
297
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
298
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
299
+ SOFTWARE.
300
+ """