torch-einops-kit 0.1.5__tar.gz → 0.1.6__tar.gz

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.
Files changed (21) hide show
  1. torch_einops_kit-0.1.6/LICENSE +407 -0
  2. torch_einops_kit-0.1.6/LICENSE-WANG +23 -0
  3. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/PKG-INFO +10 -8
  4. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/README.md +5 -5
  5. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/pyproject.toml +9 -9
  6. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/__init__.py +5 -6
  7. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/_cat_and_stack.py +3 -0
  8. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/_dimensions.py +1 -1
  9. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/_masking.py +4 -4
  10. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/_padding.py +8 -8
  11. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/_theTypes.py +78 -27
  12. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/device.py +1 -1
  13. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/einops.py +64 -42
  14. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/save_load.py +4 -12
  15. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/scaleValues.py +1 -1
  16. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/utils.py +1 -1
  17. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/_helpers.py +0 -0
  18. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/_semiotics.py +0 -0
  19. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/_slicing.py +0 -0
  20. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/nn.py +0 -0
  21. {torch_einops_kit-0.1.5 → torch_einops_kit-0.1.6}/src/torch_einops_kit/py.typed +0 -0
@@ -0,0 +1,407 @@
1
+ Attribution-NonCommercial 4.0 International
2
+
3
+ =======================================================================
4
+
5
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
6
+ does not provide legal services or legal advice. Distribution of
7
+ Creative Commons public licenses does not create a lawyer-client or
8
+ other relationship. Creative Commons makes its licenses and related
9
+ information available on an "as-is" basis. Creative Commons gives no
10
+ warranties regarding its licenses, any material licensed under their
11
+ terms and conditions, or any related information. Creative Commons
12
+ disclaims all liability for damages resulting from their use to the
13
+ fullest extent possible.
14
+
15
+ Using Creative Commons Public Licenses
16
+
17
+ Creative Commons public licenses provide a standard set of terms and
18
+ conditions that creators and other rights holders may use to share
19
+ original works of authorship and other material subject to copyright
20
+ and certain other rights specified in the public license below. The
21
+ following considerations are for informational purposes only, are not
22
+ exhaustive, and do not form part of our licenses.
23
+
24
+ Considerations for licensors: Our public licenses are
25
+ intended for use by those authorized to give the public
26
+ permission to use material in ways otherwise restricted by
27
+ copyright and certain other rights. Our licenses are
28
+ irrevocable. Licensors should read and understand the terms
29
+ and conditions of the license they choose before applying it.
30
+ Licensors should also secure all rights necessary before
31
+ applying our licenses so that the public can reuse the
32
+ material as expected. Licensors should clearly mark any
33
+ material not subject to the license. This includes other CC-
34
+ licensed material, or material used under an exception or
35
+ limitation to copyright. More considerations for licensors:
36
+ wiki.creativecommons.org/Considerations_for_licensors
37
+
38
+ Considerations for the public: By using one of our public
39
+ licenses, a licensor grants the public permission to use the
40
+ licensed material under specified terms and conditions. If
41
+ the licensor's permission is not necessary for any reason--for
42
+ example, because of any applicable exception or limitation to
43
+ copyright--then that use is not regulated by the license. Our
44
+ licenses grant only permissions under copyright and certain
45
+ other rights that a licensor has authority to grant. Use of
46
+ the licensed material may still be restricted for other
47
+ reasons, including because others have copyright or other
48
+ rights in the material. A licensor may make special requests,
49
+ such as asking that all changes be marked or described.
50
+ Although not required by our licenses, you are encouraged to
51
+ respect those requests where reasonable. More considerations
52
+ for the public:
53
+ wiki.creativecommons.org/Considerations_for_licensees
54
+
55
+ =======================================================================
56
+
57
+ Creative Commons Attribution-NonCommercial 4.0 International Public
58
+ License
59
+
60
+ By exercising the Licensed Rights (defined below), You accept and agree
61
+ to be bound by the terms and conditions of this Creative Commons
62
+ Attribution-NonCommercial 4.0 International Public License ("Public
63
+ License"). To the extent this Public License may be interpreted as a
64
+ contract, You are granted the Licensed Rights in consideration of Your
65
+ acceptance of these terms and conditions, and the Licensor grants You
66
+ such rights in consideration of benefits the Licensor receives from
67
+ making the Licensed Material available under these terms and
68
+ conditions.
69
+
70
+
71
+ Section 1 -- Definitions.
72
+
73
+ a. Adapted Material means material subject to Copyright and Similar
74
+ Rights that is derived from or based upon the Licensed Material
75
+ and in which the Licensed Material is translated, altered,
76
+ arranged, transformed, or otherwise modified in a manner requiring
77
+ permission under the Copyright and Similar Rights held by the
78
+ Licensor. For purposes of this Public License, where the Licensed
79
+ Material is a musical work, performance, or sound recording,
80
+ Adapted Material is always produced where the Licensed Material is
81
+ synched in timed relation with a moving image.
82
+
83
+ b. Adapter's License means the license You apply to Your Copyright
84
+ and Similar Rights in Your contributions to Adapted Material in
85
+ accordance with the terms and conditions of this Public License.
86
+
87
+ c. Copyright and Similar Rights means copyright and/or similar rights
88
+ closely related to copyright including, without limitation,
89
+ performance, broadcast, sound recording, and Sui Generis Database
90
+ Rights, without regard to how the rights are labeled or
91
+ categorized. For purposes of this Public License, the rights
92
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
93
+ Rights.
94
+ d. Effective Technological Measures means those measures that, in the
95
+ absence of proper authority, may not be circumvented under laws
96
+ fulfilling obligations under Article 11 of the WIPO Copyright
97
+ Treaty adopted on December 20, 1996, and/or similar international
98
+ agreements.
99
+
100
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
101
+ any other exception or limitation to Copyright and Similar Rights
102
+ that applies to Your use of the Licensed Material.
103
+
104
+ f. Licensed Material means the artistic or literary work, database,
105
+ or other material to which the Licensor applied this Public
106
+ License.
107
+
108
+ g. Licensed Rights means the rights granted to You subject to the
109
+ terms and conditions of this Public License, which are limited to
110
+ all Copyright and Similar Rights that apply to Your use of the
111
+ Licensed Material and that the Licensor has authority to license.
112
+
113
+ h. Licensor means the individual(s) or entity(ies) granting rights
114
+ under this Public License.
115
+
116
+ i. NonCommercial means not primarily intended for or directed towards
117
+ commercial advantage or monetary compensation. For purposes of
118
+ this Public License, the exchange of the Licensed Material for
119
+ other material subject to Copyright and Similar Rights by digital
120
+ file-sharing or similar means is NonCommercial provided there is
121
+ no payment of monetary compensation in connection with the
122
+ exchange.
123
+
124
+ j. Share means to provide material to the public by any means or
125
+ process that requires permission under the Licensed Rights, such
126
+ as reproduction, public display, public performance, distribution,
127
+ dissemination, communication, or importation, and to make material
128
+ available to the public including in ways that members of the
129
+ public may access the material from a place and at a time
130
+ individually chosen by them.
131
+
132
+ k. Sui Generis Database Rights means rights other than copyright
133
+ resulting from Directive 96/9/EC of the European Parliament and of
134
+ the Council of 11 March 1996 on the legal protection of databases,
135
+ as amended and/or succeeded, as well as other essentially
136
+ equivalent rights anywhere in the world.
137
+
138
+ l. You means the individual or entity exercising the Licensed Rights
139
+ under this Public License. Your has a corresponding meaning.
140
+
141
+
142
+ Section 2 -- Scope.
143
+
144
+ a. License grant.
145
+
146
+ 1. Subject to the terms and conditions of this Public License,
147
+ the Licensor hereby grants You a worldwide, royalty-free,
148
+ non-sublicensable, non-exclusive, irrevocable license to
149
+ exercise the Licensed Rights in the Licensed Material to:
150
+
151
+ a. reproduce and Share the Licensed Material, in whole or
152
+ in part, for NonCommercial purposes only; and
153
+
154
+ b. produce, reproduce, and Share Adapted Material for
155
+ NonCommercial purposes only.
156
+
157
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
158
+ Exceptions and Limitations apply to Your use, this Public
159
+ License does not apply, and You do not need to comply with
160
+ its terms and conditions.
161
+
162
+ 3. Term. The term of this Public License is specified in Section
163
+ 6(a).
164
+
165
+ 4. Media and formats; technical modifications allowed. The
166
+ Licensor authorizes You to exercise the Licensed Rights in
167
+ all media and formats whether now known or hereafter created,
168
+ and to make technical modifications necessary to do so. The
169
+ Licensor waives and/or agrees not to assert any right or
170
+ authority to forbid You from making technical modifications
171
+ necessary to exercise the Licensed Rights, including
172
+ technical modifications necessary to circumvent Effective
173
+ Technological Measures. For purposes of this Public License,
174
+ simply making modifications authorized by this Section 2(a)
175
+ (4) never produces Adapted Material.
176
+
177
+ 5. Downstream recipients.
178
+
179
+ a. Offer from the Licensor -- Licensed Material. Every
180
+ recipient of the Licensed Material automatically
181
+ receives an offer from the Licensor to exercise the
182
+ Licensed Rights under the terms and conditions of this
183
+ Public License.
184
+
185
+ b. No downstream restrictions. You may not offer or impose
186
+ any additional or different terms or conditions on, or
187
+ apply any Effective Technological Measures to, the
188
+ Licensed Material if doing so restricts exercise of the
189
+ Licensed Rights by any recipient of the Licensed
190
+ Material.
191
+
192
+ 6. No endorsement. Nothing in this Public License constitutes or
193
+ may be construed as permission to assert or imply that You
194
+ are, or that Your use of the Licensed Material is, connected
195
+ with, or sponsored, endorsed, or granted official status by,
196
+ the Licensor or others designated to receive attribution as
197
+ provided in Section 3(a)(1)(A)(i).
198
+
199
+ b. Other rights.
200
+
201
+ 1. Moral rights, such as the right of integrity, are not
202
+ licensed under this Public License, nor are publicity,
203
+ privacy, and/or other similar personality rights; however, to
204
+ the extent possible, the Licensor waives and/or agrees not to
205
+ assert any such rights held by the Licensor to the limited
206
+ extent necessary to allow You to exercise the Licensed
207
+ Rights, but not otherwise.
208
+
209
+ 2. Patent and trademark rights are not licensed under this
210
+ Public License.
211
+
212
+ 3. To the extent possible, the Licensor waives any right to
213
+ collect royalties from You for the exercise of the Licensed
214
+ Rights, whether directly or through a collecting society
215
+ under any voluntary or waivable statutory or compulsory
216
+ licensing scheme. In all other cases the Licensor expressly
217
+ reserves any right to collect such royalties, including when
218
+ the Licensed Material is used other than for NonCommercial
219
+ purposes.
220
+
221
+
222
+ Section 3 -- License Conditions.
223
+
224
+ Your exercise of the Licensed Rights is expressly made subject to the
225
+ following conditions.
226
+
227
+ a. Attribution.
228
+
229
+ 1. If You Share the Licensed Material (including in modified
230
+ form), You must:
231
+
232
+ a. retain the following if it is supplied by the Licensor
233
+ with the Licensed Material:
234
+
235
+ i. identification of the creator(s) of the Licensed
236
+ Material and any others designated to receive
237
+ attribution, in any reasonable manner requested by
238
+ the Licensor (including by pseudonym if
239
+ designated);
240
+
241
+ ii. a copyright notice;
242
+
243
+ iii. a notice that refers to this Public License;
244
+
245
+ iv. a notice that refers to the disclaimer of
246
+ warranties;
247
+
248
+ v. a URI or hyperlink to the Licensed Material to the
249
+ extent reasonably practicable;
250
+
251
+ b. indicate if You modified the Licensed Material and
252
+ retain an indication of any previous modifications; and
253
+
254
+ c. indicate the Licensed Material is licensed under this
255
+ Public License, and include the text of, or the URI or
256
+ hyperlink to, this Public License.
257
+
258
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
259
+ reasonable manner based on the medium, means, and context in
260
+ which You Share the Licensed Material. For example, it may be
261
+ reasonable to satisfy the conditions by providing a URI or
262
+ hyperlink to a resource that includes the required
263
+ information.
264
+
265
+ 3. If requested by the Licensor, You must remove any of the
266
+ information required by Section 3(a)(1)(A) to the extent
267
+ reasonably practicable.
268
+
269
+ 4. If You Share Adapted Material You produce, the Adapter's
270
+ License You apply must not prevent recipients of the Adapted
271
+ Material from complying with this Public License.
272
+
273
+
274
+ Section 4 -- Sui Generis Database Rights.
275
+
276
+ Where the Licensed Rights include Sui Generis Database Rights that
277
+ apply to Your use of the Licensed Material:
278
+
279
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
280
+ to extract, reuse, reproduce, and Share all or a substantial
281
+ portion of the contents of the database for NonCommercial purposes
282
+ only;
283
+
284
+ b. if You include all or a substantial portion of the database
285
+ contents in a database in which You have Sui Generis Database
286
+ Rights, then the database in which You have Sui Generis Database
287
+ Rights (but not its individual contents) is Adapted Material; and
288
+
289
+ c. You must comply with the conditions in Section 3(a) if You Share
290
+ all or a substantial portion of the contents of the database.
291
+
292
+ For the avoidance of doubt, this Section 4 supplements and does not
293
+ replace Your obligations under this Public License where the Licensed
294
+ Rights include other Copyright and Similar Rights.
295
+
296
+
297
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
298
+
299
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
300
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
301
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
302
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
303
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
304
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
305
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
306
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
307
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
308
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
309
+
310
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
311
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
312
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
313
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
314
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
315
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
316
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
317
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
318
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
319
+
320
+ c. The disclaimer of warranties and limitation of liability provided
321
+ above shall be interpreted in a manner that, to the extent
322
+ possible, most closely approximates an absolute disclaimer and
323
+ waiver of all liability.
324
+
325
+
326
+ Section 6 -- Term and Termination.
327
+
328
+ a. This Public License applies for the term of the Copyright and
329
+ Similar Rights licensed here. However, if You fail to comply with
330
+ this Public License, then Your rights under this Public License
331
+ terminate automatically.
332
+
333
+ b. Where Your right to use the Licensed Material has terminated under
334
+ Section 6(a), it reinstates:
335
+
336
+ 1. automatically as of the date the violation is cured, provided
337
+ it is cured within 30 days of Your discovery of the
338
+ violation; or
339
+
340
+ 2. upon express reinstatement by the Licensor.
341
+
342
+ For the avoidance of doubt, this Section 6(b) does not affect any
343
+ right the Licensor may have to seek remedies for Your violations
344
+ of this Public License.
345
+
346
+ c. For the avoidance of doubt, the Licensor may also offer the
347
+ Licensed Material under separate terms or conditions or stop
348
+ distributing the Licensed Material at any time; however, doing so
349
+ will not terminate this Public License.
350
+
351
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
352
+ License.
353
+
354
+
355
+ Section 7 -- Other Terms and Conditions.
356
+
357
+ a. The Licensor shall not be bound by any additional or different
358
+ terms or conditions communicated by You unless expressly agreed.
359
+
360
+ b. Any arrangements, understandings, or agreements regarding the
361
+ Licensed Material not stated herein are separate from and
362
+ independent of the terms and conditions of this Public License.
363
+
364
+
365
+ Section 8 -- Interpretation.
366
+
367
+ a. For the avoidance of doubt, this Public License does not, and
368
+ shall not be interpreted to, reduce, limit, restrict, or impose
369
+ conditions on any use of the Licensed Material that could lawfully
370
+ be made without permission under this Public License.
371
+
372
+ b. To the extent possible, if any provision of this Public License is
373
+ deemed unenforceable, it shall be automatically reformed to the
374
+ minimum extent necessary to make it enforceable. If the provision
375
+ cannot be reformed, it shall be severed from this Public License
376
+ without affecting the enforceability of the remaining terms and
377
+ conditions.
378
+
379
+ c. No term or condition of this Public License will be waived and no
380
+ failure to comply consented to unless expressly agreed to by the
381
+ Licensor.
382
+
383
+ d. Nothing in this Public License constitutes or may be interpreted
384
+ as a limitation upon, or waiver of, any privileges and immunities
385
+ that apply to the Licensor or You, including from the legal
386
+ processes of any jurisdiction or authority.
387
+
388
+ =======================================================================
389
+
390
+ Creative Commons is not a party to its public
391
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
392
+ its public licenses to material it publishes and in those instances
393
+ will be considered the “Licensor.” The text of the Creative Commons
394
+ public licenses is dedicated to the public domain under the CC0 Public
395
+ Domain Dedication. Except for the limited purpose of indicating that
396
+ material is shared under a Creative Commons public license or as
397
+ otherwise permitted by the Creative Commons policies published at
398
+ creativecommons.org/policies, Creative Commons does not authorize the
399
+ use of the trademark "Creative Commons" or any other trademark or logo
400
+ of Creative Commons without its prior written consent including,
401
+ without limitation, in connection with any unauthorized modifications
402
+ to any of its public licenses or any other arrangements,
403
+ understandings, or agreements concerning use of licensed material. For
404
+ the avoidance of doubt, this paragraph does not form part of the
405
+ public licenses.
406
+
407
+ Creative Commons may be contacted at creativecommons.org.
@@ -0,0 +1,23 @@
1
+ Some of the logic in this package may be protected by the following.
2
+
3
+ MIT License
4
+
5
+ Copyright (c) 2026 Phil Wang
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
@@ -1,11 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: torch-einops-kit
3
- Version: 0.1.5
3
+ Version: 0.1.6
4
4
  Summary: Typed tensor-shaping, masking, padding, device-routing, and checkpoint utilities for PyTorch and `einops`. A superset of `lucidrains/torch-einops-utils` with similar utilities from other lucidrains packages. Adds strict typing, extensive tests, and comprehensive docstrings.
5
5
  Keywords: artificial intelligence,einops,machine learning,pytorch,torch
6
- Author: Phil Wang, Hunter Hogan
7
- Author-email: Phil Wang <lucidrains@gmail.com>, Hunter Hogan <HunterHogan@pm.me>
6
+ Author: Hunter Hogan
7
+ Author-email: Hunter Hogan <HunterHogan@pm.me>
8
8
  License-Expression: CC-BY-NC-4.0
9
+ License-File: LICENSE
10
+ License-File: LICENSE-WANG
9
11
  Classifier: Development Status :: 4 - Beta
10
12
  Classifier: Environment :: Console
11
13
  Classifier: Environment :: GPU :: NVIDIA CUDA
@@ -338,11 +340,11 @@ The `torch_einops_kit.scaleValues` submodule contains exclusive and reverse cumu
338
340
 
339
341
  The `torch_einops_kit.einops` submodule contains pack and unpack utilities with paired inverse functions.
340
342
 
341
- | Name | Contract |
342
- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
343
- | `pack_one(t, pattern)` | Packs one tensor using an einops pattern and returns the packed tensor and shape metadata for paired reconstruction with `unpack_one`. |
344
- | `pack_with_inverse(t, pattern)` | Wraps `einops.pack` and stores the corresponding inverse. Input `t` may be one tensor or a `list[Tensor]`. The inverse returns the matching kind and optionally accepts a different `inv_pattern` for unpacking. |
345
- | `unpack_one(t, ps, pattern)` | Unpacks one tensor using packed-shape metadata produced by `pack_one`. |
343
+ | Name | Contract |
344
+ | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
345
+ | `pack_one(t, pattern)` | Packs one tensor using an einops pattern and returns the packed tensor and shape metadata for paired reconstruction with `unpack_one`. |
346
+ | `pack_with_inverse(t, pattern)` | Wraps `einops.pack` and stores the corresponding inverse. Input `t` may be one tensor or a `list[Tensor]`. When `t` is one tensor, the inverse has type `InversePackTensor` and returns one tensor. When `t` is a `list[Tensor]`, the inverse has type `InversePackListTensors` and returns `list[Tensor]`. The inverse optionally accepts a different `inv_pattern` for unpacking. |
347
+ | `unpack_one(t, ps, pattern)` | Unpacks one tensor using packed-shape metadata produced by `pack_one`. |
346
348
 
347
349
  ## `device` submodule reference
348
350
 
@@ -304,11 +304,11 @@ The `torch_einops_kit.scaleValues` submodule contains exclusive and reverse cumu
304
304
 
305
305
  The `torch_einops_kit.einops` submodule contains pack and unpack utilities with paired inverse functions.
306
306
 
307
- | Name | Contract |
308
- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
309
- | `pack_one(t, pattern)` | Packs one tensor using an einops pattern and returns the packed tensor and shape metadata for paired reconstruction with `unpack_one`. |
310
- | `pack_with_inverse(t, pattern)` | Wraps `einops.pack` and stores the corresponding inverse. Input `t` may be one tensor or a `list[Tensor]`. The inverse returns the matching kind and optionally accepts a different `inv_pattern` for unpacking. |
311
- | `unpack_one(t, ps, pattern)` | Unpacks one tensor using packed-shape metadata produced by `pack_one`. |
307
+ | Name | Contract |
308
+ | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
309
+ | `pack_one(t, pattern)` | Packs one tensor using an einops pattern and returns the packed tensor and shape metadata for paired reconstruction with `unpack_one`. |
310
+ | `pack_with_inverse(t, pattern)` | Wraps `einops.pack` and stores the corresponding inverse. Input `t` may be one tensor or a `list[Tensor]`. When `t` is one tensor, the inverse has type `InversePackTensor` and returns one tensor. When `t` is a `list[Tensor]`, the inverse has type `InversePackListTensors` and returns `list[Tensor]`. The inverse optionally accepts a different `inv_pattern` for unpacking. |
311
+ | `unpack_one(t, ps, pattern)` | Unpacks one tensor using packed-shape metadata produced by `pack_one`. |
312
312
 
313
313
  ## `device` submodule reference
314
314
 
@@ -1,14 +1,12 @@
1
1
  [project]
2
2
  name = "torch-einops-kit"
3
- version = "0.1.5"
3
+ version = "0.1.6"
4
4
  description = "Typed tensor-shaping, masking, padding, device-routing, and checkpoint utilities for PyTorch and `einops`. A superset of `lucidrains/torch-einops-utils` with similar utilities from other lucidrains packages. Adds strict typing, extensive tests, and comprehensive docstrings."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
7
7
  license = "CC-BY-NC-4.0"
8
- authors = [
9
- { name = "Phil Wang", email = "lucidrains@gmail.com" },
10
- { name = "Hunter Hogan", email = "HunterHogan@pm.me" }
11
- ]
8
+ license-files = ["LICEN[CS]E*"]
9
+ authors = [{ name = "Hunter Hogan", email = "HunterHogan@pm.me" }]
12
10
  maintainers = [{ name = "Hunter Hogan", email = "HunterHogan@pm.me" }]
13
11
  keywords = [
14
12
  "artificial intelligence",
@@ -46,11 +44,13 @@ Issues = "https://github.com/hunterhogan/torch_einops_kit/issues"
46
44
  Repository = "https://github.com/hunterhogan/torch_einops_kit.git"
47
45
 
48
46
  [dependency-groups]
47
+ dev = [
48
+ "pytest-cov",
49
+ ]
49
50
  testing = [
50
- "more-itertools>=11.0.2",
51
- "numpy>=2.2.6",
52
- "pytest>=9.0.3",
53
- "pytest-cov>=7.1.0",
51
+ "more-itertools",
52
+ "numpy>=2.0.0",
53
+ "pytest",
54
54
  ]
55
55
 
56
56
  [build-system]
@@ -130,8 +130,9 @@ from torch_einops_kit._semiotics import decreasing as decreasing, zeroIndexed as
130
130
  # isort: split
131
131
  from torch_einops_kit._theTypes import (
132
132
  ConfigArgsKwargs as ConfigArgsKwargs, DehydratedCheckpoint as DehydratedCheckpoint, DehydratedTorchNNModule as DehydratedTorchNNModule,
133
- DimAndValue as DimAndValue, IdentityCallable as IdentityCallable, PSpec as PSpec, RVar as RVar, StrPath as StrPath,
134
- SupportsIntIndex as SupportsIntIndex, T_co as T_co, TorchNNModule as TorchNNModule, TVar as TVar)
133
+ DimAndValue as DimAndValue, IdentityCallable as IdentityCallable, InversePackListTensors as InversePackListTensors,
134
+ InversePackTensor as InversePackTensor, PSpec as PSpec, RVar as RVar, StrPath as StrPath, SupportsIntIndex as SupportsIntIndex,
135
+ T_co as T_co, TorchNNModule as TorchNNModule, TVar as TVar)
135
136
 
136
137
  # isort: split
137
138
  from torch_einops_kit._helpers import (
@@ -149,7 +150,8 @@ from torch_einops_kit._dimensions import (
149
150
  pad_right_ndim as pad_right_ndim, pad_right_ndim_to as pad_right_ndim_to)
150
151
 
151
152
  # isort: split
152
- from torch_einops_kit._cat_and_stack import broadcast_cat as broadcast_cat, safe_cat as safe_cat, safe_stack as safe_stack
153
+ from torch_einops_kit._cat_and_stack import (
154
+ broadcast_cat as broadcast_cat, broadcat as broadcat, safe_cat as safe_cat, safe_stack as safe_stack)
153
155
 
154
156
  # isort: split
155
157
  from torch_einops_kit._padding import (
@@ -170,6 +172,3 @@ from torch_einops_kit.utils import tree_flatten_with_inverse as tree_flatten_wit
170
172
  from torch_einops_kit.einops import pack_with_inverse # pyright: ignore[reportUnusedImport]
171
173
  from torch_einops_kit.nn import Identity, Lambda, Sequential # pyright: ignore[reportUnusedImport]
172
174
  from torch_einops_kit.scaleValues import exclusive_cumsum, l2norm, masked_mean, reverse_cumsum # pyright: ignore[reportUnusedImport]
173
-
174
- # NOTE `broadcat` is the identifier used in lucidrains packages.
175
- broadcat = broadcast_cat
@@ -33,6 +33,9 @@ def broadcast_cat(tensors: Sequence[Tensor], dim: int = -1) -> Tensor:
33
33
  """
34
34
  return cat(cast('list[Tensor]', broadcast_tensors(*tensors)), dim)
35
35
 
36
+ # NOTE `broadcat` is the identifier used in lucidrains packages.
37
+ broadcat = broadcast_cat
38
+
36
39
  @safe
37
40
  def safe_cat(tensors: tuple[Tensor, ...] | list[Tensor], dim: int = 0) -> Tensor | None:
38
41
  """Concatenate tensors from `tensors` along an existing dimension, skipping `None` values.
@@ -126,7 +126,7 @@ def align_dims_left(tensors: Sequence[Tensor], *, ndim: int | None = None) -> tu
126
126
  https://context7.com/arogozhnikov/einops
127
127
  """
128
128
  if not exists(ndim):
129
- ndim = max([t.ndim for t in tensors])
129
+ ndim = max(t.ndim for t in tensors)
130
130
 
131
131
  return tuple(pad_right_ndim(t, ndim - t.ndim) for t in tensors)
132
132
 
@@ -167,8 +167,8 @@ def mask_after(t: Tensor, value: Tensor | Number, dim: int = -1, *, inclusive: b
167
167
  """
168
168
  mask: Tensor = t == value
169
169
  if inclusive:
170
- mask = shift_right(mask, amount = 1, dim = dim, pad_value = False)
171
- return mask.float().cumsum(dim = dim) == 0.
170
+ mask = shift_right(mask, amount=1, dim=dim, pad_value=False)
171
+ return mask.int().cumsum(dim=dim) == 0
172
172
 
173
173
  def mask_before(t: Tensor, value: Tensor | Number, dim: int = -1, *, inclusive: bool = True) -> Tensor:
174
174
  """Compute a boolean mask over `t` that stays `True` from the last `value` onward along `dim`.
@@ -220,8 +220,8 @@ def mask_before(t: Tensor, value: Tensor | Number, dim: int = -1, *, inclusive:
220
220
  """
221
221
  mask: Tensor = t == value
222
222
  if inclusive:
223
- mask = shift_left(mask, amount = 1, dim = dim, pad_value = False)
224
- return reverse_cumsum(mask.float(), dim = dim) == 0.
223
+ mask = shift_left(mask, amount=1, dim=dim, pad_value=False)
224
+ return reverse_cumsum(mask.int(), dim=dim) == 0
225
225
 
226
226
  def or_masks(masks: Sequence[Tensor | None]) -> Tensor | None:
227
227
  """Reduce a sequence of boolean mask `Tensor` values to a single mask using element-wise logical OR.
@@ -454,12 +454,12 @@ def pad_sequence(
454
454
  return output
455
455
 
456
456
  @overload
457
- def pad_sequence_and_cat(tensors: Sequence[Tensor], *, dim_cat: int = 0, dim: int = -1, value: float = 0., left: bool = False) -> Tensor:...
457
+ def pad_sequence_and_cat(tensors: Sequence[Tensor], *, dim_cat: int = 0, dim: int = -1, value: float = 0., left: bool = False) -> Tensor: ...
458
458
  @overload
459
- def pad_sequence_and_cat(tensors: list[Tensor] = [], *, dim_cat: int = 0, dim: int = -1, value: float = 0., left: bool = False) -> None:... # noqa: B006
459
+ def pad_sequence_and_cat(tensors: list[Tensor] = [], *, dim_cat: int = 0, dim: int = -1, value: float = 0., left: bool = False) -> None: ... # noqa: B006
460
460
  @overload
461
- def pad_sequence_and_cat(tensors: tuple[()]=(), *, dim_cat: int = 0, dim: int = -1, value: float = 0., left: bool = False) -> None:...
462
- def pad_sequence_and_cat(tensors: Sequence[Tensor]=(), *, dim_cat: int = 0, dim: int = -1, value: float = 0., left: bool = False) -> Tensor | None:
461
+ def pad_sequence_and_cat(tensors: tuple[()] = (), *, dim_cat: int = 0, dim: int = -1, value: float = 0., left: bool = False) -> None: ...
462
+ def pad_sequence_and_cat(tensors: Sequence[Tensor] = (), *, dim_cat: int = 0, dim: int = -1, value: float = 0., left: bool = False) -> Tensor | None:
463
463
  """Pad `tensors` to a shared length along `dim` and concatenate along `dim_cat`.
464
464
 
465
465
  You can use `pad_sequence_and_cat` to align and merge a heterogeneous-length sequence of `Tensor`
@@ -514,7 +514,7 @@ def pad_sequence_and_cat(tensors: Sequence[Tensor]=(), *, dim_cat: int = 0, dim:
514
514
  [3] tests/test_utils.py
515
515
  """
516
516
  padded: Tensor | list[Tensor] | None = pad_sequence(tensors, dim=dim, value=value, left=left, return_stacked=False, return_lens=False)
517
- if padded is not None: # pyright: ignore[reportUnnecessaryComparison]
517
+ if padded is not None: # pyright: ignore[reportUnnecessaryComparison]
518
518
  return cat(padded, dim=dim_cat)
519
519
  return padded
520
520
 
@@ -554,7 +554,7 @@ def shift(t: Tensor, amount: int = 1, dim: int = -1, pad_value: float = 0.) -> T
554
554
  ----------
555
555
  [1] torch_einops_kit.pad_at_dim
556
556
  """
557
- return pad_at_dim(t, (amount, -amount), dim = dim, value = pad_value)
557
+ return pad_at_dim(t, (amount, -amount), dim=dim, value=pad_value)
558
558
 
559
559
  def shift_left(t: Tensor, amount: int = 1, dim: int = -1, pad_value: float = 0.) -> Tensor:
560
560
  """Shift values in `t` toward smaller indices along `dim`.
@@ -589,7 +589,7 @@ def shift_left(t: Tensor, amount: int = 1, dim: int = -1, pad_value: float = 0.)
589
589
  ----------
590
590
  [1] torch_einops_kit.shift
591
591
  """
592
- return shift(t, -amount, dim = dim, pad_value = pad_value)
592
+ return shift(t, -amount, dim=dim, pad_value=pad_value)
593
593
 
594
594
  def shift_right(t: Tensor, amount: int = 1, dim: int = -1, pad_value: float = 0.) -> Tensor:
595
595
  """Shift values in `t` toward larger indices along `dim`.
@@ -624,7 +624,7 @@ def shift_right(t: Tensor, amount: int = 1, dim: int = -1, pad_value: float = 0.
624
624
  ----------
625
625
  [1] torch_einops_kit.shift
626
626
  """
627
- return shift(t, amount, dim = dim, pad_value = pad_value)
627
+ return shift(t, amount, dim=dim, pad_value=pad_value)
628
628
 
629
629
  """
630
630
  Some of the logic in this module may be protected by the following.
@@ -1,8 +1,9 @@
1
+ # ruff: noqa: E224
1
2
  from __future__ import annotations
2
3
 
3
4
  from os import PathLike
4
5
  from torch.nn import Module
5
- from typing import Any, Literal, ParamSpec, Protocol, TYPE_CHECKING, TypeAlias, TypedDict, TypeVar
6
+ from typing import Any, Literal, overload, ParamSpec, Protocol, TYPE_CHECKING, TypeAlias, TypedDict, TypeVar
6
7
 
7
8
  if TYPE_CHECKING:
8
9
  from torch import Tensor
@@ -332,6 +333,82 @@ class IdentityCallable(Protocol):
332
333
  """
333
334
  def __call__(self, value: TVar, /, *args: object, **kwargs: object) -> TVar: ...
334
335
 
336
+ class InversePackListTensors(Protocol):
337
+ """Annotate the inverse callable returned by `pack_with_inverse` for `list[Tensor]` input.
338
+
339
+ You can use `InversePackListTensors` as a `Protocol` [1] for the inverse callable paired with
340
+ `pack_with_inverse` [2] when `t` is a `list[Tensor]`. The callable accepts a packed or
341
+ transformed `Tensor` `out`, optionally accepts an override unpacking pattern `inv_pattern`, and
342
+ returns a `list[Tensor]` whose item count and per-item shape match the original pack step.
343
+
344
+ Call Signatures
345
+ ---------------
346
+ default pattern : callable
347
+ `inverse(out)` reuses the original `pattern` captured by `pack_with_inverse` [2].
348
+ override pattern : callable
349
+ `inverse(out, inv_pattern)` forwards `inv_pattern` to `einops.unpack` [3] instead of reusing
350
+ the original `pattern`. The `inv_pattern` must stay compatible with the packed-shape metadata
351
+ captured during packing.
352
+
353
+ See Also
354
+ --------
355
+ InversePackTensor : Annotate the inverse callable returned by `pack_with_inverse` for one
356
+ `Tensor` input.
357
+ torch_einops_kit.einops.pack_with_inverse : Build an `InversePackListTensors` callable for
358
+ `list[Tensor]` input.
359
+
360
+ References
361
+ ----------
362
+ [1] Protocol - Python typing documentation
363
+ https://docs.python.org/3/library/typing.html#typing.Protocol
364
+ [2] torch_einops_kit.einops.pack_with_inverse
365
+
366
+ [3] einops pack/unpack API
367
+ https://einops.rocks/api/pack_unpack/
368
+ """
369
+ @overload
370
+ def __call__(self, out: Tensor) -> list[Tensor]: ...
371
+ @overload
372
+ def __call__(self, out: Tensor, inv_pattern: str | None) -> list[Tensor]: ...
373
+
374
+ class InversePackTensor(Protocol):
375
+ """Annotate the inverse callable returned by `pack_with_inverse` for one `Tensor` input.
376
+
377
+ You can use `InversePackTensor` as a `Protocol` [1] for the inverse callable paired with
378
+ `pack_with_inverse` [2] when `t` is one `Tensor`. The callable accepts a packed or transformed
379
+ `Tensor` `out`, optionally accepts an override unpacking pattern `inv_pattern`, and returns one
380
+ reconstructed `Tensor` instead of `list[Tensor]`.
381
+
382
+ Call Signatures
383
+ ---------------
384
+ default pattern : callable
385
+ `inverse(out)` reuses the original `pattern` captured by `pack_with_inverse` [2].
386
+ override pattern : callable
387
+ `inverse(out, inv_pattern)` forwards `inv_pattern` to `einops.unpack` [3] instead of reusing
388
+ the original `pattern`. The returned callable unwraps the single reconstructed `Tensor` from
389
+ the single-item unpack result.
390
+
391
+ See Also
392
+ --------
393
+ InversePackListTensors : Annotate the inverse callable returned by `pack_with_inverse` for
394
+ `list[Tensor]` input.
395
+ torch_einops_kit.einops.pack_with_inverse : Build an `InversePackTensor` callable for one
396
+ `Tensor` input.
397
+
398
+ References
399
+ ----------
400
+ [1] Protocol - Python typing documentation
401
+ https://docs.python.org/3/library/typing.html#typing.Protocol
402
+ [2] torch_einops_kit.einops.pack_with_inverse
403
+
404
+ [3] einops pack/unpack API
405
+ https://einops.rocks/api/pack_unpack/
406
+ """
407
+ @overload
408
+ def __call__(self, out: Tensor) -> Tensor: ...
409
+ @overload
410
+ def __call__(self, out: Tensor, inv_pattern: str | None) -> Tensor: ...
411
+
335
412
  class SupportsIntIndex(Protocol[T_co]):
336
413
  """Match any object that supports integer indexing via `__getitem__`.
337
414
 
@@ -352,29 +429,3 @@ class SupportsIntIndex(Protocol[T_co]):
352
429
  [2] torch_einops_kit.first
353
430
  """
354
431
  def __getitem__(self, index: int, /) -> T_co: ...
355
-
356
- """
357
- Some or all of the logic in this module may be protected by the following.
358
-
359
- MIT License
360
-
361
- Copyright (c) 2026 Phil Wang
362
-
363
- Permission is hereby granted, free of charge, to any person obtaining a copy
364
- of this software and associated documentation files (the "Software"), to deal
365
- in the Software without restriction, including without limitation the rights
366
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
367
- copies of the Software, and to permit persons to whom the Software is
368
- furnished to do so, subject to the following conditions:
369
-
370
- The above copyright notice and this permission notice shall be included in all
371
- copies or substantial portions of the Software.
372
-
373
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
374
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
375
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
376
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
377
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
378
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
379
- SOFTWARE.
380
- """
@@ -300,7 +300,7 @@ def move_inputs_to_module_device(fn: Callable[Concatenate[TorchNNModule, PSpec],
300
300
  return workhorse
301
301
 
302
302
  """
303
- Some or all of the logic in this module may be protected by the following.
303
+ Some of the logic in this module may be protected by the following.
304
304
 
305
305
  MIT License
306
306
 
@@ -30,7 +30,8 @@ from torch_einops_kit import default, first
30
30
  from typing import overload, TYPE_CHECKING
31
31
 
32
32
  if TYPE_CHECKING:
33
- from collections.abc import Callable, Sequence
33
+ from collections.abc import Sequence
34
+ from torch_einops_kit import InversePackListTensors, InversePackTensor
34
35
 
35
36
  def pack_one(t: Tensor, pattern: str) -> tuple[Tensor, Sequence[tuple[int, ...] | list[int]]]:
36
37
  """Pack one `Tensor` and return shape metadata for paired reconstruction.
@@ -63,93 +64,114 @@ def pack_one(t: Tensor, pattern: str) -> tuple[Tensor, Sequence[tuple[int, ...]
63
64
  return pack([t], pattern)
64
65
 
65
66
  @overload
66
- def pack_with_inverse(t: Tensor, pattern: str) -> tuple[Tensor, Callable[[Tensor, str | None], Tensor]]: ...
67
+ def pack_with_inverse(t: Tensor, pattern: str) -> tuple[Tensor, InversePackTensor]: ...
67
68
  @overload
68
- def pack_with_inverse(t: list[Tensor], pattern: str) -> tuple[Tensor, Callable[[Tensor, str | None], list[Tensor]]]: ...
69
- def pack_with_inverse(t: Tensor | list[Tensor], pattern: str) -> tuple[Tensor, Callable[[Tensor, str | None], Tensor | list[Tensor]]]:
70
- """Pack `t` with `pattern` using einops and return a paired inverse unpacking function.
69
+ def pack_with_inverse(t: list[Tensor], pattern: str) -> tuple[Tensor, InversePackListTensors]: ...
70
+ def pack_with_inverse(t: Tensor | list[Tensor], pattern: str) -> tuple[Tensor, InversePackTensor] | tuple[Tensor, InversePackListTensors]:
71
+ """Pack `t` with `pattern` and return a paired inverse unpacking function.
71
72
 
72
- You can use this function to merge one or more tensors into a single packed tensor using an
73
- einops `pack` pattern [1] and to later restore the original shapes. When `t` is a single
74
- `torch.Tensor`, the function wraps `t` in a list before packing and unwraps the result inside the
75
- inverse function. When `t` is a list of tensors, the inverse function returns a list of tensors.
76
- The inverse function accepts an optional `inv_pattern` argument to override the pattern used for
77
- unpacking; when `inv_pattern` is `None`, the original `pattern` is reused.
73
+ You can use this function to merge one `Tensor` or one `list[Tensor]` into one packed `Tensor`
74
+ with `einops.pack` [1] and to carry forward an inverse callable tied to the captured packed-shape
75
+ metadata. The returned `inverse` callable accepts a packed or transformed `Tensor` `out`,
76
+ optionally accepts an override unpacking pattern `inv_pattern`, and reconstructs either one
77
+ `Tensor` or `list[Tensor]` to match the kind of `t`.
78
78
 
79
79
  Parameters
80
80
  ----------
81
81
  t : Tensor | list[Tensor]
82
- A single tensor or a list of tensors to pack.
82
+ One `Tensor` or one `list[Tensor]` to pack.
83
83
  pattern : str
84
- An einops pack pattern string such as `'b * d'`, where `*` collects the packed dimensions.
84
+ Einops pack pattern string passed to `einops.pack` [1]. The `*` axis marks the dimensions to
85
+ collect into the packed axis.
85
86
 
86
87
  Returns
87
88
  -------
88
89
  packed : Tensor
89
90
  The packed tensor produced by `einops.pack` [1].
90
- inverse : Callable[[Tensor, str | None], Tensor | list[Tensor]]
91
- A function that accepts the packed (or transformed) tensor and an optional override pattern
92
- and returns the unpacked tensor or list of tensors.
91
+ inverse : InversePackTensor | InversePackListTensors
92
+ Paired inverse callable. When `t` is one `Tensor`, `inverse` has type `InversePackTensor` [2]
93
+ and returns one `Tensor`. When `t` is a `list[Tensor]`, `inverse` has type
94
+ `InversePackListTensors` [3] and returns `list[Tensor]`.
95
+
96
+ Output Kind
97
+ -----------
98
+ tensor input : dispatch
99
+ Passing one `Tensor` returns an `inverse` callable that unwraps the single unpacked result.
100
+ list input : dispatch
101
+ Passing `list[Tensor]` returns an `inverse` callable that preserves the unpacked list
102
+ structure.
103
+
104
+ Unpacking Pattern
105
+ -----------------
106
+ `inv_pattern` override : pattern reuse
107
+ The returned `inverse` reuses `pattern` when `inv_pattern` is `None`. Passing `inv_pattern`
108
+ forwards `inv_pattern` to `einops.unpack` [4] so `inverse` can unpack a derived `Tensor`, as
109
+ long as `inv_pattern` remains compatible with the packed-shape metadata captured during
110
+ packing.
93
111
 
94
112
  See Also
95
113
  --------
96
- tree_flatten_with_inverse : Flatten a PyTree and return an inverse reconstruction function.
114
+ pack_one :
115
+ Pack one `Tensor` and return shape metadata for paired reconstruction.
116
+ tree_flatten_with_inverse :
117
+ Flatten a PyTree and return an inverse reconstruction function.
118
+ unpack_one :
119
+ Unpack one `Tensor` using metadata produced by `pack_one`.
97
120
 
98
121
  Examples
99
122
  --------
100
- Pack a single tensor and recover the original shape [2]:
123
+ Pack one tensor and recover the original shape.
101
124
 
102
125
  ```python
103
126
  import torch
127
+
104
128
  from torch_einops_kit import pack_with_inverse
105
129
 
106
130
  t = torch.randn(3, 12, 2, 2)
107
131
  packed, inverse = pack_with_inverse(t, 'b * d')
108
- # packed.shape == (3, 24, 2)
109
- recovered = inverse(packed)
110
- # recovered.shape == (3, 12, 2, 2)
111
- ```
112
132
 
113
- Pack a list of tensors and unpack with an overriding pattern [2]:
133
+ assert packed.shape == (3, 24, 2)
114
134
 
115
- ```python
116
- t = torch.randn(3, 12, 2)
117
- u = torch.randn(3, 4, 2)
118
- packed, inverse = pack_with_inverse([t, u], 'b * d')
119
- # packed.shape == (3, 28, 2)
120
-
121
- reduced = packed.sum(dim=-1)
122
- t_out, u_out = inverse(reduced, 'b *')
123
- # t_out.shape == (3, 12)
124
- # u_out.shape == (3, 4)
135
+ recovered = inverse(packed)
136
+ assert recovered.shape == (3, 12, 2, 2)
125
137
  ```
126
138
 
127
139
  References
128
140
  ----------
129
141
  [1] einops.pack - einops documentation
130
142
  https://einops.rocks/api/pack/
131
- [2] tests.test_utils.test_pack_with_inverse
143
+ [2] torch_einops_kit.InversePackTensor
132
144
 
133
- """
134
- is_one: bool = is_tensor(t)
145
+ [3] torch_einops_kit.InversePackListTensors
135
146
 
136
- if is_one:
147
+ [4] einops pack/unpack API
148
+ https://einops.rocks/api/pack_unpack/
149
+
150
+ """
151
+ if is_tensor(t):
152
+ is_one = True
137
153
  sequenceT: Sequence[Tensor] = [t]
138
154
  else:
155
+ is_one = False
139
156
  sequenceT = t
140
157
 
141
158
  packed, packed_shape = pack(sequenceT, pattern)
142
159
 
143
- def inverse(out: Tensor, inv_pattern: str | None = None) -> Tensor | list[Tensor]:
160
+ def inverse_is_one(out: Tensor, inv_pattern: str | None = None) -> Tensor:
144
161
  inv_pattern = default(inv_pattern, pattern)
145
162
  unpacked: list[Tensor] = unpack(out, packed_shape, inv_pattern)
146
163
 
147
- if is_one:
148
- return first(unpacked)
164
+ return first(unpacked)
165
+
166
+ def inverse_is_list(out: Tensor, inv_pattern: str | None = None) -> list[Tensor]:
167
+ inv_pattern = default(inv_pattern, pattern)
168
+ unpacked: list[Tensor] = unpack(out, packed_shape, inv_pattern)
149
169
 
150
170
  return unpacked
151
171
 
152
- return packed, inverse
172
+ if is_one:
173
+ return packed, inverse_is_one
174
+ return packed, inverse_is_list
153
175
 
154
176
  def unpack_one(t: Tensor, ps: Sequence[tuple[int, ...] | list[int]], pattern: str) -> Tensor:
155
177
  """Unpack one `Tensor` using packed-shape metadata produced by `pack_one`.
@@ -186,7 +208,7 @@ def unpack_one(t: Tensor, ps: Sequence[tuple[int, ...] | list[int]], pattern: st
186
208
  return unpack(t, list(ps), pattern)[0]
187
209
 
188
210
  """
189
- Some or all of the logic in this module may be protected by the following.
211
+ Some of the logic in this module may be protected by the following.
190
212
 
191
213
  MIT License
192
214
 
@@ -365,19 +365,19 @@ def save_load(
365
365
  [7] tests.test_save_load.test_init_and_load
366
366
 
367
367
  [8] tests.test_save_load_extended.test_save_load_supports_custom_method_names_and_config_storage
368
- """
368
+ """ # noqa: DOC502
369
369
 
370
370
  def _save_load(klass: type[TorchNNModule]) -> type[TorchNNModule]:
371
371
  if not issubclass(klass, Module):
372
372
  message: str = 'save_load should decorate a subclass of torch.nn.Module'
373
373
  raise TypeError(message)
374
374
 
375
- _orig_init: Callable[..., None] = klass.__init__
375
+ original_init: Callable[..., None] = klass.__init__
376
376
 
377
- @wraps(_orig_init)
377
+ @wraps(original_init)
378
378
  def __init__(self: TorchNNModule, *args: Any, **kwargs: Any) -> None:
379
379
  setattr(self, config_instance_var_name, (args, kwargs))
380
- _orig_init(self, *args, **kwargs)
380
+ original_init(self, *args, **kwargs)
381
381
 
382
382
  def _save(self: TorchNNModule, path: StrPath, *, overwrite: bool = True) -> None:
383
383
  """Save the current model state and constructor configuration to a checkpoint file.
@@ -395,10 +395,6 @@ def save_load(
395
395
  When `False`, raise `FileExistsError` if a file already exists at `path`. When
396
396
  `True`, an existing file at `path` is silently replaced.
397
397
 
398
- Returns
399
- -------
400
- None
401
-
402
398
  Raises
403
399
  ------
404
400
  FileExistsError
@@ -438,10 +434,6 @@ def save_load(
438
434
  Forwarded to `load_state_dict`. When `True`, the key sets of the checkpoint and the
439
435
  current model must match exactly.
440
436
 
441
- Returns
442
- -------
443
- None
444
-
445
437
  Raises
446
438
  ------
447
439
  FileNotFoundError
@@ -256,7 +256,7 @@ def reverse_cumsum(t: Tensor, dim: int = -1, *, keepdim: bool = True) -> Tensor:
256
256
  [4] Broadcasting semantics - PyTorch documentation
257
257
  https://pytorch.org/docs/stable/notes/broadcasting.html
258
258
  """
259
- return t.sum(dim = dim, keepdim = keepdim) - t.cumsum(dim = dim) + t
259
+ return t.sum(dim=dim, keepdim=keepdim) - t.cumsum(dim=dim) + t
260
260
 
261
261
  class RMSNorm(Module):
262
262
  """Normalize feature vectors with root-mean-square scaling and a learned rescaling parameter.
@@ -15,7 +15,7 @@ Functions
15
15
  from __future__ import annotations
16
16
 
17
17
  from torch import is_tensor, Tensor
18
- from torch.utils._pytree import PyTree, tree_flatten, tree_map, tree_unflatten
18
+ from torch.utils._pytree import PyTree, tree_flatten, tree_map, tree_unflatten # noqa: PLC2701
19
19
  from typing import Any, TYPE_CHECKING
20
20
 
21
21
  if TYPE_CHECKING: