michaelu0826 commited on
Commit
b0d2a6c
·
verified ·
1 Parent(s): a154c10

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. lib/python3.11/site-packages/brotli-1.2.0.dist-info/INSTALLER +1 -0
  2. lib/python3.11/site-packages/brotli-1.2.0.dist-info/METADATA +158 -0
  3. lib/python3.11/site-packages/brotli-1.2.0.dist-info/RECORD +9 -0
  4. lib/python3.11/site-packages/brotli-1.2.0.dist-info/WHEEL +6 -0
  5. lib/python3.11/site-packages/brotli-1.2.0.dist-info/licenses/LICENSE +19 -0
  6. lib/python3.11/site-packages/brotli-1.2.0.dist-info/top_level.txt +2 -0
  7. lib/python3.11/site-packages/easydict-1.13.dist-info/INSTALLER +1 -0
  8. lib/python3.11/site-packages/easydict-1.13.dist-info/LICENSE +165 -0
  9. lib/python3.11/site-packages/easydict-1.13.dist-info/METADATA +210 -0
  10. lib/python3.11/site-packages/easydict-1.13.dist-info/RECORD +9 -0
  11. lib/python3.11/site-packages/easydict-1.13.dist-info/REQUESTED +0 -0
  12. lib/python3.11/site-packages/easydict-1.13.dist-info/WHEEL +5 -0
  13. lib/python3.11/site-packages/easydict-1.13.dist-info/top_level.txt +1 -0
  14. lib/python3.11/site-packages/easydict/__init__.py +172 -0
  15. lib/python3.11/site-packages/easydict/__pycache__/__init__.cpython-311.pyc +0 -0
  16. lib/python3.11/site-packages/einops/__init__.py +17 -0
  17. lib/python3.11/site-packages/einops/__pycache__/__init__.cpython-311.pyc +0 -0
  18. lib/python3.11/site-packages/einops/__pycache__/_backends.cpython-311.pyc +0 -0
  19. lib/python3.11/site-packages/einops/__pycache__/_torch_specific.cpython-311.pyc +0 -0
  20. lib/python3.11/site-packages/einops/__pycache__/array_api.cpython-311.pyc +0 -0
  21. lib/python3.11/site-packages/einops/__pycache__/einops.cpython-311.pyc +0 -0
  22. lib/python3.11/site-packages/einops/_backends.py +764 -0
  23. lib/python3.11/site-packages/einops/_torch_specific.py +136 -0
  24. lib/python3.11/site-packages/einops/array_api.py +125 -0
  25. lib/python3.11/site-packages/einops/einops.py +939 -0
  26. lib/python3.11/site-packages/einops/experimental/__init__.py +0 -0
  27. lib/python3.11/site-packages/einops/experimental/__pycache__/__init__.cpython-311.pyc +0 -0
  28. lib/python3.11/site-packages/einops/experimental/__pycache__/indexing.cpython-311.pyc +0 -0
  29. lib/python3.11/site-packages/einops/experimental/indexing.py +5 -0
  30. lib/python3.11/site-packages/einops/layers/__init__.py +105 -0
  31. lib/python3.11/site-packages/einops/layers/__pycache__/__init__.cpython-311.pyc +0 -0
  32. lib/python3.11/site-packages/einops/layers/__pycache__/_einmix.cpython-311.pyc +0 -0
  33. lib/python3.11/site-packages/einops/layers/__pycache__/flax.cpython-311.pyc +0 -0
  34. lib/python3.11/site-packages/einops/layers/__pycache__/keras.cpython-311.pyc +0 -0
  35. lib/python3.11/site-packages/einops/layers/__pycache__/oneflow.cpython-311.pyc +0 -0
  36. lib/python3.11/site-packages/einops/layers/__pycache__/paddle.cpython-311.pyc +0 -0
  37. lib/python3.11/site-packages/einops/layers/__pycache__/tensorflow.cpython-311.pyc +0 -0
  38. lib/python3.11/site-packages/einops/layers/__pycache__/torch.cpython-311.pyc +0 -0
  39. lib/python3.11/site-packages/einops/layers/_einmix.py +227 -0
  40. lib/python3.11/site-packages/einops/layers/flax.py +82 -0
  41. lib/python3.11/site-packages/einops/layers/keras.py +9 -0
  42. lib/python3.11/site-packages/einops/layers/oneflow.py +54 -0
  43. lib/python3.11/site-packages/einops/layers/paddle.py +58 -0
  44. lib/python3.11/site-packages/einops/layers/tensorflow.py +101 -0
  45. lib/python3.11/site-packages/einops/layers/torch.py +68 -0
  46. lib/python3.11/site-packages/einops/packing.py +189 -0
  47. lib/python3.11/site-packages/einops/parsing.py +158 -0
  48. lib/python3.11/site-packages/einops/py.typed +0 -0
  49. lib/python3.11/site-packages/einops/tests/__init__.py +109 -0
  50. lib/python3.11/site-packages/einops/tests/__pycache__/__init__.cpython-311.pyc +0 -0
lib/python3.11/site-packages/brotli-1.2.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
lib/python3.11/site-packages/brotli-1.2.0.dist-info/METADATA ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: brotli
3
+ Version: 1.2.0
4
+ Summary: Python bindings for the Brotli compression library
5
+ Home-page: https://github.com/google/brotli
6
+ Author: The Brotli Authors
7
+ License: MIT
8
+ Platform: Posix
9
+ Platform: MacOS X
10
+ Platform: Windows
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: MacOS :: MacOS X
15
+ Classifier: Operating System :: Microsoft :: Windows
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: C
18
+ Classifier: Programming Language :: C++
19
+ Classifier: Programming Language :: Python
20
+ Classifier: Programming Language :: Python :: 2
21
+ Classifier: Programming Language :: Python :: 2.7
22
+ Classifier: Programming Language :: Python :: 3
23
+ Classifier: Programming Language :: Python :: 3.3
24
+ Classifier: Programming Language :: Python :: 3.4
25
+ Classifier: Programming Language :: Python :: 3.5
26
+ Classifier: Programming Language :: Unix Shell
27
+ Classifier: Topic :: Software Development :: Libraries
28
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
29
+ Classifier: Topic :: System :: Archiving
30
+ Classifier: Topic :: System :: Archiving :: Compression
31
+ Classifier: Topic :: Text Processing :: Fonts
32
+ Classifier: Topic :: Utilities
33
+ Description-Content-Type: text/markdown
34
+ License-File: LICENSE
35
+ Dynamic: author
36
+ Dynamic: classifier
37
+ Dynamic: description
38
+ Dynamic: description-content-type
39
+ Dynamic: home-page
40
+ Dynamic: license
41
+ Dynamic: license-file
42
+ Dynamic: platform
43
+ Dynamic: summary
44
+
45
+ <p align="center">
46
+ <img src="https://github.com/google/brotli/actions/workflows/build_test.yml/badge.svg" alt="GitHub Actions Build Status" href="https://github.com/google/brotli/actions?query=branch%3Amaster">
47
+ <img src="https://oss-fuzz-build-logs.storage.googleapis.com/badges/brotli.svg" alt="Fuzzing Status" href="https://oss-fuzz-build-logs.storage.googleapis.com/index.html#brotli">
48
+ </p>
49
+ <p align="center"><img src="https://brotli.org/brotli.svg" alt="Brotli" width="64"></p>
50
+
51
+ ### Introduction
52
+
53
+ Brotli is a generic-purpose lossless compression algorithm that compresses data
54
+ using a combination of a modern variant of the LZ77 algorithm, Huffman coding
55
+ and 2nd order context modeling, with a compression ratio comparable to the best
56
+ currently available general-purpose compression methods. It is similar in speed
57
+ with deflate but offers more dense compression.
58
+
59
+ The specification of the Brotli Compressed Data Format is defined in
60
+ [RFC 7932](https://datatracker.ietf.org/doc/html/rfc7932).
61
+
62
+ Brotli is open-sourced under the MIT License, see the LICENSE file.
63
+
64
+ > **Please note:** brotli is a "stream" format; it does not contain
65
+ > meta-information, like checksums or uncompressed data length. It is possible
66
+ > to modify "raw" ranges of the compressed stream and the decoder will not
67
+ > notice that.
68
+
69
+ ### Installation
70
+
71
+ In most Linux distributions, installing `brotli` is just a matter of using
72
+ the package management system. For example in Debian-based distributions:
73
+ `apt install brotli` will install `brotli`. On MacOS, you can use
74
+ [Homebrew](https://brew.sh/): `brew install brotli`.
75
+
76
+ [![brotli packaging status](https://repology.org/badge/vertical-allrepos/brotli.svg?exclude_unsupported=1&columns=3&exclude_sources=modules,site&header=brotli%20packaging%20status)](https://repology.org/project/brotli/versions)
77
+
78
+ Of course you can also build brotli from sources.
79
+
80
+ ### Build instructions
81
+
82
+ #### Vcpkg
83
+
84
+ You can download and install brotli using the
85
+ [vcpkg](https://github.com/Microsoft/vcpkg/) dependency manager:
86
+
87
+ git clone https://github.com/Microsoft/vcpkg.git
88
+ cd vcpkg
89
+ ./bootstrap-vcpkg.sh
90
+ ./vcpkg integrate install
91
+ ./vcpkg install brotli
92
+
93
+ The brotli port in vcpkg is kept up to date by Microsoft team members and
94
+ community contributors. If the version is out of date, please [create an issue
95
+ or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
96
+
97
+ #### Bazel
98
+
99
+ See [Bazel](https://www.bazel.build/)
100
+
101
+ #### CMake
102
+
103
+ The basic commands to build and install brotli are:
104
+
105
+ $ mkdir out && cd out
106
+ $ cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=./installed ..
107
+ $ cmake --build . --config Release --target install
108
+
109
+ You can use other [CMake](https://cmake.org/) configuration.
110
+
111
+ #### Python
112
+
113
+ To install the latest release of the Python module, run the following:
114
+
115
+ $ pip install brotli
116
+
117
+ To install the tip-of-the-tree version, run:
118
+
119
+ $ pip install --upgrade git+https://github.com/google/brotli
120
+
121
+ See the [Python readme](python/README.md) for more details on installing
122
+ from source, development, and testing.
123
+
124
+ ### Contributing
125
+
126
+ We glad to answer/library related questions in
127
+ [brotli mailing list](https://groups.google.com/g/brotli).
128
+
129
+ Regular issues / feature requests should be reported in
130
+ [issue tracker](https://github.com/google/brotli/issues).
131
+
132
+ For reporting vulnerability please read [SECURITY](SECURITY.md).
133
+
134
+ For contributing changes please read [CONTRIBUTING](CONTRIBUTING.md).
135
+
136
+ ### Benchmarks
137
+ * [Squash Compression Benchmark](https://quixdb.github.io/squash-benchmark/) / [Unstable Squash Compression Benchmark](https://quixdb.github.io/squash-benchmark/unstable/)
138
+ * [Large Text Compression Benchmark](https://mattmahoney.net/dc/text.html)
139
+ * [Lzturbo Benchmark](https://sites.google.com/site/powturbo/home/benchmark)
140
+
141
+ ### Related projects
142
+ > **Disclaimer:** Brotli authors take no responsibility for the third party projects mentioned in this section.
143
+
144
+ Independent [decoder](https://github.com/madler/brotli) implementation
145
+ by Mark Adler, based entirely on format specification.
146
+
147
+ JavaScript port of brotli [decoder](https://github.com/devongovett/brotli.js).
148
+ Could be used directly via `npm install brotli`
149
+
150
+ Hand ported [decoder / encoder](https://github.com/dominikhlbg/BrotliHaxe)
151
+ in haxe by Dominik Homberger.
152
+ Output source code: JavaScript, PHP, Python, Java and C#
153
+
154
+ 7Zip [plugin](https://github.com/mcmilk/7-Zip-Zstd)
155
+
156
+ Dart compression framework with
157
+ [fast FFI-based Brotli implementation](https://pub.dev/documentation/es_compression/latest/brotli/)
158
+ with ready-to-use prebuilt binaries for Win/Linux/Mac
lib/python3.11/site-packages/brotli-1.2.0.dist-info/RECORD ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/brotli.cpython-311.pyc,,
2
+ _brotli.cpython-311-x86_64-linux-gnu.so,sha256=oNkoKKdbC8N6n3NI5g1V4MFmzEX8vlGAiWeInBs6jxs,5173360
3
+ brotli-1.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
4
+ brotli-1.2.0.dist-info/METADATA,sha256=-dEtUYS1CQsUay5fDWKTFSGysUNepGZDOiObt8QfyWI,6116
5
+ brotli-1.2.0.dist-info/RECORD,,
6
+ brotli-1.2.0.dist-info/WHEEL,sha256=_CFvICYDmZlAYHt8L7Zn3n-BGLj8dkZLQPp22Piy5JE,151
7
+ brotli-1.2.0.dist-info/licenses/LICENSE,sha256=PRgACONpIqTo2uwRw0x68mT-1ZYtB5JK6pKMOOhmPJQ,1084
8
+ brotli-1.2.0.dist-info/top_level.txt,sha256=gsS54HrhO3ZveFxeMrKo_7qH4Sm4TbQ7jGLVBEqJ4NI,15
9
+ brotli.py,sha256=gTYQvw10ppmNe0fZEuiJLDiW5urBnLeyJXXgT8KUtj8,1970
lib/python3.11/site-packages/brotli-1.2.0.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp311-cp311-manylinux_2_17_x86_64
5
+ Tag: cp311-cp311-manylinux2014_x86_64
6
+
lib/python3.11/site-packages/brotli-1.2.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
lib/python3.11/site-packages/brotli-1.2.0.dist-info/top_level.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ _brotli
2
+ brotli
lib/python3.11/site-packages/easydict-1.13.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
lib/python3.11/site-packages/easydict-1.13.dist-info/LICENSE ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
lib/python3.11/site-packages/easydict-1.13.dist-info/METADATA ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: easydict
3
+ Version: 1.13
4
+ Summary: Access dict values as attributes (works recursively).
5
+ Home-page: https://github.com/makinacorpus/easydict
6
+ Download-URL: http://pypi.python.org/pypi/easydict/
7
+ Author: Mathieu Leplatre
8
+ Author-email: mathieu.leplatre@makina-corpus.com
9
+ License: LGPL-3.0
10
+ Keywords: Tools
11
+ Classifier: Topic :: Utilities
12
+ Classifier: Natural Language :: English
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Development Status :: 5 - Production/Stable
16
+ Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
17
+ Classifier: Programming Language :: Python :: 2.5
18
+ Classifier: Programming Language :: Python :: 3.6
19
+ License-File: LICENSE
20
+
21
+ .. image:: https://img.shields.io/pypi/v/easydict.svg
22
+ :target: https://pypi.python.org/pypi/easydict
23
+
24
+ .. image:: https://img.shields.io/pypi/dm/easydict.svg
25
+ :target: https://pypi.python.org/pypi/easydict
26
+
27
+ ========
28
+ Easydict
29
+ ========
30
+
31
+ *EasyDict* allows to access dict values as attributes (works recursively).
32
+ A Javascript-like properties dot notation for python dicts.
33
+
34
+ INSTALL
35
+ =======
36
+
37
+ ::
38
+
39
+ pip install easydict
40
+
41
+
42
+ USAGE
43
+ =====
44
+
45
+ ::
46
+
47
+ >>> from easydict import EasyDict as edict
48
+ >>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}})
49
+ >>> d.foo
50
+ 3
51
+ >>> d.bar.x
52
+ 1
53
+
54
+ >>> d = edict(foo=3)
55
+ >>> d.foo
56
+ 3
57
+
58
+
59
+ Very useful when exploiting parsed JSON content !
60
+
61
+ ::
62
+
63
+ >>> from easydict import EasyDict as edict
64
+ >>> from simplejson import loads
65
+ >>> j = """{
66
+ "Buffer": 12,
67
+ "List1": [
68
+ {"type" : "point", "coordinates" : [100.1,54.9] },
69
+ {"type" : "point", "coordinates" : [109.4,65.1] },
70
+ {"type" : "point", "coordinates" : [115.2,80.2] },
71
+ {"type" : "point", "coordinates" : [150.9,97.8] }
72
+ ]
73
+ }"""
74
+ >>> d = edict(loads(j))
75
+ >>> d.Buffer
76
+ 12
77
+ >>> d.List1[0].coordinates[1]
78
+ 54.9
79
+
80
+ Can set attributes as easily as getting them :
81
+
82
+ ::
83
+
84
+ >>> d = EasyDict()
85
+ >>> d.foo = 3
86
+ >>> d.foo
87
+ 3
88
+
89
+ It is still a ``dict`` !
90
+
91
+ ::
92
+
93
+ >>> d = EasyDict(log=False)
94
+ >>> d.debug = True
95
+ >>> d.items()
96
+ [('debug', True), ('log', False)]
97
+
98
+ Instance and class attributes are accessed like usual objects...
99
+
100
+ ::
101
+
102
+ >>> class Flower(EasyDict):
103
+ ... power = 1
104
+ ...
105
+ >>> f = Flower({'height': 12})
106
+ >>> f.power
107
+ 1
108
+ >>> f['power']
109
+ 1
110
+
111
+ LICENSE
112
+ =======
113
+
114
+ * Lesser GNU Public License
115
+
116
+ AUTHORS
117
+ =======
118
+
119
+ * Mathieu Leplatre <mathieu.leplatre@makina-corpus.com>
120
+
121
+ |makinacom|_
122
+
123
+ .. |makinacom| image:: http://depot.makina-corpus.org/public/logo.gif
124
+ .. _makinacom: http://www.makina-corpus.com
125
+
126
+ Similar tools
127
+ =============
128
+
129
+ * `TreeDict <http://pypi.python.org/pypi/treedict>`_, a fast and full-featured dict-like tree container.
130
+ * `addict <https://github.com/mewwts/addict>`_
131
+
132
+
133
+ =========
134
+ CHANGELOG
135
+ =========
136
+
137
+ 1.12 (2024-03-04)
138
+ =================
139
+
140
+ - Fix #46: Fix handling of optional default value for .pop() (#47)
141
+
142
+ 1.12 (2024-02-13)
143
+ =================
144
+
145
+ - Fix #22: Do not convert tuple attributes to list (#44)
146
+
147
+ 1.11 (2023-10-24)
148
+ =================
149
+
150
+ - Fix #39: RecursionError when dict in class member (#41)
151
+ - Minor changes in README
152
+
153
+ 1.10 (2022-09-28)
154
+ =================
155
+
156
+ * Make tests compatible with python2 and python3 (thanks @JackLangerman)
157
+ * Dictify input
158
+ * Fix license metadata
159
+
160
+ 1.9 (2018-10-18)
161
+ ================
162
+
163
+ * Fix issue #3 that update and pop now work correctly on EasyDicts.
164
+
165
+
166
+ 1.8 (2018-08-17)
167
+ ================
168
+
169
+ * Update package classifiers.
170
+
171
+
172
+ 1.7 (2017-04-27)
173
+ ================
174
+
175
+ * Prevent copying sub-EasyDicts on assignment to fix unpickling (#7, thanks @Chronos-Sk)
176
+
177
+ 1.6 (2015-01-27)
178
+ ================
179
+
180
+ * Allow setting attributes via setting items (thanks phivos)
181
+
182
+ 1.5 (2014-08-07)
183
+ ================
184
+
185
+ * Allow subclassing using self instead of class name (thanks Steve Engledow)
186
+
187
+ 1.4 (2011-03-13)
188
+ ================
189
+
190
+ * Access class attributes like instance attributes
191
+
192
+ 1.3 (2012-02-08)
193
+ ================
194
+
195
+ * Better documentation and tests
196
+
197
+ 1.2 (2011-06-08)
198
+ ================
199
+
200
+ * Fix inclusion of README
201
+
202
+ 1.1 (2012-04-21)
203
+ ================
204
+
205
+ * Switch to distutils2
206
+
207
+ 1.0 (2011-04-18)
208
+ ================
209
+
210
+ * Initial working version
lib/python3.11/site-packages/easydict-1.13.dist-info/RECORD ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ easydict-1.13.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ easydict-1.13.dist-info/LICENSE,sha256=2n6rt7r999OuXp8iOqW9we7ORaxWncIbOwN1ILRGR2g,7651
3
+ easydict-1.13.dist-info/METADATA,sha256=YPrpwf30ijzJABsg6D-gVIgjZVmnQPh_GggB2ibalBY,4188
4
+ easydict-1.13.dist-info/RECORD,,
5
+ easydict-1.13.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ easydict-1.13.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
7
+ easydict-1.13.dist-info/top_level.txt,sha256=WDpNAmp3Lb0_IG0NcZb77INmgflthquw-8KX8Rf9isw,9
8
+ easydict/__init__.py,sha256=fVYcsTpfPRLYuf31_OguehXsQvO_E2FXTHMQ2DYUUTo,3664
9
+ easydict/__pycache__/__init__.cpython-311.pyc,,
lib/python3.11/site-packages/easydict-1.13.dist-info/REQUESTED ADDED
File without changes
lib/python3.11/site-packages/easydict-1.13.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.42.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
lib/python3.11/site-packages/easydict-1.13.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ easydict
lib/python3.11/site-packages/easydict/__init__.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class EasyDict(dict):
2
+ """
3
+ Get attributes
4
+
5
+ >>> d = EasyDict({'foo':3})
6
+ >>> d['foo']
7
+ 3
8
+ >>> d.foo
9
+ 3
10
+ >>> d.bar
11
+ Traceback (most recent call last):
12
+ ...
13
+ AttributeError: 'EasyDict' object has no attribute 'bar'
14
+
15
+ Works recursively
16
+
17
+ >>> d = EasyDict({'foo':3, 'bar':{'x':1, 'y':2}})
18
+ >>> isinstance(d.bar, dict)
19
+ True
20
+ >>> d.bar.x
21
+ 1
22
+
23
+ Bullet-proof
24
+
25
+ >>> EasyDict({})
26
+ {}
27
+ >>> EasyDict(d={})
28
+ {}
29
+ >>> EasyDict(None)
30
+ {}
31
+ >>> d = {'a': 1}
32
+ >>> EasyDict(**d)
33
+ {'a': 1}
34
+ >>> EasyDict((('a', 1), ('b', 2)))
35
+ {'a': 1, 'b': 2}
36
+
37
+ Set attributes
38
+
39
+ >>> d = EasyDict()
40
+ >>> d.foo = 3
41
+ >>> d.foo
42
+ 3
43
+ >>> d.bar = {'prop': 'value'}
44
+ >>> d.bar.prop
45
+ 'value'
46
+ >>> d
47
+ {'foo': 3, 'bar': {'prop': 'value'}}
48
+ >>> d.bar.prop = 'newer'
49
+ >>> d.bar.prop
50
+ 'newer'
51
+ >>> d.lst = [1, 2, 3]
52
+ >>> d.lst
53
+ [1, 2, 3]
54
+ >>> d.tpl = (1, 2, 3)
55
+ >>> d.tpl
56
+ (1, 2, 3)
57
+
58
+
59
+ Values extraction
60
+
61
+ >>> d = EasyDict({'foo':0, 'bar':[{'x':1, 'y':2}, {'x':3, 'y':4}]})
62
+ >>> isinstance(d.bar, list)
63
+ True
64
+ >>> from operator import attrgetter
65
+ >>> list(map(attrgetter('x'), d.bar))
66
+ [1, 3]
67
+ >>> list(map(attrgetter('y'), d.bar))
68
+ [2, 4]
69
+ >>> d = EasyDict()
70
+ >>> list(d.keys())
71
+ []
72
+ >>> d = EasyDict(foo=3, bar=dict(x=1, y=2))
73
+ >>> d.foo
74
+ 3
75
+ >>> d.bar.x
76
+ 1
77
+
78
+ Still like a dict though
79
+
80
+ >>> o = EasyDict({'clean':True})
81
+ >>> list(o.items())
82
+ [('clean', True)]
83
+
84
+ And like a class
85
+
86
+ >>> class Flower(EasyDict):
87
+ ... power = 1
88
+ ... mean = {}
89
+ ... color = {"r": 100, "g": 0, "b": 0}
90
+ ...
91
+ >>> f = Flower()
92
+ >>> f.power
93
+ 1
94
+ >>> f.color.r
95
+ 100
96
+ >>> f.mean.x = 10
97
+ >>> f.mean.x
98
+ 10
99
+ >>> f = Flower({'height': 12})
100
+ >>> f.height
101
+ 12
102
+ >>> f['power']
103
+ 1
104
+ >>> sorted(f.keys())
105
+ ['color', 'height', 'mean', 'power']
106
+
107
+ update and pop items
108
+ >>> d = EasyDict(a=1, b='2')
109
+ >>> e = EasyDict(c=3.0, a=9.0)
110
+ >>> d.update(e)
111
+ >>> d.c
112
+ 3.0
113
+ >>> d['c']
114
+ 3.0
115
+ >>> d.get('c')
116
+ 3.0
117
+ >>> d.update(a=4, b=4)
118
+ >>> d.b
119
+ 4
120
+ >>> d.pop('a')
121
+ 4
122
+ >>> d.a
123
+ Traceback (most recent call last):
124
+ ...
125
+ AttributeError: 'EasyDict' object has no attribute 'a'
126
+ >>> d.pop('a', 8)
127
+ 8
128
+ >>> d.pop('b', 100)
129
+ 4
130
+ >>> d
131
+ {'c': 3.0}
132
+ """
133
+ def __init__(self, d=None, **kwargs):
134
+ if d is None:
135
+ d = {}
136
+ else:
137
+ d = dict(d)
138
+ if kwargs:
139
+ d.update(**kwargs)
140
+ for k, v in d.items():
141
+ setattr(self, k, v)
142
+ # Class attributes
143
+ for k in self.__class__.__dict__.keys():
144
+ if not (k.startswith('__') and k.endswith('__')) and k not in ('update', 'pop'):
145
+ setattr(self, k, getattr(self, k))
146
+
147
+ def __setattr__(self, name, value):
148
+ if isinstance(value, (list, tuple)):
149
+ value = type(value)(self.__class__(x)
150
+ if isinstance(x, dict) else x for x in value)
151
+ elif isinstance(value, dict) and not isinstance(value, EasyDict):
152
+ value = EasyDict(value)
153
+ super(EasyDict, self).__setattr__(name, value)
154
+ super(EasyDict, self).__setitem__(name, value)
155
+
156
+ __setitem__ = __setattr__
157
+
158
+ def update(self, e=None, **f):
159
+ d = e or dict()
160
+ d.update(f)
161
+ for k in d:
162
+ setattr(self, k, d[k])
163
+
164
+ def pop(self, k, *args):
165
+ if hasattr(self, k):
166
+ delattr(self, k)
167
+ return super(EasyDict, self).pop(k, *args)
168
+
169
+
170
+ if __name__ == "__main__":
171
+ import doctest
172
+ doctest.testmod()
lib/python3.11/site-packages/easydict/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (5.85 kB). View file
 
lib/python3.11/site-packages/einops/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # imports can use EinopsError class
2
+ # ruff: noqa: E402
3
+
4
+ __author__ = "Alex Rogozhnikov"
5
+ __version__ = "0.8.2"
6
+
7
+
8
+ class EinopsError(RuntimeError):
9
+ """Runtime error thrown by einops"""
10
+
11
+ pass # noqa: PIE790
12
+
13
+
14
+ __all__ = ["EinopsError", "asnumpy", "einsum", "pack", "parse_shape", "rearrange", "reduce", "repeat", "unpack"]
15
+
16
+ from .einops import asnumpy, einsum, parse_shape, rearrange, reduce, repeat
17
+ from .packing import pack, unpack
lib/python3.11/site-packages/einops/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (882 Bytes). View file
 
lib/python3.11/site-packages/einops/__pycache__/_backends.cpython-311.pyc ADDED
Binary file (48.1 kB). View file
 
lib/python3.11/site-packages/einops/__pycache__/_torch_specific.cpython-311.pyc ADDED
Binary file (7 kB). View file
 
lib/python3.11/site-packages/einops/__pycache__/array_api.cpython-311.pyc ADDED
Binary file (7.75 kB). View file
 
lib/python3.11/site-packages/einops/__pycache__/einops.cpython-311.pyc ADDED
Binary file (47 kB). View file
 
lib/python3.11/site-packages/einops/_backends.py ADDED
@@ -0,0 +1,764 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Backends in `einops` are organized to meet the following requirements
3
+ - backends are not imported unless those are actually needed, because
4
+ - backends may not be installed
5
+ - importing all available backends will drive to significant memory footprint
6
+ - backends may be present but installed with errors (but never used),
7
+ importing may drive to crashes
8
+ - backend should be either symbolic or imperative
9
+ - this determines which methods (from_numpy/to_numpy or create_symbol/eval_symbol) should be defined
10
+ - if backend can't provide symbols for shape dimensions, UnknownSize objects are used
11
+ """
12
+
13
+ import sys
14
+
15
+ __author__ = "Alex Rogozhnikov"
16
+
17
+ _loaded_backends: dict = {}
18
+ _type2backend: dict = {}
19
+ _debug_importing = False
20
+
21
+
22
+ def get_backend(tensor) -> "AbstractBackend":
23
+ """
24
+ Takes a correct backend (e.g. numpy backend if tensor is numpy.ndarray) for a tensor.
25
+ If needed, imports package and creates backend
26
+ """
27
+ _type = type(tensor)
28
+ _result = _type2backend.get(_type, None)
29
+ if _result is not None:
30
+ return _result
31
+
32
+ previously_loaded_backends = list(_loaded_backends.items())
33
+ for _framework_name, backend in previously_loaded_backends:
34
+ if backend.is_appropriate_type(tensor):
35
+ _type2backend[_type] = backend
36
+ return backend
37
+
38
+ # Find backend subclasses recursively
39
+ backend_subclasses = []
40
+ backends = AbstractBackend.__subclasses__()
41
+ while backends:
42
+ backend = backends.pop()
43
+ backends += backend.__subclasses__()
44
+ backend_subclasses.append(backend)
45
+
46
+ # handles modification of _loaded_backends from other thread, see #391
47
+ prev_backend_names = [x for x, _ in previously_loaded_backends]
48
+ for BackendSubclass in backend_subclasses:
49
+ if _debug_importing:
50
+ print("Testing for subclass of ", BackendSubclass)
51
+ if BackendSubclass.framework_name not in prev_backend_names:
52
+ # check that module was already imported. Otherwise it can't be imported
53
+ if BackendSubclass.framework_name in sys.modules:
54
+ if _debug_importing:
55
+ print("Imported backend for ", BackendSubclass.framework_name)
56
+ backend = BackendSubclass()
57
+ _loaded_backends[backend.framework_name] = backend
58
+ if backend.is_appropriate_type(tensor):
59
+ _type2backend[_type] = backend
60
+ return backend
61
+
62
+ raise RuntimeError(f"Tensor type unknown to einops {type(tensor)}")
63
+
64
+
65
+ class AbstractBackend:
66
+ """Base backend class, major part of methods are only for debugging purposes."""
67
+
68
+ framework_name: str
69
+
70
+ def is_appropriate_type(self, tensor):
71
+ """helper method should recognize tensors it can handle"""
72
+ raise NotImplementedError()
73
+
74
+ def from_numpy(self, x):
75
+ raise NotImplementedError("framework doesn't support imperative execution")
76
+
77
+ def to_numpy(self, x):
78
+ raise NotImplementedError("framework doesn't support imperative execution")
79
+
80
+ def create_symbol(self, shape):
81
+ raise NotImplementedError("framework doesn't support symbolic computations")
82
+
83
+ def eval_symbol(self, symbol, symbol_value_pairs):
84
+ # symbol-value pairs is list[tuple[symbol, value-tensor]]
85
+ raise NotImplementedError("framework doesn't support symbolic computations")
86
+
87
+ def arange(self, start, stop):
88
+ # supplementary method used only in testing, so should implement CPU version
89
+ raise NotImplementedError("framework doesn't implement arange")
90
+
91
+ def shape(self, x):
92
+ """shape should return a tuple with integers or "shape symbols" (which will evaluate to actual size)"""
93
+ return x.shape
94
+
95
+ def reshape(self, x, shape):
96
+ return x.reshape(shape)
97
+
98
+ def transpose(self, x, axes):
99
+ return x.transpose(axes)
100
+
101
+ def reduce(self, x, operation, axes):
102
+ return getattr(x, operation)(axis=axes)
103
+
104
+ def stack_on_zeroth_dimension(self, tensors: list):
105
+ raise NotImplementedError()
106
+
107
+ def add_axis(self, x, new_position):
108
+ raise NotImplementedError()
109
+
110
+ def add_axes(self, x, n_axes, pos2len):
111
+ repeats = [1] * n_axes
112
+ for axis_position, axis_length in pos2len.items():
113
+ x = self.add_axis(x, axis_position)
114
+ repeats[axis_position] = axis_length
115
+ return self.tile(x, tuple(repeats))
116
+
117
+ def tile(self, x, repeats):
118
+ """repeats - same lengths as x.shape"""
119
+ raise NotImplementedError()
120
+
121
+ def concat(self, tensors, axis: int):
122
+ """concatenates tensors along axis.
123
+ Assume identical across tensors: devices, dtypes and shapes except selected axis."""
124
+ raise NotImplementedError()
125
+
126
+ def is_float_type(self, x):
127
+ # some backends (torch) can't compute average for non-floating types.
128
+ # Decided to drop average for all backends if type is not floating
129
+ raise NotImplementedError()
130
+
131
+ def layers(self):
132
+ raise NotImplementedError("backend does not provide layers")
133
+
134
+ def __repr__(self):
135
+ return f"<einops backend for {self.framework_name}>"
136
+
137
+ def einsum(self, pattern, *x):
138
+ raise NotImplementedError("backend does not support einsum")
139
+
140
+
141
+ class UnknownSize:
142
+ """pseudo-symbol for symbolic frameworks which do not provide symbols for shape elements"""
143
+
144
+ def __floordiv__(self, other):
145
+ return self
146
+
147
+ def __eq__(self, other):
148
+ return True # we don't know actual size
149
+
150
+ def __mul__(self, other):
151
+ return self
152
+
153
+ def __rmul__(self, other):
154
+ return self
155
+
156
+ def __hash__(self):
157
+ return hash(None)
158
+
159
+
160
+ class NumpyBackend(AbstractBackend):
161
+ framework_name = "numpy"
162
+
163
+ def __init__(self):
164
+ import numpy
165
+
166
+ self.np = numpy
167
+
168
+ def is_appropriate_type(self, tensor):
169
+ return isinstance(tensor, self.np.ndarray)
170
+
171
+ def from_numpy(self, x):
172
+ return x
173
+
174
+ def to_numpy(self, x):
175
+ return x
176
+
177
+ def arange(self, start, stop):
178
+ return self.np.arange(start, stop)
179
+
180
+ def stack_on_zeroth_dimension(self, tensors: list):
181
+ return self.np.stack(tensors)
182
+
183
+ def tile(self, x, repeats):
184
+ return self.np.tile(x, repeats)
185
+
186
+ def concat(self, tensors, axis: int):
187
+ return self.np.concatenate(tensors, axis=axis)
188
+
189
+ def is_float_type(self, x):
190
+ return x.dtype in ("float16", "float32", "float64", "float128", "bfloat16")
191
+
192
+ def add_axis(self, x, new_position):
193
+ return self.np.expand_dims(x, new_position)
194
+
195
+ def einsum(self, pattern, *x):
196
+ return self.np.einsum(pattern, *x)
197
+
198
+
199
+ class JaxBackend(NumpyBackend):
200
+ framework_name = "jax"
201
+
202
+ def __init__(self):
203
+ super().__init__()
204
+ self.onp = self.np
205
+
206
+ import jax.numpy
207
+
208
+ self.np = jax.numpy
209
+
210
+ def from_numpy(self, x):
211
+ return self.np.asarray(x)
212
+
213
+ def to_numpy(self, x):
214
+ return self.onp.asarray(x)
215
+
216
+
217
+ class TorchBackend(AbstractBackend):
218
+ framework_name = "torch"
219
+
220
+ def __init__(self):
221
+ import torch
222
+
223
+ self.torch = torch
224
+ # importing would register operations in torch._dynamo for torch.compile
225
+ from . import _torch_specific # noqa
226
+
227
+ def is_appropriate_type(self, tensor):
228
+ return isinstance(tensor, self.torch.Tensor)
229
+
230
+ def from_numpy(self, x):
231
+ variable = self.torch.from_numpy(x)
232
+ if self.is_float_type(variable):
233
+ # attach grad only to floating types
234
+ variable.requires_grad = True
235
+ return variable
236
+
237
+ def to_numpy(self, x):
238
+ return x.detach().cpu().numpy()
239
+
240
+ def arange(self, start, stop):
241
+ return self.torch.arange(start, stop, dtype=self.torch.int64)
242
+
243
+ def reduce(self, x, operation, reduced_axes):
244
+ if operation == "min":
245
+ return x.amin(dim=reduced_axes)
246
+ elif operation == "max":
247
+ return x.amax(dim=reduced_axes)
248
+ elif operation == "sum":
249
+ return x.sum(dim=reduced_axes)
250
+ elif operation == "mean":
251
+ return x.mean(dim=reduced_axes)
252
+ elif operation in ("any", "all", "prod"):
253
+ # pytorch supports reducing only one operation at a time
254
+ for i in sorted(reduced_axes)[::-1]:
255
+ x = getattr(x, operation)(dim=i)
256
+ return x
257
+ else:
258
+ raise NotImplementedError("Unknown reduction ", operation)
259
+
260
+ def transpose(self, x, axes):
261
+ return x.permute(axes)
262
+
263
+ def stack_on_zeroth_dimension(self, tensors: list):
264
+ return self.torch.stack(tensors)
265
+
266
+ def add_axes(self, x, n_axes, pos2len):
267
+ repeats = [-1] * n_axes
268
+ for axis_position, axis_length in pos2len.items():
269
+ x = self.add_axis(x, axis_position)
270
+ repeats[axis_position] = axis_length
271
+ return x.expand(repeats)
272
+
273
+ def tile(self, x, repeats):
274
+ return x.repeat(repeats)
275
+
276
+ def concat(self, tensors, axis: int):
277
+ return self.torch.cat(tensors, dim=axis)
278
+
279
+ def add_axis(self, x, new_position):
280
+ return self.torch.unsqueeze(x, new_position)
281
+
282
+ def is_float_type(self, x):
283
+ return x.dtype in [self.torch.float16, self.torch.float32, self.torch.float64, self.torch.bfloat16]
284
+
285
+ def layers(self):
286
+ from .layers import torch
287
+
288
+ return torch
289
+
290
+ def einsum(self, pattern, *x):
291
+ return self.torch.einsum(pattern, *x)
292
+
293
+
294
+ class CupyBackend(AbstractBackend):
295
+ framework_name = "cupy"
296
+
297
+ def __init__(self):
298
+ import cupy
299
+
300
+ self.cupy = cupy
301
+
302
+ def is_appropriate_type(self, tensor):
303
+ return isinstance(tensor, self.cupy.ndarray)
304
+
305
+ def from_numpy(self, x):
306
+ return self.cupy.asarray(x)
307
+
308
+ def to_numpy(self, x):
309
+ return self.cupy.asnumpy(x)
310
+
311
+ def arange(self, start, stop):
312
+ return self.cupy.arange(start, stop)
313
+
314
+ def stack_on_zeroth_dimension(self, tensors: list):
315
+ return self.cupy.stack(tensors)
316
+
317
+ def tile(self, x, repeats):
318
+ return self.cupy.tile(x, repeats)
319
+
320
+ def concat(self, tensors, axis: int):
321
+ return self.cupy.concatenate(tensors, axis=axis)
322
+
323
+ def add_axis(self, x, new_position):
324
+ return self.cupy.expand_dims(x, new_position)
325
+
326
+ def is_float_type(self, x):
327
+ return x.dtype in ("float16", "float32", "float64", "float128", "bfloat16")
328
+
329
+ def einsum(self, pattern, *x):
330
+ return self.cupy.einsum(pattern, *x)
331
+
332
+
333
+ class HashableTuple:
334
+ """Overcomes non-hashability of symbolic elements"""
335
+
336
+ def __init__(self, elements: tuple):
337
+ self.elements = elements
338
+
339
+ def __iter__(self):
340
+ yield from self.elements
341
+
342
+ def __len__(self):
343
+ return len(self.elements)
344
+
345
+ def __getitem__(self, item):
346
+ return self.elements[item]
347
+
348
+ # default equality and hash is used (True only with itself, hash taken of id)
349
+
350
+
351
+ class TensorflowBackend(AbstractBackend):
352
+ framework_name = "tensorflow"
353
+
354
+ def __init__(self):
355
+ import tensorflow
356
+
357
+ self.tf = tensorflow
358
+
359
+ def is_appropriate_type(self, tensor):
360
+ return isinstance(tensor, (self.tf.Tensor, self.tf.Variable))
361
+
362
+ def from_numpy(self, x):
363
+ assert self.tf.executing_eagerly()
364
+ return self.tf.convert_to_tensor(x)
365
+
366
+ def to_numpy(self, x):
367
+ assert self.tf.executing_eagerly()
368
+ return x.numpy()
369
+
370
+ def arange(self, start, stop):
371
+ return self.tf.range(start, stop)
372
+
373
+ def shape(self, x):
374
+ if self.tf.executing_eagerly():
375
+ return tuple(UnknownSize() if d is None else int(d) for d in x.shape)
376
+ else:
377
+ static_shape = x.shape.as_list()
378
+ tf_shape = self.tf.shape(x)
379
+ # use the static shape where known, otherwise use the TF shape components
380
+ shape = tuple([s or tf_shape[dim] for dim, s in enumerate(static_shape)])
381
+ try:
382
+ hash(shape)
383
+ return shape
384
+ except BaseException:
385
+ # unhashable symbols in shape. Wrap tuple to be hashable.
386
+ return HashableTuple(shape)
387
+
388
+ def reduce(self, x, operation, axes):
389
+ return getattr(self.tf, "reduce_" + operation)(x, axis=axes)
390
+
391
+ def reshape(self, x, shape):
392
+ return self.tf.reshape(x, shape)
393
+
394
+ def transpose(self, x, axes):
395
+ return self.tf.transpose(x, axes)
396
+
397
+ def stack_on_zeroth_dimension(self, tensors: list):
398
+ return self.tf.stack(tensors)
399
+
400
+ def tile(self, x, repeats):
401
+ return self.tf.tile(x, repeats)
402
+
403
+ def concat(self, tensors, axis: int):
404
+ return self.tf.concat(tensors, axis=axis)
405
+
406
+ def add_axis(self, x, new_position):
407
+ return self.tf.expand_dims(x, new_position)
408
+
409
+ def is_float_type(self, x):
410
+ return x.dtype in ("float16", "float32", "float64", "float128", "bfloat16")
411
+
412
+ def layers(self):
413
+ from .layers import tensorflow
414
+
415
+ return tensorflow
416
+
417
+ def einsum(self, pattern, *x):
418
+ return self.tf.einsum(pattern, *x)
419
+
420
+
421
+ class TFKerasBackend(AbstractBackend):
422
+ framework_name = "tensorflow.keras"
423
+
424
+ def __init__(self):
425
+ import tensorflow as tf
426
+
427
+ self.tf = tf
428
+ self.keras = tf.keras
429
+ self.K = tf.keras.backend
430
+
431
+ def is_appropriate_type(self, tensor):
432
+ return self.tf.is_tensor(tensor) and self.K.is_keras_tensor(tensor)
433
+
434
+ def create_symbol(self, shape):
435
+ return self.keras.Input(batch_shape=shape)
436
+
437
+ def eval_symbol(self, symbol, symbol_value_pairs):
438
+ model = self.keras.models.Model([var for (var, _) in symbol_value_pairs], symbol)
439
+ return model.predict_on_batch([val for (_, val) in symbol_value_pairs])
440
+
441
+ def arange(self, start, stop):
442
+ return self.K.arange(start, stop)
443
+
444
+ def shape(self, x):
445
+ shape = self.K.shape(x) # tf tensor
446
+ return HashableTuple(tuple(shape))
447
+
448
+ def reduce(self, x, operation, axes):
449
+ return getattr(self.K, operation)(x, axis=axes)
450
+
451
+ def reshape(self, x, shape):
452
+ return self.K.reshape(x, shape)
453
+
454
+ def transpose(self, x, axes):
455
+ return self.K.permute_dimensions(x, axes)
456
+
457
+ def stack_on_zeroth_dimension(self, tensors: list):
458
+ return self.K.stack(tensors)
459
+
460
+ def tile(self, x, repeats):
461
+ return self.K.tile(x, repeats)
462
+
463
+ def concat(self, tensors, axis: int):
464
+ return self.K.concatenate(tensors, axis=axis)
465
+
466
+ def add_axis(self, x, new_position):
467
+ return self.K.expand_dims(x, new_position)
468
+
469
+ def is_float_type(self, x):
470
+ return "float" in self.K.dtype(x)
471
+
472
+ def layers(self):
473
+ from .layers import keras
474
+
475
+ return keras
476
+
477
+
478
+ class OneFlowBackend(AbstractBackend):
479
+ framework_name = "oneflow"
480
+
481
+ def __init__(self):
482
+ import oneflow as flow
483
+
484
+ self.flow = flow
485
+
486
+ def is_appropriate_type(self, tensor):
487
+ return isinstance(tensor, self.flow.Tensor)
488
+
489
+ def from_numpy(self, x):
490
+ variable = self.flow.from_numpy(x)
491
+ if self.is_float_type(variable):
492
+ # attach grad only to floating types
493
+ variable.requires_grad = True
494
+ return variable
495
+
496
+ def to_numpy(self, x):
497
+ return x.detach().cpu().numpy()
498
+
499
+ def arange(self, start, stop):
500
+ return self.flow.arange(start, stop, dtype=self.flow.int64)
501
+
502
+ def reduce(self, x, operation, reduced_axes):
503
+ for axis in sorted(reduced_axes, reverse=True):
504
+ if operation == "min":
505
+ x, _ = x.min(dim=axis)
506
+ elif operation == "max":
507
+ x, _ = x.max(dim=axis)
508
+ elif operation in ["sum", "mean", "prod", "any", "all"]:
509
+ x = getattr(x, operation)(dim=axis)
510
+ else:
511
+ raise NotImplementedError("Unknown reduction ", operation)
512
+ return x
513
+
514
+ def transpose(self, x, axes):
515
+ return x.permute(axes)
516
+
517
+ def stack_on_zeroth_dimension(self, tensors: list):
518
+ return self.flow.stack(tensors)
519
+
520
+ def add_axes(self, x, n_axes, pos2len):
521
+ repeats = [-1] * n_axes
522
+ for axis_position, axis_length in pos2len.items():
523
+ x = self.add_axis(x, axis_position)
524
+ repeats[axis_position] = axis_length
525
+ return x.expand(*repeats)
526
+
527
+ def tile(self, x, repeats):
528
+ return x.repeat(repeats)
529
+
530
+ def concat(self, tensors, axis: int):
531
+ return self.flow.concat(tensors, dim=axis)
532
+
533
+ def add_axis(self, x, new_position):
534
+ return self.flow.unsqueeze(x, new_position)
535
+
536
+ def is_float_type(self, x):
537
+ return x.dtype in [self.flow.float16, self.flow.float32, self.flow.float64]
538
+
539
+ def layers(self):
540
+ from .layers import oneflow
541
+
542
+ return oneflow
543
+
544
+ def einsum(self, pattern, *x):
545
+ return self.flow.einsum(pattern, *x)
546
+
547
+
548
+ class PaddleBackend(AbstractBackend):
549
+ framework_name = "paddle"
550
+
551
+ def __init__(self):
552
+ import paddle
553
+
554
+ self.paddle = paddle
555
+
556
+ def is_appropriate_type(self, tensor):
557
+ return self.paddle.is_tensor(tensor)
558
+
559
+ def from_numpy(self, x):
560
+ tensor = self.paddle.to_tensor(x)
561
+ tensor.stop_gradient = False
562
+ return tensor
563
+
564
+ def to_numpy(self, x):
565
+ return x.detach().numpy()
566
+
567
+ def arange(self, start, stop):
568
+ return self.paddle.arange(start, stop, dtype=self.paddle.int64)
569
+
570
+ def reduce(self, x, operation, axes):
571
+ if len(axes) == x.ndim:
572
+ # currently paddle returns 1d tensor instead of 0d
573
+ return super().reduce(x, operation, axes).squeeze(0)
574
+ else:
575
+ return super().reduce(x, operation, axes)
576
+
577
+ def transpose(self, x, axes):
578
+ return x.transpose(axes)
579
+
580
+ def add_axes(self, x, n_axes, pos2len):
581
+ repeats = [-1] * n_axes
582
+ for axis_position, axis_length in pos2len.items():
583
+ x = self.add_axis(x, axis_position)
584
+ repeats[axis_position] = axis_length
585
+ return x.expand(repeats)
586
+
587
+ def stack_on_zeroth_dimension(self, tensors: list):
588
+ return self.paddle.stack(tensors)
589
+
590
+ def reshape(self, x, shape):
591
+ return x.reshape(shape)
592
+
593
+ def tile(self, x, repeats):
594
+ return x.tile(repeats)
595
+
596
+ def concat(self, tensors, axis: int):
597
+ return self.paddle.concat(tensors, axis=axis)
598
+
599
+ def add_axis(self, x, new_position):
600
+ return x.unsqueeze(new_position)
601
+
602
+ def is_float_type(self, x):
603
+ return x.dtype in [self.paddle.float16, self.paddle.float32, self.paddle.float64]
604
+
605
+ def layers(self):
606
+ from .layers import paddle
607
+
608
+ return paddle
609
+
610
+ def einsum(self, pattern, *x):
611
+ return self.paddle.einsum(pattern, *x)
612
+
613
+ def shape(self, x):
614
+ return tuple(x.shape)
615
+
616
+
617
+ class TinygradBackend(AbstractBackend):
618
+ framework_name = "tinygrad"
619
+
620
+ def __init__(self):
621
+ import tinygrad
622
+
623
+ self.tinygrad = tinygrad
624
+
625
+ def is_appropriate_type(self, tensor):
626
+ return isinstance(tensor, self.tinygrad.Tensor)
627
+
628
+ def from_numpy(self, x):
629
+ return self.tinygrad.Tensor(x)
630
+
631
+ def to_numpy(self, x):
632
+ return x.numpy()
633
+
634
+ def arange(self, start, stop):
635
+ return self.tinygrad.Tensor.arange(start, stop)
636
+
637
+ def shape(self, x):
638
+ return x.shape
639
+
640
+ def reshape(self, x, shape):
641
+ return x.reshape(shape)
642
+
643
+ def transpose(self, x, axes):
644
+ return x.permute(axes)
645
+
646
+ def reduce(self, x, operation, axes):
647
+ for axis in sorted(axes, reverse=True):
648
+ x = getattr(x, operation)(axis=axis)
649
+ return x
650
+
651
+ def stack_on_zeroth_dimension(self, tensors: list):
652
+ return self.tinygrad.Tensor.stack(tensors)
653
+
654
+ def add_axis(self, x, new_position):
655
+ return x.unsqueeze(new_position)
656
+
657
+ def tile(self, x, repeats):
658
+ return x.repeat(repeats)
659
+
660
+ def concat(self, tensors, axis: int):
661
+ return tensors[0].cat(*tensors[1:], dim=axis) if len(tensors) > 1 else tensors[0]
662
+
663
+ def is_float_type(self, x):
664
+ return self.tinygrad.dtypes.is_float(x.dtype)
665
+
666
+ def einsum(self, pattern, *x):
667
+ return self.tinygrad.Tensor.einsum(pattern, *x)
668
+
669
+
670
+ class PyTensorBackend(AbstractBackend):
671
+ framework_name = "pytensor"
672
+
673
+ def __init__(self):
674
+ from pytensor import tensor
675
+
676
+ self.pt = tensor
677
+
678
+ def is_appropriate_type(self, tensor):
679
+ return isinstance(tensor, self.pt.TensorVariable)
680
+
681
+ def is_float_type(self, x):
682
+ return x.dtype in self.pt.type.float_dtypes
683
+
684
+ def from_numpy(self, x):
685
+ return self.pt.as_tensor(x)
686
+
687
+ def to_numpy(self, x):
688
+ return x.eval() # Will only work if there are no symbolic inputs
689
+
690
+ def create_symbol(self, shape):
691
+ if not isinstance(shape, tuple | list):
692
+ shape = (shape,)
693
+ return self.pt.tensor(shape=shape)
694
+
695
+ def eval_symbol(self, symbol, symbol_value_pairs):
696
+ return symbol.eval(dict(symbol_value_pairs))
697
+
698
+ def arange(self, start, stop):
699
+ return self.pt.arange(start, stop)
700
+
701
+ def shape(self, x):
702
+ # use the static shape dimensions where known
703
+ return tuple(
704
+ static_dim if static_dim is not None else symbolic_dim
705
+ for static_dim, symbolic_dim in zip(x.type.shape, x.shape)
706
+ )
707
+
708
+ def stack_on_zeroth_dimension(self, tensors: list):
709
+ return self.pt.stack(tensors)
710
+
711
+ def tile(self, x, repeats):
712
+ return self.pt.tile(x, repeats)
713
+
714
+ def concat(self, tensors, axis: int):
715
+ return self.pt.concatenate(tensors, axis=axis)
716
+
717
+ def add_axis(self, x, new_position):
718
+ return self.pt.expand_dims(x, new_position)
719
+
720
+ def einsum(self, pattern, *x):
721
+ return self.pt.einsum(pattern, *x)
722
+
723
+
724
+ class MLXBackend(AbstractBackend):
725
+ framework_name = "mlx"
726
+
727
+ def __init__(self):
728
+ import mlx.core as mx
729
+ import numpy as np
730
+
731
+ self.mx = mx
732
+ self.np = np
733
+
734
+ def is_appropriate_type(self, tensor):
735
+ return isinstance(tensor, self.mx.array)
736
+
737
+ def from_numpy(self, x):
738
+ return self.mx.array(x)
739
+
740
+ def to_numpy(self, x):
741
+ if x.dtype == self.mx.bfloat16:
742
+ x = x.astype(self.mx.float32)
743
+ return self.np.array(x)
744
+
745
+ def arange(self, start, stop):
746
+ return self.mx.arange(start, stop)
747
+
748
+ def stack_on_zeroth_dimension(self, tensors: list):
749
+ return self.mx.stack(tensors)
750
+
751
+ def add_axes(self, x, new_position):
752
+ return self.mx.expand_dims(x, new_position)
753
+
754
+ def tile(self, x, repeats):
755
+ return self.mx.tile(x, repeats)
756
+
757
+ def concat(self, tensors, axis: int):
758
+ return self.mx.concatenate(tensors, axis=axis)
759
+
760
+ def is_float_type(self, x):
761
+ return self.mx.issubdtype(x.dtype, self.mx.floating)
762
+
763
+ def einsum(self, pattern, *x):
764
+ return self.mx.einsum(pattern, *x)
lib/python3.11/site-packages/einops/_torch_specific.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Specialization of einops for torch.
3
+
4
+ Unfortunately, torch's jit scripting mechanism isn't strong enough,
5
+ and to have scripting supported at least for layers,
6
+ a number of additional moves is needed.
7
+
8
+ Design of main operations (dynamic resolution by lookup) is unlikely
9
+ to be implemented by torch.jit.script,
10
+ but torch.compile seems to work with operations just fine.
11
+ """
12
+
13
+ import warnings
14
+ from typing import Dict, List, Tuple
15
+
16
+ import torch
17
+
18
+ from einops.einops import TransformRecipe, _reconstruct_from_shape_uncached
19
+
20
+
21
+ class TorchJitBackend:
22
+ """
23
+ Completely static backend that mimics part of normal backend functionality
24
+ but restricted to be within torchscript.
25
+ """
26
+
27
+ @staticmethod
28
+ def reduce(x: torch.Tensor, operation: str, reduced_axes: List[int]):
29
+ if operation == "min":
30
+ return x.amin(dim=reduced_axes)
31
+ elif operation == "max":
32
+ return x.amax(dim=reduced_axes)
33
+ elif operation == "sum":
34
+ return x.sum(dim=reduced_axes)
35
+ elif operation == "mean":
36
+ return x.mean(dim=reduced_axes)
37
+ elif operation == "prod":
38
+ for i in sorted(reduced_axes)[::-1]:
39
+ x = x.prod(dim=i)
40
+ return x
41
+ else:
42
+ raise NotImplementedError("Unknown reduction ", operation)
43
+
44
+ @staticmethod
45
+ def transpose(x, axes: List[int]):
46
+ return x.permute(axes)
47
+
48
+ @staticmethod
49
+ def stack_on_zeroth_dimension(tensors: List[torch.Tensor]):
50
+ return torch.stack(tensors)
51
+
52
+ @staticmethod
53
+ def tile(x, repeats: List[int]):
54
+ return x.repeat(repeats)
55
+
56
+ @staticmethod
57
+ def add_axes(x, n_axes: int, pos2len: Dict[int, int]):
58
+ repeats = [-1] * n_axes
59
+ for axis_position, axis_length in pos2len.items():
60
+ x = torch.unsqueeze(x, axis_position)
61
+ repeats[axis_position] = axis_length
62
+ return x.expand(repeats)
63
+
64
+ @staticmethod
65
+ def is_float_type(x):
66
+ return x.dtype in [torch.float16, torch.float32, torch.float64, torch.bfloat16]
67
+
68
+ @staticmethod
69
+ def shape(x):
70
+ return x.shape
71
+
72
+ @staticmethod
73
+ def reshape(x, shape: List[int]):
74
+ return x.reshape(shape)
75
+
76
+
77
+ # mirrors einops.einops._apply_recipe
78
+ def apply_for_scriptable_torch(
79
+ recipe: TransformRecipe, tensor: torch.Tensor, reduction_type: str, axes_dims: List[Tuple[str, int]]
80
+ ) -> torch.Tensor:
81
+ backend = TorchJitBackend
82
+ (
83
+ init_shapes,
84
+ axes_reordering,
85
+ reduced_axes,
86
+ added_axes,
87
+ final_shapes,
88
+ n_axes_w_added,
89
+ ) = _reconstruct_from_shape_uncached(recipe, backend.shape(tensor), axes_dims=axes_dims)
90
+ if init_shapes is not None:
91
+ tensor = backend.reshape(tensor, init_shapes)
92
+ if axes_reordering is not None:
93
+ tensor = backend.transpose(tensor, axes_reordering)
94
+ if len(reduced_axes) > 0:
95
+ tensor = backend.reduce(tensor, operation=reduction_type, reduced_axes=reduced_axes)
96
+ if len(added_axes) > 0:
97
+ tensor = backend.add_axes(tensor, n_axes=n_axes_w_added, pos2len=added_axes)
98
+ if final_shapes is not None:
99
+ tensor = backend.reshape(tensor, final_shapes)
100
+ return tensor
101
+
102
+
103
+ def allow_ops_in_compiled_graph():
104
+ if hasattr(torch, "__version__") and torch.__version__[0] < "2":
105
+ # torch._dynamo and torch.compile appear in pytorch 2.0
106
+ return
107
+
108
+ if hasattr(torch, "__version__") and torch.__version__ >= "2.8":
109
+ # einops don't need to use allow_in graph for torch 2.8 and above
110
+ return
111
+
112
+ try:
113
+ from torch._dynamo import allow_in_graph
114
+ except ImportError:
115
+ warnings.warn(
116
+ "allow_ops_in_compiled_graph failed to import torch: ensure pytorch >=2.0", ImportWarning, stacklevel=1
117
+ )
118
+ return
119
+
120
+ from .einops import einsum, rearrange, reduce, repeat
121
+ from .packing import pack, unpack
122
+
123
+ allow_in_graph(rearrange)
124
+ allow_in_graph(reduce)
125
+ allow_in_graph(repeat)
126
+ allow_in_graph(einsum)
127
+ allow_in_graph(pack)
128
+ allow_in_graph(unpack)
129
+
130
+ # CF: https://github.com/pytorch/pytorch/blob/2df939aacac68e9621fbd5d876c78d86e72b41e2/torch/_dynamo/__init__.py#L222
131
+ global _ops_were_registered_in_torchdynamo
132
+ _ops_were_registered_in_torchdynamo = True
133
+
134
+
135
+ # module import automatically registers ops in torchdynamo
136
+ allow_ops_in_compiled_graph()
lib/python3.11/site-packages/einops/array_api.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Sequence, Tuple
2
+
3
+ from .einops import EinopsError, Reduction, Tensor, _apply_recipe_array_api, _prepare_transformation_recipe
4
+ from .packing import analyze_pattern, prod
5
+
6
+
7
+ def reduce(tensor: Tensor, pattern: str, reduction: Reduction, **axes_lengths: int) -> Tensor:
8
+ if isinstance(tensor, list):
9
+ if len(tensor) == 0:
10
+ raise TypeError("Einops can't be applied to an empty list")
11
+ xp = tensor[0].__array_namespace__()
12
+ tensor = xp.stack(tensor)
13
+ else:
14
+ xp = tensor.__array_namespace__()
15
+ try:
16
+ hashable_axes_lengths = tuple(axes_lengths.items())
17
+ recipe = _prepare_transformation_recipe(pattern, reduction, axes_names=tuple(axes_lengths), ndim=tensor.ndim)
18
+ return _apply_recipe_array_api(
19
+ xp,
20
+ recipe=recipe,
21
+ tensor=tensor,
22
+ reduction_type=reduction,
23
+ axes_lengths=hashable_axes_lengths,
24
+ )
25
+ except EinopsError as e:
26
+ message = f' Error while processing {reduction}-reduction pattern "{pattern}".'
27
+ if not isinstance(tensor, list):
28
+ message += f"\n Input tensor shape: {tensor.shape}. "
29
+ else:
30
+ message += "\n Input is list. "
31
+ message += f"Additional info: {axes_lengths}."
32
+ raise EinopsError(message + f"\n {e}") from None
33
+
34
+
35
+ def repeat(tensor: Tensor, pattern: str, **axes_lengths) -> Tensor:
36
+ return reduce(tensor, pattern, reduction="repeat", **axes_lengths)
37
+
38
+
39
+ def rearrange(tensor: Tensor, pattern: str, **axes_lengths) -> Tensor:
40
+ return reduce(tensor, pattern, reduction="rearrange", **axes_lengths)
41
+
42
+
43
+ def asnumpy(tensor: Tensor):
44
+ import numpy as np
45
+
46
+ return np.from_dlpack(tensor)
47
+
48
+
49
+ Shape = Tuple
50
+
51
+
52
+ def pack(tensors: Sequence[Tensor], pattern: str) -> Tuple[Tensor, List[Shape]]:
53
+ n_axes_before, n_axes_after, min_axes = analyze_pattern(pattern, "pack")
54
+ xp = tensors[0].__array_namespace__()
55
+
56
+ reshaped_tensors: List[Tensor] = []
57
+ packed_shapes: List[Shape] = []
58
+ for i, tensor in enumerate(tensors):
59
+ shape = tensor.shape
60
+ if len(shape) < min_axes:
61
+ raise EinopsError(
62
+ f"packed tensor #{i} (enumeration starts with 0) has shape {shape}, "
63
+ f"while pattern {pattern} assumes at least {min_axes} axes"
64
+ )
65
+ axis_after_packed_axes = len(shape) - n_axes_after
66
+ packed_shapes.append(shape[n_axes_before:axis_after_packed_axes])
67
+ reshaped_tensors.append(xp.reshape(tensor, (*shape[:n_axes_before], -1, *shape[axis_after_packed_axes:])))
68
+
69
+ return xp.concat(reshaped_tensors, axis=n_axes_before), packed_shapes
70
+
71
+
72
+ def unpack(tensor: Tensor, packed_shapes: List[Shape], pattern: str) -> List[Tensor]:
73
+ xp = tensor.__array_namespace__()
74
+ n_axes_before, n_axes_after, min_axes = analyze_pattern(pattern, opname="unpack")
75
+
76
+ # backend = get_backend(tensor)
77
+ input_shape = tensor.shape
78
+ if len(input_shape) != n_axes_before + 1 + n_axes_after:
79
+ raise EinopsError(f"unpack(..., {pattern}) received input of wrong dim with shape {input_shape}")
80
+
81
+ unpacked_axis: int = n_axes_before
82
+
83
+ lengths_of_composed_axes: List[int] = [-1 if -1 in p_shape else prod(p_shape) for p_shape in packed_shapes]
84
+
85
+ n_unknown_composed_axes = sum(x == -1 for x in lengths_of_composed_axes)
86
+ if n_unknown_composed_axes > 1:
87
+ raise EinopsError(
88
+ f"unpack(..., {pattern}) received more than one -1 in {packed_shapes} and can't infer dimensions"
89
+ )
90
+
91
+ # following manipulations allow to skip some shape verifications
92
+ # and leave it to backends
93
+
94
+ # [[], [2, 3], [4], [-1, 5], [6]] < examples of packed_axis
95
+ # split positions when computed should be
96
+ # [0, 1, 7, 11, N-6 , N ], where N = length of axis
97
+ split_positions = [0] * len(packed_shapes) + [input_shape[unpacked_axis]]
98
+ if n_unknown_composed_axes == 0:
99
+ for i, x in enumerate(lengths_of_composed_axes[:-1]):
100
+ split_positions[i + 1] = split_positions[i] + x
101
+ else:
102
+ unknown_composed_axis: int = lengths_of_composed_axes.index(-1)
103
+ for i in range(unknown_composed_axis):
104
+ split_positions[i + 1] = split_positions[i] + lengths_of_composed_axes[i]
105
+ for j in range(unknown_composed_axis + 1, len(lengths_of_composed_axes))[::-1]:
106
+ split_positions[j] = split_positions[j + 1] - lengths_of_composed_axes[j]
107
+
108
+ shape_start = input_shape[:unpacked_axis]
109
+ shape_end = input_shape[unpacked_axis + 1 :]
110
+ slice_filler = (slice(None, None),) * unpacked_axis
111
+ try:
112
+ return [
113
+ xp.reshape(
114
+ # shortest way slice arbitrary axis
115
+ tensor[(*slice_filler, slice(split_positions[i], split_positions[i + 1]), ...)],
116
+ (*shape_start, *element_shape, *shape_end),
117
+ )
118
+ for i, element_shape in enumerate(packed_shapes)
119
+ ]
120
+ except Exception as e:
121
+ # this hits if there is an error during reshapes, which means passed shapes were incorrect
122
+ raise RuntimeError(
123
+ f'Error during unpack(..., "{pattern}"): could not split axis of size {split_positions[-1]}'
124
+ f" into requested {packed_shapes}"
125
+ ) from e
lib/python3.11/site-packages/einops/einops.py ADDED
@@ -0,0 +1,939 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import itertools
3
+ import string
4
+ import typing
5
+ from collections import OrderedDict
6
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple, TypeVar, Union, cast, overload
7
+
8
+ if typing.TYPE_CHECKING:
9
+ # for docstrings in pycharm
10
+ import numpy as np # noqa E401
11
+
12
+ from . import EinopsError
13
+ from ._backends import get_backend
14
+ from .parsing import AnonymousAxis, ParsedExpression, _ellipsis
15
+
16
+ Tensor = TypeVar("Tensor")
17
+ ReductionCallable = Callable[[Tensor, Tuple[int, ...]], Tensor]
18
+ Reduction = Union[str, ReductionCallable]
19
+ Size = typing.Any
20
+
21
+ _reductions = ("min", "max", "sum", "mean", "prod", "any", "all")
22
+
23
+ # magic integers are required to stay within
24
+ # traceable subset of language
25
+ _unknown_axis_length = -999999
26
+ _expected_axis_length = -99999
27
+
28
+
29
+ def _product(sequence: List[int]) -> int:
30
+ """minimalistic product that works both with numbers and symbols. Supports empty lists"""
31
+ result = 1
32
+ for element in sequence:
33
+ result *= element
34
+ return result
35
+
36
+
37
+ def _reduce_axes(tensor, reduction_type: Reduction, reduced_axes: List[int], backend):
38
+ if callable(reduction_type):
39
+ # custom callable
40
+ return reduction_type(tensor, tuple(reduced_axes))
41
+ else:
42
+ # one of built-in operations
43
+ assert reduction_type in _reductions
44
+ if reduction_type == "mean":
45
+ if not backend.is_float_type(tensor):
46
+ raise NotImplementedError("reduce_mean is not available for non-floating tensors")
47
+ return backend.reduce(tensor, reduction_type, tuple(reduced_axes))
48
+
49
+
50
+ def _optimize_transformation(init_shapes, reduced_axes, axes_reordering, final_shapes):
51
+ # 'collapses' neighboring axes if those participate in the result pattern in the same order
52
+ # TODO add support for added_axes
53
+ assert len(axes_reordering) + len(reduced_axes) == len(init_shapes)
54
+ # joining consecutive axes that will be reduced
55
+ # possibly we can skip this if all backends can optimize this (not sure)
56
+ reduced_axes = tuple(sorted(reduced_axes))
57
+ for i in range(len(reduced_axes) - 1)[::-1]:
58
+ if reduced_axes[i] + 1 == reduced_axes[i + 1]:
59
+ removed_axis = reduced_axes[i + 1]
60
+ removed_length = init_shapes[removed_axis]
61
+ init_shapes = init_shapes[:removed_axis] + init_shapes[removed_axis + 1 :]
62
+ init_shapes[removed_axis - 1] *= removed_length
63
+ reduced_axes = reduced_axes[: i + 1] + tuple(axis - 1 for axis in reduced_axes[i + 2 :])
64
+
65
+ # removing axes that are moved together during reshape
66
+ def build_mapping():
67
+ init_to_final = {}
68
+ for axis in range(len(init_shapes)):
69
+ if axis in reduced_axes:
70
+ init_to_final[axis] = None
71
+ else:
72
+ after_reduction = sum(x is not None for x in init_to_final.values())
73
+ init_to_final[axis] = list(axes_reordering).index(after_reduction)
74
+ return init_to_final
75
+
76
+ init_axis_to_final_axis = build_mapping()
77
+
78
+ for init_axis in range(len(init_shapes) - 1)[::-1]:
79
+ if init_axis_to_final_axis[init_axis] is None:
80
+ continue
81
+ if init_axis_to_final_axis[init_axis + 1] is None:
82
+ continue
83
+ if init_axis_to_final_axis[init_axis] + 1 == init_axis_to_final_axis[init_axis + 1]:
84
+ removed_axis = init_axis + 1
85
+ removed_length = init_shapes[removed_axis]
86
+ removed_axis_after_reduction = sum(x not in reduced_axes for x in range(removed_axis))
87
+
88
+ reduced_axes = tuple(axis if axis < removed_axis else axis - 1 for axis in reduced_axes)
89
+ init_shapes = init_shapes[:removed_axis] + init_shapes[removed_axis + 1 :]
90
+ init_shapes[removed_axis - 1] *= removed_length
91
+ old_reordering = axes_reordering
92
+ axes_reordering = []
93
+ for axis in old_reordering:
94
+ if axis == removed_axis_after_reduction:
95
+ pass
96
+ elif axis < removed_axis_after_reduction:
97
+ axes_reordering.append(axis)
98
+ else:
99
+ axes_reordering.append(axis - 1)
100
+ init_axis_to_final_axis = build_mapping()
101
+
102
+ return init_shapes, reduced_axes, axes_reordering, final_shapes
103
+
104
+
105
+ CookedRecipe = Tuple[Optional[List[int]], Optional[List[int]], List[int], Dict[int, int], Optional[List[int]], int]
106
+
107
+ # Actual type is tuple[tuple[str, int], ...]
108
+ # However torch.jit.script does not "understand" the correct type,
109
+ # and torch_specific will use list version.
110
+ HashableAxesLengths = Tuple[Tuple[str, int], ...]
111
+ FakeHashableAxesLengths = List[Tuple[str, int]]
112
+
113
+
114
+ class TransformRecipe:
115
+ """
116
+ Recipe describes actual computation pathway.
117
+ Recipe can be applied to a tensor or variable.
118
+ """
119
+
120
+ # structure is non-mutable. In future, this can be non-mutable dataclass (python 3.7+)
121
+ # update: pytorch 2.0 torch.jit.script seems to have problems with dataclasses unless they were explicitly provided
122
+
123
+ def __init__(
124
+ self,
125
+ # list of sizes (or just sizes) for elementary axes as they appear in left expression.
126
+ # this is what (after computing unknown parts) will be a shape after first transposition.
127
+ # This does not include any ellipsis dimensions.
128
+ elementary_axes_lengths: List[int],
129
+ # if additional axes are provided, they should be set in prev array
130
+ # This shows mapping from name to position
131
+ axis_name2elementary_axis: Dict[str, int],
132
+ # each dimension in input can help to reconstruct length of one elementary axis
133
+ # or verify one of dimensions. Each element points to element of elementary_axes_lengths.
134
+ input_composition_known_unknown: List[Tuple[List[int], List[int]]],
135
+ # permutation applied to elementary axes, if ellipsis is absent
136
+ axes_permutation: List[int],
137
+ # permutation puts reduced axes in the end, we only need to know the first position.
138
+ first_reduced_axis: int,
139
+ # at which positions which of elementary axes should appear. Axis position -> axis index.
140
+ added_axes: Dict[int, int],
141
+ # ids of axes as they appear in result, again pointers to elementary_axes_lengths,
142
+ # only used to infer result dimensions
143
+ output_composite_axes: List[List[int]],
144
+ ):
145
+ self.elementary_axes_lengths: List[int] = elementary_axes_lengths
146
+ self.axis_name2elementary_axis: Dict[str, int] = axis_name2elementary_axis
147
+ self.input_composition_known_unknown: List[Tuple[List[int], List[int]]] = input_composition_known_unknown
148
+ self.axes_permutation: List[int] = axes_permutation
149
+
150
+ self.first_reduced_axis: int = first_reduced_axis
151
+ self.added_axes: Dict[int, int] = added_axes
152
+ self.output_composite_axes: List[List[int]] = output_composite_axes
153
+
154
+
155
+ def _reconstruct_from_shape_uncached(
156
+ self: TransformRecipe, shape: List[int], axes_dims: FakeHashableAxesLengths
157
+ ) -> CookedRecipe:
158
+ """
159
+ Reconstruct all actual parameters using shape.
160
+ Shape is a tuple that may contain integers, shape symbols (tf, theano) and UnknownSize (tf, previously mxnet)
161
+ known axes can be integers or symbols, but not Nones.
162
+ """
163
+ # magic number
164
+ need_init_reshape = False
165
+
166
+ # last axis is allocated for collapsed ellipsis
167
+ axes_lengths: List[int] = list(self.elementary_axes_lengths)
168
+ for axis, dim in axes_dims:
169
+ axes_lengths[self.axis_name2elementary_axis[axis]] = dim
170
+
171
+ for input_axis, (known_axes, unknown_axes) in enumerate(self.input_composition_known_unknown):
172
+ length = shape[input_axis]
173
+ if len(known_axes) == 0 and len(unknown_axes) == 1:
174
+ # shortcut for the most common case
175
+ axes_lengths[unknown_axes[0]] = length
176
+ continue
177
+
178
+ known_product = 1
179
+ for axis in known_axes:
180
+ known_product *= axes_lengths[axis]
181
+
182
+ if len(unknown_axes) == 0:
183
+ if isinstance(length, int) and isinstance(known_product, int) and length != known_product:
184
+ raise EinopsError(f"Shape mismatch, {length} != {known_product}")
185
+ else:
186
+ # assert len(unknown_axes) == 1, 'this is enforced when recipe is created, so commented out'
187
+ if isinstance(length, int) and isinstance(known_product, int) and length % known_product != 0:
188
+ raise EinopsError(f"Shape mismatch, can't divide axis of length {length} in chunks of {known_product}")
189
+
190
+ unknown_axis = unknown_axes[0]
191
+ inferred_length: int = length // known_product
192
+ axes_lengths[unknown_axis] = inferred_length
193
+
194
+ if len(known_axes) + len(unknown_axes) != 1:
195
+ need_init_reshape = True
196
+
197
+ # at this point all axes_lengths are computed (either have values or variables, but not Nones)
198
+
199
+ # elementary axes are ordered as they appear in input, then all added axes
200
+ init_shapes: Optional[List[int]] = axes_lengths[: len(self.axes_permutation)] if need_init_reshape else None
201
+
202
+ need_final_reshape = False
203
+ final_shapes: List[int] = []
204
+ for grouping in self.output_composite_axes:
205
+ lengths = [axes_lengths[elementary_axis] for elementary_axis in grouping]
206
+ final_shapes.append(_product(lengths))
207
+ if len(lengths) != 1:
208
+ need_final_reshape = True
209
+
210
+ added_axes: Dict[int, int] = {
211
+ pos: axes_lengths[pos_in_elementary] for pos, pos_in_elementary in self.added_axes.items()
212
+ }
213
+
214
+ # this list can be empty
215
+ reduced_axes = list(range(self.first_reduced_axis, len(self.axes_permutation)))
216
+
217
+ n_axes_after_adding_axes = len(added_axes) + len(self.axes_permutation)
218
+
219
+ axes_reordering: Optional[List[int]] = self.axes_permutation
220
+ if self.axes_permutation == list(range(len(self.axes_permutation))):
221
+ axes_reordering = None
222
+
223
+ _final_shapes = final_shapes if need_final_reshape else None
224
+ return init_shapes, axes_reordering, reduced_axes, added_axes, _final_shapes, n_axes_after_adding_axes
225
+
226
+
227
+ _reconstruct_from_shape = functools.lru_cache(1024)(_reconstruct_from_shape_uncached)
228
+
229
+
230
+ def _apply_recipe(
231
+ backend, recipe: TransformRecipe, tensor: Tensor, reduction_type: Reduction, axes_lengths: HashableAxesLengths
232
+ ) -> Tensor:
233
+ # this method implements actual work for all backends for 3 operations
234
+ try:
235
+ init_shapes, axes_reordering, reduced_axes, added_axes, final_shapes, n_axes_w_added = _reconstruct_from_shape(
236
+ recipe, backend.shape(tensor), axes_lengths
237
+ )
238
+ except TypeError:
239
+ # shape or one of passed axes lengths is not hashable (i.e. they are symbols)
240
+ _result = _reconstruct_from_shape_uncached(recipe, backend.shape(tensor), axes_lengths)
241
+ (init_shapes, axes_reordering, reduced_axes, added_axes, final_shapes, n_axes_w_added) = _result
242
+ if init_shapes is not None:
243
+ tensor = backend.reshape(tensor, init_shapes)
244
+ if axes_reordering is not None:
245
+ tensor = backend.transpose(tensor, axes_reordering)
246
+ if len(reduced_axes) > 0:
247
+ tensor = _reduce_axes(tensor, reduction_type=reduction_type, reduced_axes=reduced_axes, backend=backend)
248
+ if len(added_axes) > 0:
249
+ tensor = backend.add_axes(tensor, n_axes=n_axes_w_added, pos2len=added_axes)
250
+ if final_shapes is not None:
251
+ tensor = backend.reshape(tensor, final_shapes)
252
+ return tensor
253
+
254
+
255
+ def _apply_recipe_array_api(
256
+ xp, recipe: TransformRecipe, tensor: Tensor, reduction_type: Reduction, axes_lengths: HashableAxesLengths
257
+ ) -> Tensor:
258
+ # completely-inline implementation
259
+ init_shapes, axes_reordering, reduced_axes, added_axes, final_shapes, n_axes_w_added = _reconstruct_from_shape(
260
+ recipe, tensor.shape, axes_lengths
261
+ )
262
+ if init_shapes is not None:
263
+ tensor = xp.reshape(tensor, init_shapes)
264
+ if axes_reordering is not None:
265
+ tensor = xp.permute_dims(tensor, axes_reordering)
266
+ if len(reduced_axes) > 0:
267
+ if callable(reduction_type):
268
+ # custom callable
269
+ tensor = reduction_type(tensor, tuple(reduced_axes))
270
+ else:
271
+ # one of built-in operations
272
+ assert reduction_type in _reductions
273
+ tensor = getattr(xp, reduction_type)(tensor, axis=tuple(reduced_axes))
274
+ if len(added_axes) > 0:
275
+ # we use broadcasting
276
+ for axis_position, _axis_length in added_axes.items():
277
+ tensor = xp.expand_dims(tensor, axis=axis_position)
278
+
279
+ final_shape = list(tensor.shape)
280
+ for axis_position, axis_length in added_axes.items():
281
+ final_shape[axis_position] = axis_length
282
+
283
+ tensor = xp.broadcast_to(tensor, final_shape)
284
+ if final_shapes is not None:
285
+ tensor = xp.reshape(tensor, final_shapes)
286
+ return tensor
287
+
288
+
289
+ @functools.lru_cache(256)
290
+ def _prepare_transformation_recipe(
291
+ pattern: str,
292
+ operation: Reduction,
293
+ axes_names: Tuple[str, ...],
294
+ ndim: int,
295
+ ) -> TransformRecipe:
296
+ """Perform initial parsing of pattern and provided supplementary info
297
+ axes_lengths is a tuple of tuples (axis_name, axis_length)
298
+ """
299
+ left_str, rght_str = pattern.split("->")
300
+ left = ParsedExpression(left_str)
301
+ rght = ParsedExpression(rght_str)
302
+
303
+ # checking that axes are in agreement - new axes appear only in repeat, while disappear only in reduction
304
+ if not left.has_ellipsis and rght.has_ellipsis:
305
+ raise EinopsError(f"Ellipsis found in right side, but not left side of a pattern {pattern}")
306
+ if left.has_ellipsis and left.has_ellipsis_parenthesized:
307
+ raise EinopsError(f"Ellipsis inside parenthesis in the left side is not allowed: {pattern}")
308
+ if operation == "rearrange":
309
+ if left.has_non_unitary_anonymous_axes or rght.has_non_unitary_anonymous_axes:
310
+ raise EinopsError("Non-unitary anonymous axes are not supported in rearrange (exception is length 1)")
311
+ difference = set.symmetric_difference(left.identifiers, rght.identifiers)
312
+ if len(difference) > 0:
313
+ raise EinopsError(f"Identifiers only on one side of expression (should be on both): {difference}")
314
+ elif operation == "repeat":
315
+ difference = set.difference(left.identifiers, rght.identifiers)
316
+ if len(difference) > 0:
317
+ raise EinopsError(f"Unexpected identifiers on the left side of repeat: {difference}")
318
+ axes_without_size = set.difference(
319
+ {ax for ax in rght.identifiers if not isinstance(ax, AnonymousAxis)},
320
+ {*left.identifiers, *axes_names},
321
+ )
322
+ if len(axes_without_size) > 0:
323
+ raise EinopsError(f"Specify sizes for new axes in repeat: {axes_without_size}")
324
+ elif operation in _reductions or callable(operation):
325
+ difference = set.difference(rght.identifiers, left.identifiers)
326
+ if len(difference) > 0:
327
+ raise EinopsError(f"Unexpected identifiers on the right side of reduce {operation}: {difference}")
328
+ else:
329
+ raise EinopsError(f"Unknown reduction {operation}. Expect one of {_reductions}.")
330
+
331
+ if left.has_ellipsis:
332
+ n_other_dims = len(left.composition) - 1
333
+ if ndim < n_other_dims:
334
+ raise EinopsError(f"Wrong shape: expected >={n_other_dims} dims. Received {ndim}-dim tensor.")
335
+ ellipsis_ndim = ndim - n_other_dims
336
+ ell_axes = [_ellipsis + str(i) for i in range(ellipsis_ndim)]
337
+ left_composition = []
338
+ for composite_axis in left.composition:
339
+ if composite_axis == _ellipsis:
340
+ for axis in ell_axes:
341
+ left_composition.append([axis])
342
+ else:
343
+ left_composition.append(composite_axis)
344
+
345
+ rght_composition = []
346
+ for composite_axis in rght.composition:
347
+ if composite_axis == _ellipsis:
348
+ for axis in ell_axes:
349
+ rght_composition.append([axis])
350
+ else:
351
+ group = []
352
+ for axis in composite_axis:
353
+ if axis == _ellipsis:
354
+ group.extend(ell_axes)
355
+ else:
356
+ group.append(axis)
357
+ rght_composition.append(group)
358
+
359
+ left.identifiers.update(ell_axes)
360
+ left.identifiers.remove(_ellipsis)
361
+ if rght.has_ellipsis:
362
+ rght.identifiers.update(ell_axes)
363
+ rght.identifiers.remove(_ellipsis)
364
+ else:
365
+ if ndim != len(left.composition):
366
+ raise EinopsError(f"Wrong shape: expected {len(left.composition)} dims. Received {ndim}-dim tensor.")
367
+ left_composition = left.composition
368
+ rght_composition = rght.composition
369
+
370
+ # parsing all dimensions to find out lengths
371
+ axis_name2known_length: Dict[Union[str, AnonymousAxis], int] = OrderedDict()
372
+ for composite_axis in left_composition:
373
+ for axis_name in composite_axis:
374
+ if isinstance(axis_name, AnonymousAxis):
375
+ axis_name2known_length[axis_name] = axis_name.value
376
+ else:
377
+ axis_name2known_length[axis_name] = _unknown_axis_length
378
+
379
+ # axis_ids_after_first_reshape = range(len(axis_name2known_length)) at this point
380
+
381
+ repeat_axes_names = []
382
+ for axis_name in rght.identifiers:
383
+ if axis_name not in axis_name2known_length:
384
+ if isinstance(axis_name, AnonymousAxis):
385
+ axis_name2known_length[axis_name] = axis_name.value
386
+ else:
387
+ axis_name2known_length[axis_name] = _unknown_axis_length
388
+ repeat_axes_names.append(axis_name)
389
+
390
+ axis_name2position = {name: position for position, name in enumerate(axis_name2known_length)}
391
+
392
+ # axes provided as kwargs
393
+ for elementary_axis in axes_names:
394
+ if not ParsedExpression.check_axis_name(elementary_axis):
395
+ raise EinopsError("Invalid name for an axis", elementary_axis)
396
+ if elementary_axis not in axis_name2known_length:
397
+ raise EinopsError(f"Axis {elementary_axis} is not used in transform")
398
+ axis_name2known_length[elementary_axis] = _expected_axis_length
399
+
400
+ input_axes_known_unknown = []
401
+ # some shapes are inferred later - all information is prepared for faster inference
402
+ for composite_axis in left_composition:
403
+ known: Set[str] = {axis for axis in composite_axis if axis_name2known_length[axis] != _unknown_axis_length}
404
+ unknown: Set[str] = {axis for axis in composite_axis if axis_name2known_length[axis] == _unknown_axis_length}
405
+ if len(unknown) > 1:
406
+ raise EinopsError(f"Could not infer sizes for {unknown}")
407
+ assert len(unknown) + len(known) == len(composite_axis)
408
+ input_axes_known_unknown.append(
409
+ ([axis_name2position[axis] for axis in known], [axis_name2position[axis] for axis in unknown])
410
+ )
411
+
412
+ axis_position_after_reduction: Dict[str, int] = {}
413
+ for axis_name in itertools.chain(*left_composition):
414
+ if axis_name in rght.identifiers:
415
+ axis_position_after_reduction[axis_name] = len(axis_position_after_reduction)
416
+
417
+ result_axes_grouping: List[List[int]] = [
418
+ [axis_name2position[axis] for axis in composite_axis] for i, composite_axis in enumerate(rght_composition)
419
+ ]
420
+
421
+ ordered_axis_left = list(itertools.chain(*left_composition))
422
+ ordered_axis_rght = list(itertools.chain(*rght_composition))
423
+ reduced_axes = [axis for axis in ordered_axis_left if axis not in rght.identifiers]
424
+ order_after_transposition = [axis for axis in ordered_axis_rght if axis in left.identifiers] + reduced_axes
425
+ axes_permutation = [ordered_axis_left.index(axis) for axis in order_after_transposition]
426
+ added_axes = {
427
+ i: axis_name2position[axis_name]
428
+ for i, axis_name in enumerate(ordered_axis_rght)
429
+ if axis_name not in left.identifiers
430
+ }
431
+
432
+ first_reduced_axis = len(order_after_transposition) - len(reduced_axes)
433
+
434
+ return TransformRecipe(
435
+ elementary_axes_lengths=list(axis_name2known_length.values()),
436
+ axis_name2elementary_axis={axis: axis_name2position[axis] for axis in axes_names},
437
+ input_composition_known_unknown=input_axes_known_unknown,
438
+ axes_permutation=axes_permutation,
439
+ first_reduced_axis=first_reduced_axis,
440
+ added_axes=added_axes,
441
+ output_composite_axes=result_axes_grouping,
442
+ )
443
+
444
+
445
+ def _prepare_recipes_for_all_dims(
446
+ pattern: str, operation: Reduction, axes_names: Tuple[str, ...]
447
+ ) -> Dict[int, TransformRecipe]:
448
+ """
449
+ Internal function, used in layers.
450
+ Layer makes all recipe creation when it is initialized, thus to keep recipes simple we pre-compute for all dims
451
+ """
452
+ left_str, rght_str = pattern.split("->")
453
+ left = ParsedExpression(left_str)
454
+ dims = [len(left.composition)]
455
+ if left.has_ellipsis:
456
+ dims = [len(left.composition) - 1 + ellipsis_dims for ellipsis_dims in range(8)]
457
+ return {ndim: _prepare_transformation_recipe(pattern, operation, axes_names, ndim=ndim) for ndim in dims}
458
+
459
+
460
+ @overload
461
+ def reduce(tensor: List[Tensor], pattern: str, reduction: Reduction, **axes_lengths: Size) -> Tensor: ...
462
+
463
+
464
+ @overload
465
+ def reduce(tensor: Tensor, pattern: str, reduction: Reduction, **axes_lengths: Size) -> Tensor: ...
466
+
467
+
468
+ def reduce(tensor: Union[Tensor, List[Tensor]], pattern: str, reduction: Reduction, **axes_lengths: Size) -> Tensor:
469
+ """
470
+ einops.reduce combines rearrangement and reduction using reader-friendly notation.
471
+
472
+ Some examples:
473
+
474
+ ```python
475
+ >>> x = np.random.randn(100, 32, 64)
476
+
477
+ # perform max-reduction on the first axis
478
+ # Axis t does not appear on RHS - thus we reduced over t
479
+ >>> y = reduce(x, 't b c -> b c', 'max')
480
+
481
+ # same as previous, but using verbose names for axes
482
+ >>> y = reduce(x, 'time batch channel -> batch channel', 'max')
483
+
484
+ # let's pretend now that x is a batch of images
485
+ # with 4 dims: batch=10, height=20, width=30, channel=40
486
+ >>> x = np.random.randn(10, 20, 30, 40)
487
+
488
+ # 2d max-pooling with kernel size = 2 * 2 for image processing
489
+ >>> y1 = reduce(x, 'b c (h1 h2) (w1 w2) -> b c h1 w1', 'max', h2=2, w2=2)
490
+
491
+ # same as previous, using anonymous axes,
492
+ # note: only reduced axes can be anonymous
493
+ >>> y1 = reduce(x, 'b c (h1 2) (w1 2) -> b c h1 w1', 'max')
494
+
495
+ # adaptive 2d max-pooling to 3 * 4 grid,
496
+ # each element is max of 10x10 tile in the original tensor.
497
+ >>> reduce(x, 'b c (h1 h2) (w1 w2) -> b c h1 w1', 'max', h1=3, w1=4).shape
498
+ (10, 20, 3, 4)
499
+
500
+ # Global average pooling
501
+ >>> reduce(x, 'b c h w -> b c', 'mean').shape
502
+ (10, 20)
503
+
504
+ # subtracting mean over batch for each channel;
505
+ # similar to x - np.mean(x, axis=(0, 2, 3), keepdims=True)
506
+ >>> y = x - reduce(x, 'b c h w -> 1 c 1 1', 'mean')
507
+
508
+ # Subtracting per-image mean for each channel
509
+ >>> y = x - reduce(x, 'b c h w -> b c 1 1', 'mean')
510
+
511
+ # same as previous, but using empty compositions
512
+ >>> y = x - reduce(x, 'b c h w -> b c () ()', 'mean')
513
+
514
+ ```
515
+
516
+ Parameters:
517
+ tensor: tensor: tensor of any supported library (e.g. numpy.ndarray, tensorflow, pytorch).
518
+ list of tensors is also accepted, those should be of the same type and shape
519
+ pattern: string, reduction pattern
520
+ reduction: one of available reductions ('min', 'max', 'sum', 'mean', 'prod', 'any', 'all').
521
+ Alternatively, a callable f(tensor, reduced_axes) -> tensor can be provided.
522
+ This allows using various reductions like: np.max, np.nanmean, tf.reduce_logsumexp, torch.var, etc.
523
+ axes_lengths: any additional specifications for dimensions
524
+
525
+ Returns:
526
+ tensor of the same type as input
527
+ """
528
+ try:
529
+ if isinstance(tensor, list):
530
+ if len(tensor) == 0:
531
+ raise TypeError("Rearrange/Reduce/Repeat can't be applied to an empty list")
532
+ backend = get_backend(tensor[0])
533
+ tensor = backend.stack_on_zeroth_dimension(tensor)
534
+ else:
535
+ backend = get_backend(tensor)
536
+
537
+ hashable_axes_lengths = tuple(axes_lengths.items())
538
+ shape = backend.shape(tensor)
539
+ recipe = _prepare_transformation_recipe(pattern, reduction, axes_names=tuple(axes_lengths), ndim=len(shape))
540
+ return _apply_recipe(
541
+ backend, recipe, cast(Tensor, tensor), reduction_type=reduction, axes_lengths=hashable_axes_lengths
542
+ )
543
+ except EinopsError as e:
544
+ message = f' Error while processing {reduction}-reduction pattern "{pattern}".'
545
+ if not isinstance(tensor, list):
546
+ message += f"\n Input tensor shape: {shape}. "
547
+ else:
548
+ message += "\n Input is list. "
549
+ message += f"Additional info: {axes_lengths}."
550
+ raise EinopsError(message + f"\n {e}") from None
551
+
552
+
553
+ @overload
554
+ def rearrange(tensor: List[Tensor], pattern: str, **axes_lengths: Size) -> Tensor: ...
555
+
556
+
557
+ @overload
558
+ def rearrange(tensor: Tensor, pattern: str, **axes_lengths: Size) -> Tensor: ...
559
+
560
+
561
+ def rearrange(tensor: Union[Tensor, List[Tensor]], pattern: str, **axes_lengths: Size) -> Tensor:
562
+ """
563
+ einops.rearrange is a reader-friendly smart element reordering for multidimensional tensors.
564
+ This operation includes functionality of transpose (axes permutation), reshape (view), squeeze, unsqueeze,
565
+ stack, concatenate and other operations.
566
+
567
+ Examples:
568
+
569
+ ```python
570
+ # suppose we have a set of 32 images in "h w c" format (height-width-channel)
571
+ >>> images = [np.random.randn(30, 40, 3) for _ in range(32)]
572
+
573
+ # stack along first (batch) axis, output is a single array
574
+ >>> rearrange(images, 'b h w c -> b h w c').shape
575
+ (32, 30, 40, 3)
576
+
577
+ # stacked and reordered axes to "b c h w" format
578
+ >>> rearrange(images, 'b h w c -> b c h w').shape
579
+ (32, 3, 30, 40)
580
+
581
+ # concatenate images along height (vertical axis), 960 = 32 * 30
582
+ >>> rearrange(images, 'b h w c -> (b h) w c').shape
583
+ (960, 40, 3)
584
+
585
+ # concatenated images along horizontal axis, 1280 = 32 * 40
586
+ >>> rearrange(images, 'b h w c -> h (b w) c').shape
587
+ (30, 1280, 3)
588
+
589
+ # flattened each image into a vector, 3600 = 30 * 40 * 3
590
+ >>> rearrange(images, 'b h w c -> b (c h w)').shape
591
+ (32, 3600)
592
+
593
+ # split each image into 4 smaller (top-left, top-right, bottom-left, bottom-right), 128 = 32 * 2 * 2
594
+ >>> rearrange(images, 'b (h1 h) (w1 w) c -> (b h1 w1) h w c', h1=2, w1=2).shape
595
+ (128, 15, 20, 3)
596
+
597
+ # space-to-depth operation
598
+ >>> rearrange(images, 'b (h h1) (w w1) c -> b h w (c h1 w1)', h1=2, w1=2).shape
599
+ (32, 15, 20, 12)
600
+
601
+ ```
602
+
603
+ When composing axes, C-order enumeration used (consecutive elements have different last axis).
604
+ Find more examples in einops tutorial.
605
+
606
+ Parameters:
607
+ tensor: tensor of any supported library (e.g. numpy.ndarray, tensorflow, pytorch).
608
+ list of tensors is also accepted, those should be of the same type and shape
609
+ pattern: string, rearrangement pattern
610
+ axes_lengths: any additional specifications for dimensions
611
+
612
+ Returns:
613
+ tensor of the same type as input. If possible, a view to the original tensor is returned.
614
+
615
+ """
616
+ return reduce(tensor, pattern, reduction="rearrange", **axes_lengths)
617
+
618
+
619
+ @overload
620
+ def repeat(tensor: List[Tensor], pattern: str, **axes_lengths: Size) -> Tensor: ...
621
+
622
+
623
+ @overload
624
+ def repeat(tensor: Tensor, pattern: str, **axes_lengths: Size) -> Tensor: ...
625
+
626
+
627
+ def repeat(tensor: Union[Tensor, List[Tensor]], pattern: str, **axes_lengths: Size) -> Tensor:
628
+ """
629
+ einops.repeat allows reordering elements and repeating them in arbitrary combinations.
630
+ This operation includes functionality of repeat, tile, and broadcast functions.
631
+
632
+ Examples for repeat operation:
633
+
634
+ ```python
635
+ # a grayscale image (of shape height x width)
636
+ >>> image = np.random.randn(30, 40)
637
+
638
+ # change it to RGB format by repeating in each channel
639
+ >>> repeat(image, 'h w -> h w c', c=3).shape
640
+ (30, 40, 3)
641
+
642
+ # repeat image 2 times along height (vertical axis)
643
+ >>> repeat(image, 'h w -> (repeat h) w', repeat=2).shape
644
+ (60, 40)
645
+
646
+ # repeat image 2 time along height and 3 times along width
647
+ >>> repeat(image, 'h w -> (h2 h) (w3 w)', h2=2, w3=3).shape
648
+ (60, 120)
649
+
650
+ # convert each pixel to a small square 2x2, i.e. upsample an image by 2x
651
+ >>> repeat(image, 'h w -> (h h2) (w w2)', h2=2, w2=2).shape
652
+ (60, 80)
653
+
654
+ # 'pixelate' an image first by downsampling by 2x, then upsampling
655
+ >>> downsampled = reduce(image, '(h h2) (w w2) -> h w', 'mean', h2=2, w2=2)
656
+ >>> repeat(downsampled, 'h w -> (h h2) (w w2)', h2=2, w2=2).shape
657
+ (30, 40)
658
+
659
+ ```
660
+
661
+ When composing axes, C-order enumeration used (consecutive elements have different last axis).
662
+ Find more examples in einops tutorial.
663
+
664
+ Parameters:
665
+ tensor: tensor of any supported library (e.g. numpy.ndarray, tensorflow, pytorch).
666
+ list of tensors is also accepted, those should be of the same type and shape
667
+ pattern: string, rearrangement pattern
668
+ axes_lengths: any additional specifications for dimensions
669
+
670
+ Returns:
671
+ Tensor of the same type as input. If possible, a view to the original tensor is returned.
672
+
673
+ """
674
+ return reduce(tensor, pattern, reduction="repeat", **axes_lengths)
675
+
676
+
677
+ def parse_shape(x: Tensor, pattern: str) -> dict:
678
+ """
679
+ Parse a tensor shape to dictionary mapping axes names to their lengths.
680
+
681
+ ```python
682
+ # Use underscore to skip the dimension in parsing.
683
+ >>> x = np.zeros([2, 3, 5, 7])
684
+ >>> parse_shape(x, 'batch _ h w')
685
+ {'batch': 2, 'h': 5, 'w': 7}
686
+
687
+ # `parse_shape` output can be used to specify axes_lengths for other operations:
688
+ >>> y = np.zeros([700])
689
+ >>> rearrange(y, '(b c h w) -> b c h w', **parse_shape(x, 'b _ h w')).shape
690
+ (2, 10, 5, 7)
691
+
692
+ ```
693
+
694
+ For symbolic frameworks may return symbols, not integers.
695
+
696
+ Parameters:
697
+ x: tensor of any supported framework
698
+ pattern: str, space separated names for axes, underscore means skip axis
699
+
700
+ Returns:
701
+ dict, maps axes names to their lengths
702
+ """
703
+ exp = ParsedExpression(pattern, allow_underscore=True)
704
+ shape = get_backend(x).shape(x)
705
+ if exp.has_composed_axes():
706
+ raise RuntimeError(f"Can't parse shape with composite axes: {pattern} {shape}")
707
+ if len(shape) != len(exp.composition):
708
+ if exp.has_ellipsis:
709
+ if len(shape) < len(exp.composition) - 1:
710
+ raise RuntimeError(f"Can't parse shape with this number of dimensions: {pattern} {shape}")
711
+ else:
712
+ raise RuntimeError(f"Can't parse shape with different number of dimensions: {pattern} {shape}")
713
+ if exp.has_ellipsis:
714
+ ellipsis_idx = exp.composition.index(_ellipsis)
715
+ composition = (
716
+ exp.composition[:ellipsis_idx]
717
+ + ["_"] * (len(shape) - len(exp.composition) + 1)
718
+ + exp.composition[ellipsis_idx + 1 :]
719
+ )
720
+ else:
721
+ composition = exp.composition
722
+ result = {}
723
+ for axes, axis_length in zip(composition, shape): # type: ignore
724
+ # axes either [], or [AnonymousAxis] or ['axis_name']
725
+ if len(axes) == 0:
726
+ if axis_length != 1:
727
+ raise RuntimeError(f"Length of axis is not 1: {pattern} {shape}")
728
+ else:
729
+ [axis] = axes
730
+ if isinstance(axis, str):
731
+ if axis != "_":
732
+ result[axis] = axis_length
733
+ else:
734
+ if axis.value != axis_length:
735
+ raise RuntimeError(f"Length of anonymous axis does not match: {pattern} {shape}")
736
+ return result
737
+
738
+
739
+ # _enumerate_directions is not exposed in the public API
740
+ def _enumerate_directions(x):
741
+ """
742
+ For an n-dimensional tensor, returns tensors to enumerate each axis.
743
+ ```python
744
+ x = np.zeros([2, 3, 4]) # or any other tensor
745
+ i, j, k = _enumerate_directions(x)
746
+ result = i + 2*j + 3*k
747
+ ```
748
+
749
+ `result[i, j, k] = i + 2j + 3k`, and also has the same shape as result
750
+ Works very similarly to numpy.ogrid (open indexing grid)
751
+ """
752
+ backend = get_backend(x)
753
+ shape = backend.shape(x)
754
+ result = []
755
+ for axis_id, axis_length in enumerate(shape):
756
+ shape = [1] * len(shape)
757
+ shape[axis_id] = axis_length
758
+ result.append(backend.reshape(backend.arange(0, axis_length), shape))
759
+ return result
760
+
761
+
762
+ # to avoid importing numpy
763
+ np_ndarray = Any
764
+
765
+
766
+ def asnumpy(tensor: Tensor) -> np_ndarray:
767
+ """
768
+ Convert a tensor of an imperative framework (i.e. numpy/cupy/torch/jax/etc.) to `numpy.ndarray`
769
+
770
+ Parameters:
771
+ tensor: tensor of any known imperative framework
772
+
773
+ Returns:
774
+ `numpy.ndarray`, converted to numpy
775
+ """
776
+ return get_backend(tensor).to_numpy(tensor)
777
+
778
+
779
+ def _validate_einsum_axis_name(axis_name):
780
+ if len(axis_name) == 0:
781
+ raise NotImplementedError("Singleton () axes are not yet supported in einsum.")
782
+ if len(axis_name) > 1:
783
+ raise NotImplementedError("Shape rearrangement is not yet supported in einsum.")
784
+
785
+ axis_name = axis_name[0]
786
+
787
+ if isinstance(axis_name, AnonymousAxis):
788
+ raise NotImplementedError("Anonymous axes are not yet supported in einsum.")
789
+ if len(axis_name) == 0:
790
+ raise RuntimeError("Encountered empty axis name in einsum.")
791
+ if not isinstance(axis_name, str):
792
+ raise RuntimeError("Axis name in einsum must be a string.")
793
+
794
+
795
+ @functools.lru_cache(256)
796
+ def _compactify_pattern_for_einsum(pattern: str) -> str:
797
+ if "->" not in pattern:
798
+ # numpy allows this, so make sure users
799
+ # don't accidentally do something like this.
800
+ raise ValueError("Einsum pattern must contain '->'.")
801
+ lefts_str, right_str = pattern.split("->")
802
+
803
+ lefts = [ParsedExpression(left, allow_underscore=True, allow_duplicates=True) for left in lefts_str.split(",")]
804
+
805
+ right = ParsedExpression(right_str, allow_underscore=True)
806
+
807
+ # Start from 'a' and go up to 'Z'
808
+ output_axis_names = string.ascii_letters
809
+ i = 0
810
+ axis_name_mapping = {}
811
+
812
+ left_patterns = []
813
+ for left in lefts:
814
+ left_pattern = ""
815
+ for raw_axis_name in left.composition:
816
+ if raw_axis_name == _ellipsis:
817
+ left_pattern += "..."
818
+ continue
819
+
820
+ _validate_einsum_axis_name(raw_axis_name)
821
+ axis_name = raw_axis_name[0]
822
+ if axis_name not in axis_name_mapping:
823
+ if i >= len(output_axis_names):
824
+ raise RuntimeError("Too many axes in einsum.")
825
+ axis_name_mapping[axis_name] = output_axis_names[i]
826
+ i += 1
827
+
828
+ left_pattern += axis_name_mapping[axis_name]
829
+ left_patterns.append(left_pattern)
830
+
831
+ compact_pattern = ",".join(left_patterns) + "->"
832
+
833
+ for raw_axis_name in right.composition:
834
+ if raw_axis_name == _ellipsis:
835
+ compact_pattern += "..."
836
+ continue
837
+
838
+ _validate_einsum_axis_name(raw_axis_name)
839
+ axis_name = raw_axis_name[0]
840
+
841
+ if axis_name not in axis_name_mapping:
842
+ raise EinopsError(f"Unknown axis {axis_name} on right side of einsum {pattern}.")
843
+
844
+ compact_pattern += axis_name_mapping[axis_name]
845
+
846
+ return compact_pattern
847
+
848
+
849
+ @typing.overload
850
+ def einsum(tensor: Tensor, pattern: str, /) -> Tensor: ...
851
+
852
+
853
+ @typing.overload
854
+ def einsum(tensor1: Tensor, tensor2: Tensor, pattern: str, /) -> Tensor: ...
855
+
856
+
857
+ @typing.overload
858
+ def einsum(tensor1: Tensor, tensor2: Tensor, tensor3: Tensor, pattern: str, /) -> Tensor: ...
859
+
860
+
861
+ @typing.overload
862
+ def einsum(tensor1: Tensor, tensor2: Tensor, tensor3: Tensor, tensor4: Tensor, pattern: str, /) -> Tensor: ...
863
+
864
+
865
+ def einsum(*tensors_and_pattern: Union[Tensor, str]) -> Tensor:
866
+ r"""
867
+ einops.einsum calls einsum operations with einops-style named
868
+ axes indexing, computing tensor products with an arbitrary
869
+ number of tensors. Unlike typical einsum syntax, here you must
870
+ pass tensors first, and then the pattern.
871
+
872
+ Also, note that rearrange operations such as `"(batch chan) out"`,
873
+ or singleton axes `()`, are not currently supported.
874
+
875
+ Examples:
876
+
877
+ For a given pattern such as:
878
+ ```python
879
+ >>> x, y, z = np.random.randn(3, 20, 20, 20)
880
+ >>> output = einsum(x, y, z, "a b c, c b d, a g k -> a b k")
881
+
882
+ ```
883
+ the following formula is computed:
884
+ ```tex
885
+ output[a, b, k] = \sum_{c, d, g} x[a, b, c] * y[c, b, d] * z[a, g, k]
886
+ ```
887
+ where the summation over `c`, `d`, and `g` is performed
888
+ because those axes names do not appear on the right-hand side.
889
+
890
+ Let's see some additional examples:
891
+ ```python
892
+ # Filter a set of images:
893
+ >>> batched_images = np.random.randn(128, 16, 16)
894
+ >>> filters = np.random.randn(16, 16, 30)
895
+ >>> result = einsum(batched_images, filters,
896
+ ... "batch h w, h w channel -> batch channel")
897
+ >>> result.shape
898
+ (128, 30)
899
+
900
+ # Matrix multiplication, with an unknown input shape:
901
+ >>> batch_shape = (50, 30)
902
+ >>> data = np.random.randn(*batch_shape, 20)
903
+ >>> weights = np.random.randn(10, 20)
904
+ >>> result = einsum(weights, data,
905
+ ... "out_dim in_dim, ... in_dim -> ... out_dim")
906
+ >>> result.shape
907
+ (50, 30, 10)
908
+
909
+ # Matrix trace on a single tensor:
910
+ >>> matrix = np.random.randn(10, 10)
911
+ >>> result = einsum(matrix, "i i ->")
912
+ >>> result.shape
913
+ ()
914
+
915
+ ```
916
+
917
+ Parameters:
918
+ tensors_and_pattern:
919
+ tensors: tensors of any supported library (numpy, tensorflow, pytorch, jax).
920
+ pattern: string, einsum pattern, with commas
921
+ separating specifications for each tensor.
922
+ pattern should be provided after all tensors.
923
+
924
+ Returns:
925
+ Tensor of the same type as input, after processing with einsum.
926
+
927
+ """
928
+ if len(tensors_and_pattern) <= 1:
929
+ raise ValueError(
930
+ "`einops.einsum` takes at minimum two arguments: the tensors (at least one), followed by the pattern."
931
+ )
932
+ pattern = tensors_and_pattern[-1]
933
+ if not isinstance(pattern, str):
934
+ raise ValueError(
935
+ "The last argument passed to `einops.einsum` must be a string, representing the einsum pattern."
936
+ )
937
+ tensors = tensors_and_pattern[:-1]
938
+ pattern = _compactify_pattern_for_einsum(pattern)
939
+ return get_backend(tensors[0]).einsum(pattern, *tensors)
lib/python3.11/site-packages/einops/experimental/__init__.py ADDED
File without changes
lib/python3.11/site-packages/einops/experimental/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (204 Bytes). View file
 
lib/python3.11/site-packages/einops/experimental/__pycache__/indexing.cpython-311.pyc ADDED
Binary file (340 Bytes). View file
 
lib/python3.11/site-packages/einops/experimental/indexing.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """
2
+ This file contained some thoughts on indexing.
3
+
4
+ These ideas were developed further in eindex (separate package).
5
+ """
lib/python3.11/site-packages/einops/layers/__init__.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __author__ = "Alex Rogozhnikov"
2
+
3
+ from typing import Any, Dict
4
+
5
+ from einops import EinopsError
6
+ from einops.einops import TransformRecipe, _apply_recipe, _prepare_recipes_for_all_dims, get_backend
7
+
8
+
9
+ class RearrangeMixin:
10
+ """
11
+ Rearrange layer behaves identically to einops.rearrange operation.
12
+
13
+ :param pattern: str, rearrangement pattern
14
+ :param axes_lengths: any additional specification of dimensions
15
+
16
+ See einops.rearrange for source_examples.
17
+ """
18
+
19
+ def __init__(self, pattern: str, **axes_lengths: Any) -> None:
20
+ super().__init__()
21
+ self.pattern = pattern
22
+ self.axes_lengths = axes_lengths
23
+ # self._recipe = self.recipe() # checking parameters
24
+ self._multirecipe = self.multirecipe()
25
+ self._axes_lengths = tuple(self.axes_lengths.items())
26
+
27
+ def __repr__(self) -> str:
28
+ params = repr(self.pattern)
29
+ for axis, length in self.axes_lengths.items():
30
+ params += f", {axis}={length}"
31
+ return f"{self.__class__.__name__}({params})"
32
+
33
+ def multirecipe(self) -> Dict[int, TransformRecipe]:
34
+ try:
35
+ return _prepare_recipes_for_all_dims(
36
+ self.pattern, operation="rearrange", axes_names=tuple(self.axes_lengths)
37
+ )
38
+ except EinopsError as e:
39
+ raise EinopsError(f" Error while preparing {self!r}\n {e}") from None
40
+
41
+ def _apply_recipe(self, x):
42
+ backend = get_backend(x)
43
+ return _apply_recipe(
44
+ backend=backend,
45
+ recipe=self._multirecipe[len(x.shape)],
46
+ tensor=x,
47
+ reduction_type="rearrange",
48
+ axes_lengths=self._axes_lengths,
49
+ )
50
+
51
+ def __getstate__(self):
52
+ return {"pattern": self.pattern, "axes_lengths": self.axes_lengths}
53
+
54
+ def __setstate__(self, state):
55
+ self.__init__(pattern=state["pattern"], **state["axes_lengths"])
56
+
57
+
58
+ class ReduceMixin:
59
+ """
60
+ Reduce layer behaves identically to einops.reduce operation.
61
+
62
+ :param pattern: str, rearrangement pattern
63
+ :param reduction: one of available reductions ('min', 'max', 'sum', 'mean', 'prod'), case-sensitive
64
+ :param axes_lengths: any additional specification of dimensions
65
+
66
+ See einops.reduce for source_examples.
67
+ """
68
+
69
+ def __init__(self, pattern: str, reduction: str, **axes_lengths: Any):
70
+ super().__init__()
71
+ self.pattern = pattern
72
+ self.reduction = reduction
73
+ self.axes_lengths = axes_lengths
74
+ self._multirecipe = self.multirecipe()
75
+ self._axes_lengths = tuple(self.axes_lengths.items())
76
+
77
+ def __repr__(self):
78
+ params = f"{self.pattern!r}, {self.reduction!r}"
79
+ for axis, length in self.axes_lengths.items():
80
+ params += f", {axis}={length}"
81
+ return f"{self.__class__.__name__}({params})"
82
+
83
+ def multirecipe(self) -> Dict[int, TransformRecipe]:
84
+ try:
85
+ return _prepare_recipes_for_all_dims(
86
+ self.pattern, operation=self.reduction, axes_names=tuple(self.axes_lengths)
87
+ )
88
+ except EinopsError as e:
89
+ raise EinopsError(f" Error while preparing {self!r}\n {e}") from None
90
+
91
+ def _apply_recipe(self, x):
92
+ backend = get_backend(x)
93
+ return _apply_recipe(
94
+ backend=backend,
95
+ recipe=self._multirecipe[len(x.shape)],
96
+ tensor=x,
97
+ reduction_type=self.reduction,
98
+ axes_lengths=self._axes_lengths,
99
+ )
100
+
101
+ def __getstate__(self):
102
+ return {"pattern": self.pattern, "reduction": self.reduction, "axes_lengths": self.axes_lengths}
103
+
104
+ def __setstate__(self, state):
105
+ self.__init__(pattern=state["pattern"], reduction=state["reduction"], **state["axes_lengths"])
lib/python3.11/site-packages/einops/layers/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (6.72 kB). View file
 
lib/python3.11/site-packages/einops/layers/__pycache__/_einmix.cpython-311.pyc ADDED
Binary file (15.4 kB). View file
 
lib/python3.11/site-packages/einops/layers/__pycache__/flax.cpython-311.pyc ADDED
Binary file (5 kB). View file
 
lib/python3.11/site-packages/einops/layers/__pycache__/keras.cpython-311.pyc ADDED
Binary file (462 Bytes). View file
 
lib/python3.11/site-packages/einops/layers/__pycache__/oneflow.cpython-311.pyc ADDED
Binary file (3.59 kB). View file
 
lib/python3.11/site-packages/einops/layers/__pycache__/paddle.cpython-311.pyc ADDED
Binary file (3.53 kB). View file
 
lib/python3.11/site-packages/einops/layers/__pycache__/tensorflow.cpython-311.pyc ADDED
Binary file (5.07 kB). View file
 
lib/python3.11/site-packages/einops/layers/__pycache__/torch.cpython-311.pyc ADDED
Binary file (4.25 kB). View file
 
lib/python3.11/site-packages/einops/layers/_einmix.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import string
2
+ import warnings
3
+ from typing import Any, Dict, List, Optional
4
+
5
+ from einops import EinopsError
6
+ from einops.einops import _product
7
+ from einops.parsing import ParsedExpression, _ellipsis
8
+
9
+
10
+ def _report_axes(axes: set, report_message: str):
11
+ if len(axes) > 0:
12
+ raise EinopsError(report_message.format(axes))
13
+
14
+
15
+ class _EinmixMixin:
16
+ def __init__(self, pattern: str, weight_shape: str, bias_shape: Optional[str] = None, **axes_lengths: Any):
17
+ """
18
+ EinMix - Einstein summation with automated tensor management and axis packing/unpacking.
19
+
20
+ EinMix is a combination of einops and MLP, see tutorial:
21
+ https://github.com/arogozhnikov/einops/blob/main/docs/3-einmix-layer.ipynb
22
+
23
+ Imagine taking einsum with two arguments, one of each input, and one - tensor with weights
24
+ >>> einsum('time batch channel_in, channel_in channel_out -> time batch channel_out', input, weight)
25
+
26
+ This layer manages weights for you, syntax highlights a special role of weight matrix
27
+ >>> EinMix('time batch channel_in -> time batch channel_out', weight_shape='channel_in channel_out')
28
+ But otherwise it is the same einsum under the hood. Plus einops-rearrange.
29
+
30
+ Simple linear layer with a bias term (you have one like that in your framework)
31
+ >>> EinMix('t b cin -> t b cout', weight_shape='cin cout', bias_shape='cout', cin=10, cout=20)
32
+ There is no restriction to mix the last axis. Let's mix along height
33
+ >>> EinMix('h w c-> hout w c', weight_shape='h hout', bias_shape='hout', h=32, hout=32)
34
+ Example of channel-wise multiplication (like one used in normalizations)
35
+ >>> EinMix('t b c -> t b c', weight_shape='c', c=128)
36
+ Multi-head linear layer (each head is own linear layer):
37
+ >>> EinMix('t b (head cin) -> t b (head cout)', weight_shape='head cin cout', ...)
38
+
39
+ ... and yes, you need to specify all dimensions of weight shape/bias shape in parameters.
40
+
41
+ Use cases:
42
+ - when channel dimension is not last, use EinMix, not transposition
43
+ - patch/segment embeddings
44
+ - when need only within-group connections to reduce number of weights and computations
45
+ - next-gen MLPs (follow tutorial link above to learn more!)
46
+ - in general, any time you want to combine linear layer and einops.rearrange
47
+
48
+ Uniform He initialization is applied to weight tensor.
49
+ This accounts for the number of elements mixed and produced.
50
+
51
+ Parameters
52
+ :param pattern: transformation pattern, left side - dimensions of input, right side - dimensions of output
53
+ :param weight_shape: axes of weight. A tensor of this shape is created, stored, and optimized in a layer
54
+ If bias_shape is not specified, bias is not created.
55
+ :param bias_shape: axes of bias added to output. Weights of this shape are created and stored. If `None` (the default), no bias is added.
56
+ :param axes_lengths: dimensions of weight tensor
57
+ """
58
+ super().__init__()
59
+ self.pattern = pattern
60
+ self.weight_shape = weight_shape
61
+ self.bias_shape = bias_shape
62
+ self.axes_lengths = axes_lengths
63
+ self.initialize_einmix(
64
+ pattern=pattern, weight_shape=weight_shape, bias_shape=bias_shape, axes_lengths=axes_lengths
65
+ )
66
+
67
+ def initialize_einmix(self, pattern: str, weight_shape: str, bias_shape: Optional[str], axes_lengths: dict):
68
+ left_pattern, right_pattern = pattern.split("->")
69
+ left = ParsedExpression(left_pattern)
70
+ right = ParsedExpression(right_pattern)
71
+ weight = ParsedExpression(weight_shape)
72
+ _report_axes(
73
+ set.difference(right.identifiers, {*left.identifiers, *weight.identifiers}),
74
+ "Unrecognized identifiers on the right side of EinMix {}",
75
+ )
76
+ if weight.has_ellipsis:
77
+ raise EinopsError("Ellipsis is not supported in weight, as its shape should be fully specified")
78
+ if left.has_ellipsis or right.has_ellipsis:
79
+ if not (left.has_ellipsis and right.has_ellipsis):
80
+ raise EinopsError(f"Ellipsis in EinMix should be on both sides, {pattern}")
81
+ if left.has_ellipsis_parenthesized:
82
+ raise EinopsError(f"Ellipsis on left side can't be in parenthesis, got {pattern}")
83
+ if any(x.has_non_unitary_anonymous_axes for x in [left, right, weight]):
84
+ raise EinopsError("Anonymous axes (numbers) are not allowed in EinMix")
85
+ if "(" in weight_shape or ")" in weight_shape:
86
+ raise EinopsError(f"Parenthesis is not allowed in weight shape: {weight_shape}")
87
+
88
+ pre_reshape_pattern = None
89
+ pre_reshape_lengths = None
90
+ post_reshape_pattern = None
91
+ if any(len(group) != 1 for group in left.composition):
92
+ names: List[str] = []
93
+ for group in left.composition:
94
+ names += group
95
+ names = [name if name != _ellipsis else "..." for name in names]
96
+ composition = " ".join(names)
97
+ pre_reshape_pattern = f"{left_pattern}-> {composition}"
98
+ pre_reshape_lengths = {name: length for name, length in axes_lengths.items() if name in names}
99
+
100
+ if any(len(group) != 1 for group in right.composition) or right.has_ellipsis_parenthesized:
101
+ names = []
102
+ for group in right.composition:
103
+ names += group
104
+ names = [name if name != _ellipsis else "..." for name in names]
105
+ composition = " ".join(names)
106
+ post_reshape_pattern = f"{composition} ->{right_pattern}"
107
+
108
+ self._create_rearrange_layers(pre_reshape_pattern, pre_reshape_lengths, post_reshape_pattern, {})
109
+
110
+ for axis in weight.identifiers:
111
+ if axis not in axes_lengths:
112
+ raise EinopsError(f"Dimension {axis} of weight should be specified")
113
+ _report_axes(
114
+ set.difference(set(axes_lengths), {*left.identifiers, *weight.identifiers}),
115
+ "Axes {} are not used in pattern",
116
+ )
117
+ _report_axes(
118
+ set.difference(weight.identifiers, {*left.identifiers, *right.identifiers}), "Weight axes {} are redundant"
119
+ )
120
+ if len(weight.identifiers) == 0:
121
+ warnings.warn("EinMix: weight has no dimensions (means multiplication by a number)", stacklevel=2)
122
+
123
+ _weight_shape = [axes_lengths[axis] for (axis,) in weight.composition]
124
+ # single output element is a combination of fan_in input elements
125
+ _fan_in = _product([axes_lengths[axis] for (axis,) in weight.composition if axis not in right.identifiers])
126
+ if bias_shape is not None:
127
+ # maybe I should put ellipsis in the beginning for simplicity?
128
+ if not isinstance(bias_shape, str):
129
+ raise EinopsError("bias shape should be string specifying which axes bias depends on")
130
+ bias = ParsedExpression(bias_shape)
131
+ _report_axes(
132
+ set.difference(bias.identifiers, right.identifiers),
133
+ "Bias axes {} not present in output",
134
+ )
135
+ _report_axes(
136
+ set.difference(bias.identifiers, set(axes_lengths)),
137
+ "Sizes not provided for bias axes {}",
138
+ )
139
+
140
+ _bias_shape = []
141
+ used_non_trivial_size = False
142
+ for axes in right.composition:
143
+ if axes == _ellipsis:
144
+ if used_non_trivial_size:
145
+ raise EinopsError("all bias dimensions should go after ellipsis in the output")
146
+ else:
147
+ # handles ellipsis correctly
148
+ for axis in axes:
149
+ if axis == _ellipsis:
150
+ if used_non_trivial_size:
151
+ raise EinopsError("all bias dimensions should go after ellipsis in the output")
152
+ elif axis in bias.identifiers:
153
+ _bias_shape.append(axes_lengths[axis])
154
+ used_non_trivial_size = True
155
+ else:
156
+ _bias_shape.append(1)
157
+ else:
158
+ _bias_shape = None
159
+
160
+ weight_bound = (3 / _fan_in) ** 0.5
161
+ bias_bound = (1 / _fan_in) ** 0.5
162
+ self._create_parameters(_weight_shape, weight_bound, _bias_shape, bias_bound)
163
+
164
+ # rewrite einsum expression with single-letter latin identifiers so that
165
+ # expression will be understood by any framework
166
+ mapped_identifiers = {*left.identifiers, *right.identifiers, *weight.identifiers}
167
+ if _ellipsis in mapped_identifiers:
168
+ mapped_identifiers.remove(_ellipsis)
169
+ mapped_identifiers = sorted(mapped_identifiers)
170
+ mapping2letters = {k: letter for letter, k in zip(string.ascii_lowercase, mapped_identifiers)}
171
+ mapping2letters[_ellipsis] = "..." # preserve ellipsis
172
+
173
+ def write_flat_remapped(axes: ParsedExpression):
174
+ result = []
175
+ for composed_axis in axes.composition:
176
+ if isinstance(composed_axis, list):
177
+ result.extend([mapping2letters[axis] for axis in composed_axis])
178
+ else:
179
+ assert composed_axis == _ellipsis
180
+ result.append("...")
181
+ return "".join(result)
182
+
183
+ self.einsum_pattern: str = (
184
+ f"{write_flat_remapped(left)},{write_flat_remapped(weight)}->{write_flat_remapped(right)}"
185
+ )
186
+
187
+ def _create_rearrange_layers(
188
+ self,
189
+ pre_reshape_pattern: Optional[str],
190
+ pre_reshape_lengths: Optional[Dict],
191
+ post_reshape_pattern: Optional[str],
192
+ post_reshape_lengths: Optional[Dict],
193
+ ):
194
+ raise NotImplementedError("Should be defined in framework implementations")
195
+
196
+ def _create_parameters(self, weight_shape, weight_bound, bias_shape, bias_bound):
197
+ """Shape and implementations"""
198
+ raise NotImplementedError("Should be defined in framework implementations")
199
+
200
+ def __repr__(self):
201
+ params = repr(self.pattern)
202
+ params += f", '{self.weight_shape}'"
203
+ if self.bias_shape is not None:
204
+ params += f", '{self.bias_shape}'"
205
+ for axis, length in self.axes_lengths.items():
206
+ params += f", {axis}={length}"
207
+ return f"{self.__class__.__name__}({params})"
208
+
209
+
210
+ class _EinmixDebugger(_EinmixMixin):
211
+ """Used only to test mixin"""
212
+
213
+ def _create_rearrange_layers(
214
+ self,
215
+ pre_reshape_pattern: Optional[str],
216
+ pre_reshape_lengths: Optional[Dict],
217
+ post_reshape_pattern: Optional[str],
218
+ post_reshape_lengths: Optional[Dict],
219
+ ):
220
+ self.pre_reshape_pattern = pre_reshape_pattern
221
+ self.pre_reshape_lengths = pre_reshape_lengths
222
+ self.post_reshape_pattern = post_reshape_pattern
223
+ self.post_reshape_lengths = post_reshape_lengths
224
+
225
+ def _create_parameters(self, weight_shape, weight_bound, bias_shape, bias_bound):
226
+ self.saved_weight_shape = weight_shape
227
+ self.saved_bias_shape = bias_shape
lib/python3.11/site-packages/einops/layers/flax.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import field
2
+ from typing import Dict, Optional, cast
3
+
4
+ import flax.linen as nn
5
+ import jax
6
+ import jax.numpy as jnp
7
+
8
+ from . import RearrangeMixin, ReduceMixin
9
+ from ._einmix import _EinmixMixin
10
+
11
+ __author__ = "Alex Rogozhnikov"
12
+
13
+
14
+ class Reduce(nn.Module):
15
+ pattern: str
16
+ reduction: str
17
+ sizes: dict = field(default_factory=dict)
18
+
19
+ def setup(self):
20
+ self.reducer = ReduceMixin(self.pattern, self.reduction, **self.sizes)
21
+
22
+ def __call__(self, input):
23
+ return self.reducer._apply_recipe(input)
24
+
25
+
26
+ class Rearrange(nn.Module):
27
+ pattern: str
28
+ sizes: dict = field(default_factory=dict)
29
+
30
+ def setup(self):
31
+ self.rearranger = RearrangeMixin(self.pattern, **self.sizes)
32
+
33
+ def __call__(self, input):
34
+ return self.rearranger._apply_recipe(input)
35
+
36
+
37
+ class EinMix(nn.Module, _EinmixMixin):
38
+ pattern: str
39
+ weight_shape: str
40
+ bias_shape: Optional[str] = None
41
+ sizes: dict = field(default_factory=dict)
42
+
43
+ def setup(self):
44
+ self.initialize_einmix(
45
+ pattern=self.pattern,
46
+ weight_shape=self.weight_shape,
47
+ bias_shape=self.bias_shape,
48
+ axes_lengths=self.sizes,
49
+ )
50
+
51
+ def _create_parameters(self, weight_shape, weight_bound, bias_shape, bias_bound):
52
+ self.weight = self.param("weight", jax.nn.initializers.uniform(weight_bound), weight_shape)
53
+
54
+ if bias_shape is not None:
55
+ self.bias = self.param("bias", jax.nn.initializers.uniform(bias_bound), bias_shape)
56
+ else:
57
+ self.bias = None
58
+
59
+ def _create_rearrange_layers(
60
+ self,
61
+ pre_reshape_pattern: Optional[str],
62
+ pre_reshape_lengths: Optional[Dict],
63
+ post_reshape_pattern: Optional[str],
64
+ post_reshape_lengths: Optional[Dict],
65
+ ):
66
+ self.pre_rearrange = None
67
+ if pre_reshape_pattern is not None:
68
+ self.pre_rearrange = Rearrange(pre_reshape_pattern, sizes=cast(dict, pre_reshape_lengths))
69
+
70
+ self.post_rearrange = None
71
+ if post_reshape_pattern is not None:
72
+ self.post_rearrange = Rearrange(post_reshape_pattern, sizes=cast(dict, post_reshape_lengths))
73
+
74
+ def __call__(self, input):
75
+ if self.pre_rearrange is not None:
76
+ input = self.pre_rearrange(input)
77
+ result = jnp.einsum(self.einsum_pattern, input, self.weight)
78
+ if self.bias is not None:
79
+ result += self.bias
80
+ if self.post_rearrange is not None:
81
+ result = self.post_rearrange(result)
82
+ return result
lib/python3.11/site-packages/einops/layers/keras.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ __author__ = "Alex Rogozhnikov"
2
+
3
+ from einops.layers.tensorflow import EinMix, Rearrange, Reduce
4
+
5
+ keras_custom_objects = {
6
+ Rearrange.__name__: Rearrange,
7
+ Reduce.__name__: Reduce,
8
+ EinMix.__name__: EinMix,
9
+ }
lib/python3.11/site-packages/einops/layers/oneflow.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Optional, cast
2
+
3
+ import oneflow as flow
4
+
5
+ from . import RearrangeMixin, ReduceMixin
6
+ from ._einmix import _EinmixMixin
7
+
8
+ __author__ = "Tianhe Ren & Depeng Liang"
9
+
10
+
11
+ class Rearrange(RearrangeMixin, flow.nn.Module):
12
+ def forward(self, input):
13
+ return self._apply_recipe(input)
14
+
15
+
16
+ class Reduce(ReduceMixin, flow.nn.Module):
17
+ def forward(self, input):
18
+ return self._apply_recipe(input)
19
+
20
+
21
+ class EinMix(_EinmixMixin, flow.nn.Module):
22
+ def _create_parameters(self, weight_shape, weight_bound, bias_shape, bias_bound):
23
+ self.weight = flow.nn.Parameter(
24
+ flow.zeros(weight_shape).uniform_(-weight_bound, weight_bound), requires_grad=True
25
+ )
26
+ if bias_shape is not None:
27
+ self.bias = flow.nn.Parameter(flow.zeros(bias_shape).uniform_(-bias_bound, bias_bound), requires_grad=True)
28
+ else:
29
+ self.bias = None
30
+
31
+ def _create_rearrange_layers(
32
+ self,
33
+ pre_reshape_pattern: Optional[str],
34
+ pre_reshape_lengths: Optional[Dict],
35
+ post_reshape_pattern: Optional[str],
36
+ post_reshape_lengths: Optional[Dict],
37
+ ):
38
+ self.pre_rearrange = None
39
+ if pre_reshape_pattern is not None:
40
+ self.pre_rearrange = Rearrange(pre_reshape_pattern, **cast(dict, pre_reshape_lengths))
41
+
42
+ self.post_rearrange = None
43
+ if post_reshape_pattern is not None:
44
+ self.post_rearrange = Rearrange(post_reshape_pattern, **cast(dict, post_reshape_lengths))
45
+
46
+ def forward(self, input):
47
+ if self.pre_rearrange is not None:
48
+ input = self.pre_rearrange(input)
49
+ result = flow.einsum(self.einsum_pattern, input, self.weight)
50
+ if self.bias is not None:
51
+ result += self.bias
52
+ if self.post_rearrange is not None:
53
+ result = self.post_rearrange(result)
54
+ return result
lib/python3.11/site-packages/einops/layers/paddle.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Optional, cast
2
+
3
+ import paddle
4
+
5
+ from . import RearrangeMixin, ReduceMixin
6
+ from ._einmix import _EinmixMixin
7
+
8
+ __author__ = "PaddlePaddle"
9
+
10
+
11
+ class Rearrange(RearrangeMixin, paddle.nn.Layer):
12
+ def forward(self, input):
13
+ return self._apply_recipe(input)
14
+
15
+
16
+ class Reduce(ReduceMixin, paddle.nn.Layer):
17
+ def forward(self, input):
18
+ return self._apply_recipe(input)
19
+
20
+
21
+ class EinMix(_EinmixMixin, paddle.nn.Layer):
22
+ def _create_parameters(self, weight_shape, weight_bound, bias_shape, bias_bound):
23
+ self.weight = self.create_parameter(
24
+ weight_shape, default_initializer=paddle.nn.initializer.Uniform(-weight_bound, weight_bound)
25
+ )
26
+
27
+ if bias_shape is not None:
28
+ self.bias = self.create_parameter(
29
+ bias_shape, default_initializer=paddle.nn.initializer.Uniform(-bias_bound, bias_bound)
30
+ )
31
+ else:
32
+ self.bias = None
33
+
34
+ def _create_rearrange_layers(
35
+ self,
36
+ pre_reshape_pattern: Optional[str],
37
+ pre_reshape_lengths: Optional[Dict],
38
+ post_reshape_pattern: Optional[str],
39
+ post_reshape_lengths: Optional[Dict],
40
+ ):
41
+ self.pre_rearrange = None
42
+ if pre_reshape_pattern is not None:
43
+ self.pre_rearrange = Rearrange(pre_reshape_pattern, **cast(dict, pre_reshape_lengths))
44
+
45
+ self.post_rearrange = None
46
+ if post_reshape_pattern is not None:
47
+ self.post_rearrange = Rearrange(post_reshape_pattern, **cast(dict, post_reshape_lengths))
48
+
49
+ def forward(self, input):
50
+ if self.pre_rearrange is not None:
51
+ input = self.pre_rearrange(input)
52
+
53
+ result = paddle.einsum(self.einsum_pattern, input, self.weight)
54
+ if self.bias is not None:
55
+ result += self.bias
56
+ if self.post_rearrange is not None:
57
+ result = self.post_rearrange(result)
58
+ return result
lib/python3.11/site-packages/einops/layers/tensorflow.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Comment about tensorflow layers:
3
+ unfortunately instructions on creation of TF layers change constantly,
4
+ and changed way too many times at this point to remember what-compatible-where.
5
+
6
+ Layers in einops==0.7.0 (and several prior versions)
7
+ are compatible with TF 2.13
8
+
9
+ Layers in einops==0.8.0 were re-implemented
10
+ according to official instructions for TF 2.16
11
+
12
+ """
13
+
14
+ from typing import Dict, Optional, cast
15
+
16
+ import tensorflow as tf
17
+ from tensorflow.keras.layers import Layer
18
+
19
+ from . import RearrangeMixin, ReduceMixin
20
+ from ._einmix import _EinmixMixin
21
+
22
+ __author__ = "Alex Rogozhnikov"
23
+
24
+
25
+ class Rearrange(RearrangeMixin, Layer):
26
+ def build(self, input_shape):
27
+ pass # layer does not have any parameters to be initialized
28
+
29
+ def call(self, inputs):
30
+ return self._apply_recipe(inputs)
31
+
32
+ def get_config(self):
33
+ return {"pattern": self.pattern, **self.axes_lengths}
34
+
35
+
36
+ class Reduce(ReduceMixin, Layer):
37
+ def build(self, input_shape):
38
+ pass # layer does not have any parameters to be initialized
39
+
40
+ def call(self, inputs):
41
+ return self._apply_recipe(inputs)
42
+
43
+ def get_config(self):
44
+ return {"pattern": self.pattern, "reduction": self.reduction, **self.axes_lengths}
45
+
46
+
47
+ class EinMix(_EinmixMixin, Layer):
48
+ def _create_parameters(self, weight_shape, weight_bound, bias_shape, bias_bound):
49
+ # this method is called in __init__,
50
+ # but we postpone actual creation to build(), as TF instruction suggests
51
+ self._params = [weight_shape, weight_bound, bias_shape, bias_bound]
52
+
53
+ def _create_rearrange_layers(
54
+ self,
55
+ pre_reshape_pattern: Optional[str],
56
+ pre_reshape_lengths: Optional[Dict],
57
+ post_reshape_pattern: Optional[str],
58
+ post_reshape_lengths: Optional[Dict],
59
+ ):
60
+ self.pre_rearrange = None
61
+ if pre_reshape_pattern is not None:
62
+ self.pre_rearrange = Rearrange(pre_reshape_pattern, **cast(dict, pre_reshape_lengths))
63
+
64
+ self.post_rearrange = None
65
+ if post_reshape_pattern is not None:
66
+ self.post_rearrange = Rearrange(post_reshape_pattern, **cast(dict, post_reshape_lengths))
67
+
68
+ def build(self, input_shape):
69
+ [weight_shape, weight_bound, bias_shape, bias_bound] = self._params
70
+ self.weight = self.add_weight(
71
+ shape=weight_shape,
72
+ initializer=tf.random_uniform_initializer(-weight_bound, weight_bound),
73
+ trainable=True,
74
+ )
75
+
76
+ if bias_shape is not None:
77
+ self.bias = self.add_weight(
78
+ shape=bias_shape,
79
+ initializer=tf.random_uniform_initializer(-bias_bound, bias_bound),
80
+ trainable=True,
81
+ )
82
+ else:
83
+ self.bias = None
84
+
85
+ def call(self, inputs):
86
+ if self.pre_rearrange is not None:
87
+ inputs = self.pre_rearrange(inputs)
88
+ result = tf.einsum(self.einsum_pattern, inputs, self.weight)
89
+ if self.bias is not None:
90
+ result = result + self.bias
91
+ if self.post_rearrange is not None:
92
+ result = self.post_rearrange(result)
93
+ return result
94
+
95
+ def get_config(self):
96
+ return {
97
+ "pattern": self.pattern,
98
+ "weight_shape": self.weight_shape,
99
+ "bias_shape": self.bias_shape,
100
+ **self.axes_lengths,
101
+ }
lib/python3.11/site-packages/einops/layers/torch.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Optional, cast
2
+
3
+ import torch
4
+
5
+ from einops._torch_specific import apply_for_scriptable_torch
6
+
7
+ from . import RearrangeMixin, ReduceMixin
8
+ from ._einmix import _EinmixMixin
9
+
10
+ __author__ = "Alex Rogozhnikov"
11
+
12
+
13
+ class Rearrange(RearrangeMixin, torch.nn.Module):
14
+ def forward(self, input):
15
+ recipe = self._multirecipe[input.ndim]
16
+ return apply_for_scriptable_torch(recipe, input, reduction_type="rearrange", axes_dims=self._axes_lengths)
17
+
18
+ def _apply_recipe(self, x):
19
+ # overriding parent method to prevent it's scripting
20
+ pass
21
+
22
+
23
+ class Reduce(ReduceMixin, torch.nn.Module):
24
+ def forward(self, input):
25
+ recipe = self._multirecipe[input.ndim]
26
+ return apply_for_scriptable_torch(recipe, input, reduction_type=self.reduction, axes_dims=self._axes_lengths)
27
+
28
+ def _apply_recipe(self, x):
29
+ # overriding parent method to prevent it's scripting
30
+ pass
31
+
32
+
33
+ class EinMix(_EinmixMixin, torch.nn.Module):
34
+ def _create_parameters(self, weight_shape, weight_bound, bias_shape, bias_bound):
35
+ self.weight = torch.nn.Parameter(
36
+ torch.zeros(weight_shape).uniform_(-weight_bound, weight_bound), requires_grad=True
37
+ )
38
+ if bias_shape is not None:
39
+ self.bias = torch.nn.Parameter(
40
+ torch.zeros(bias_shape).uniform_(-bias_bound, bias_bound), requires_grad=True
41
+ )
42
+ else:
43
+ self.bias = None
44
+
45
+ def _create_rearrange_layers(
46
+ self,
47
+ pre_reshape_pattern: Optional[str],
48
+ pre_reshape_lengths: Optional[Dict],
49
+ post_reshape_pattern: Optional[str],
50
+ post_reshape_lengths: Optional[Dict],
51
+ ):
52
+ self.pre_rearrange = None
53
+ if pre_reshape_pattern is not None:
54
+ self.pre_rearrange = Rearrange(pre_reshape_pattern, **cast(dict, pre_reshape_lengths))
55
+
56
+ self.post_rearrange = None
57
+ if post_reshape_pattern is not None:
58
+ self.post_rearrange = Rearrange(post_reshape_pattern, **cast(dict, post_reshape_lengths))
59
+
60
+ def forward(self, input):
61
+ if self.pre_rearrange is not None:
62
+ input = self.pre_rearrange(input)
63
+ result = torch.einsum(self.einsum_pattern, input, self.weight)
64
+ if self.bias is not None:
65
+ result += self.bias
66
+ if self.post_rearrange is not None:
67
+ result = self.post_rearrange(result)
68
+ return result
lib/python3.11/site-packages/einops/packing.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import lru_cache
2
+ from typing import List, Sequence, Tuple, TypeVar, Union
3
+
4
+ from einops import EinopsError
5
+ from einops._backends import get_backend
6
+ from einops.parsing import ParsedExpression
7
+
8
+ Tensor = TypeVar("Tensor")
9
+
10
+ Shape = Union[Tuple[int, ...], List[int]]
11
+
12
+
13
+ @lru_cache(maxsize=128)
14
+ def analyze_pattern(pattern: str, opname: str) -> Tuple[int, int, int]:
15
+ # Maybe some validation of identifiers?
16
+ axes = pattern.split()
17
+ axes_set = set(axes)
18
+ if len(axes) != len(axes_set):
19
+ raise EinopsError(f'Duplicates in axes names in {opname}(..., "{pattern}")')
20
+ if "*" not in axes_set:
21
+ raise EinopsError(f'No *-axis in {opname}(..., "{pattern}")')
22
+ for axis in axes:
23
+ if axis != "*":
24
+ is_valid, reason = ParsedExpression.check_axis_name_return_reason(axis)
25
+ if not is_valid:
26
+ raise EinopsError(f'Invalid axis name {axis} in {opname}(..., "{pattern}")')
27
+ n_axes_before = axes.index("*")
28
+ n_axes_after = len(axes) - n_axes_before - 1
29
+ min_axes = n_axes_before + n_axes_after
30
+ return n_axes_before, n_axes_after, min_axes
31
+
32
+
33
+ def pack(tensors: Sequence[Tensor], pattern: str) -> Tuple[Tensor, List[Shape]]:
34
+ """
35
+ Packs several tensors into one.
36
+ See einops tutorial for introduction into packing (and how it replaces stack and concatenation).
37
+
38
+ Parameters:
39
+ tensors: tensors to be packed, can be of different dimensionality
40
+ pattern: pattern that is shared for all inputs and output, e.g. "i j * k" or "batch seq *"
41
+
42
+ Returns:
43
+ (packed_tensor, packed_shapes aka PS)
44
+
45
+ Example:
46
+ ```python
47
+ >>> from numpy import zeros as Z
48
+ >>> inputs = [Z([2, 3, 5]), Z([2, 3, 7, 5]), Z([2, 3, 7, 9, 5])]
49
+ >>> packed, ps = pack(inputs, 'i j * k')
50
+ >>> packed.shape, ps
51
+ ((2, 3, 71, 5), [(), (7,), (7, 9)])
52
+ ```
53
+
54
+ In this example, axes were matched to: i=2, j=3, k=5 based on order (first, second, and last).
55
+ All other axes were 'packed' and concatenated.
56
+ PS (packed shapes) contains information about axes that were matched to '*' in every input.
57
+ Resulting tensor has as many elements as all inputs in total.
58
+
59
+ Packing can be reversed with unpack, which additionally needs PS (packed shapes) to reconstruct order.
60
+
61
+ ```python
62
+ >>> inputs_unpacked = unpack(packed, ps, 'i j * k')
63
+ >>> [x.shape for x in inputs_unpacked]
64
+ [(2, 3, 5), (2, 3, 7, 5), (2, 3, 7, 9, 5)]
65
+ ```
66
+
67
+ Read the tutorial for introduction and application scenarios.
68
+ """
69
+ n_axes_before, n_axes_after, min_axes = analyze_pattern(pattern, "pack")
70
+
71
+ # packing zero tensors is illegal
72
+ backend = get_backend(tensors[0])
73
+
74
+ reshaped_tensors: List[Tensor] = []
75
+ packed_shapes: List[Shape] = []
76
+ for i, tensor in enumerate(tensors):
77
+ shape = backend.shape(tensor)
78
+ if len(shape) < min_axes:
79
+ raise EinopsError(
80
+ f"packed tensor #{i} (enumeration starts with 0) has shape {shape}, "
81
+ f"while pattern {pattern} assumes at least {min_axes} axes"
82
+ )
83
+ axis_after_packed_axes = len(shape) - n_axes_after
84
+ packed_shapes.append(shape[n_axes_before:axis_after_packed_axes])
85
+ reshaped_tensors.append(backend.reshape(tensor, (*shape[:n_axes_before], -1, *shape[axis_after_packed_axes:])))
86
+
87
+ return backend.concat(reshaped_tensors, axis=n_axes_before), packed_shapes
88
+
89
+
90
+ def prod(x: Shape) -> int:
91
+ result = 1
92
+ for i in x:
93
+ result *= i
94
+ return result
95
+
96
+
97
+ def unpack(tensor: Tensor, packed_shapes: List[Shape], pattern: str) -> List[Tensor]:
98
+ """
99
+ Unpacks a single tensor into several by splitting over a selected axes.
100
+ See einops tutorial for introduction into packing (and how it replaces stack and concatenation).
101
+
102
+ Parameters:
103
+ tensor: tensor to be unpacked
104
+ packed_shapes: packed_shapes (aka PS) is a list of shapes that take place of '*' in each output.
105
+ output will contain a single tensor for every provided shape
106
+ pattern: pattern that is shared for input and all outputs, e.g. "i j * k" or "batch seq *",
107
+ where * designates an axis to be unpacked
108
+
109
+ Returns:
110
+ list of tensors
111
+
112
+ If framework supports views, results are views to the original tensor.
113
+
114
+ Example:
115
+ ```python
116
+ >>> from numpy import zeros as Z
117
+ >>> inputs = [Z([2, 3, 5]), Z([2, 3, 7, 5]), Z([2, 3, 7, 9, 5])]
118
+ >>> packed, ps = pack(inputs, 'i j * k')
119
+ >>> packed.shape, ps
120
+ ((2, 3, 71, 5), [(), (7,), (7, 9)])
121
+ ```
122
+
123
+ In this example, axes were matched to: i=2, j=3, k=5 based on order (first, second, and last).
124
+ All other axes were 'packed' and concatenated.
125
+ PS (packed shapes) contains information about axes that were matched to '*' in every input.
126
+ Resulting tensor has as many elements as all inputs in total.
127
+
128
+ Packing can be reversed with unpack, which additionally needs PS (packed shapes) to reconstruct order.
129
+
130
+ ```python
131
+ >>> inputs_unpacked = unpack(packed, ps, 'i j * k')
132
+ >>> [x.shape for x in inputs_unpacked]
133
+ [(2, 3, 5), (2, 3, 7, 5), (2, 3, 7, 9, 5)]
134
+ ```
135
+
136
+ Read the tutorial for introduction and application scenarios.
137
+ """
138
+ n_axes_before, n_axes_after, min_axes = analyze_pattern(pattern, opname="unpack")
139
+
140
+ backend = get_backend(tensor)
141
+ input_shape = backend.shape(tensor)
142
+ if len(input_shape) != n_axes_before + 1 + n_axes_after:
143
+ raise EinopsError(f"unpack(..., {pattern}) received input of wrong dim with shape {input_shape}")
144
+
145
+ unpacked_axis: int = n_axes_before
146
+
147
+ lengths_of_composed_axes: List[int] = [-1 if -1 in p_shape else prod(p_shape) for p_shape in packed_shapes]
148
+
149
+ n_unknown_composed_axes = sum(int(x == -1) for x in lengths_of_composed_axes)
150
+ if n_unknown_composed_axes > 1:
151
+ raise EinopsError(
152
+ f"unpack(..., {pattern}) received more than one -1 in {packed_shapes} and can't infer dimensions"
153
+ )
154
+
155
+ # following manipulations allow to skip some shape verifications
156
+ # and leave it to backends
157
+
158
+ # [[], [2, 3], [4], [-1, 5], [6]] < examples of packed_axis
159
+ # split positions when computed should be
160
+ # [0, 1, 7, 11, N-6 , N ], where N = length of axis
161
+ split_positions = [0] * len(packed_shapes) + [input_shape[unpacked_axis]]
162
+ if n_unknown_composed_axes == 0:
163
+ for i, x in enumerate(lengths_of_composed_axes[:-1]):
164
+ split_positions[i + 1] = split_positions[i] + x
165
+ else:
166
+ unknown_composed_axis: int = lengths_of_composed_axes.index(-1)
167
+ for i in range(unknown_composed_axis):
168
+ split_positions[i + 1] = split_positions[i] + lengths_of_composed_axes[i]
169
+ for j in range(unknown_composed_axis + 1, len(lengths_of_composed_axes))[::-1]:
170
+ split_positions[j] = split_positions[j + 1] - lengths_of_composed_axes[j]
171
+
172
+ shape_start = input_shape[:unpacked_axis]
173
+ shape_end = input_shape[unpacked_axis + 1 :]
174
+ slice_filler = (slice(None, None),) * unpacked_axis
175
+ try:
176
+ return [
177
+ backend.reshape(
178
+ # shortest way slice arbitrary axis
179
+ tensor[(*slice_filler, slice(split_positions[i], split_positions[i + 1]))],
180
+ (*shape_start, *element_shape, *shape_end),
181
+ )
182
+ for i, element_shape in enumerate(packed_shapes)
183
+ ]
184
+ except Exception as e:
185
+ # this hits if there is an error during reshapes, which means passed shapes were incorrect
186
+ raise EinopsError(
187
+ f'Error during unpack(..., "{pattern}"): could not split axis of size {split_positions[-1]}'
188
+ f" into requested {packed_shapes}"
189
+ ) from e
lib/python3.11/site-packages/einops/parsing.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import keyword
2
+ import warnings
3
+ from typing import List, Optional, Set, Tuple, Union
4
+
5
+ from einops import EinopsError
6
+
7
+ _ellipsis: str = "…" # NB, this is a single unicode symbol. String is used as it is not a list, but can be iterated
8
+
9
+
10
+ class AnonymousAxis:
11
+ """Important thing: all instances of this class are not equal to each other"""
12
+
13
+ def __init__(self, value: str):
14
+ self.value = int(value)
15
+ if self.value <= 1:
16
+ if self.value == 1:
17
+ raise EinopsError("No need to create anonymous axis of length 1. Report this as an issue")
18
+ else:
19
+ raise EinopsError(f"Anonymous axis should have positive length, not {self.value}")
20
+
21
+ def __repr__(self):
22
+ return f"{str(self.value)}-axis"
23
+
24
+
25
+ class ParsedExpression:
26
+ """
27
+ non-mutable structure that contains information about one side of expression (e.g. 'b c (h w)')
28
+ and keeps some information important for downstream
29
+ """
30
+
31
+ def __init__(self, expression: str, *, allow_underscore: bool = False, allow_duplicates: bool = False):
32
+ self.has_ellipsis: bool = False
33
+ self.has_ellipsis_parenthesized: Optional[bool] = None
34
+ self.identifiers: Set[str] = set()
35
+ # that's axes like 2, 3, 4 or 5. Axes with size 1 are exceptional and replaced with empty composition
36
+ self.has_non_unitary_anonymous_axes: bool = False
37
+ # composition keeps structure of composite axes, see how different corner cases are handled in tests
38
+ self.composition: List[Union[List[str], str]] = []
39
+ if "." in expression:
40
+ if "..." not in expression:
41
+ raise EinopsError("Expression may contain dots only inside ellipsis (...)")
42
+ if str.count(expression, "...") != 1 or str.count(expression, ".") != 3:
43
+ raise EinopsError(
44
+ "Expression may contain dots only inside ellipsis (...); only one ellipsis for tensor "
45
+ )
46
+ expression = expression.replace("...", _ellipsis)
47
+ self.has_ellipsis = True
48
+
49
+ bracket_group: Optional[List[str]] = None
50
+
51
+ def add_axis_name(x):
52
+ if x in self.identifiers:
53
+ if not (allow_underscore and x == "_") and not allow_duplicates:
54
+ raise EinopsError(f'Indexing expression contains duplicate dimension "{x}"')
55
+ if x == _ellipsis:
56
+ self.identifiers.add(_ellipsis)
57
+ if bracket_group is None:
58
+ self.composition.append(_ellipsis)
59
+ self.has_ellipsis_parenthesized = False
60
+ else:
61
+ bracket_group.append(_ellipsis)
62
+ self.has_ellipsis_parenthesized = True
63
+ else:
64
+ is_number = str.isdecimal(x)
65
+ if is_number and int(x) == 1:
66
+ # handling the case of anonymous axis of length 1
67
+ if bracket_group is None:
68
+ self.composition.append([])
69
+ else:
70
+ pass # no need to think about 1s inside parenthesis
71
+ return
72
+ is_axis_name, reason = self.check_axis_name_return_reason(x, allow_underscore=allow_underscore)
73
+ if not (is_number or is_axis_name):
74
+ raise EinopsError(f"Invalid axis identifier: {x}\n{reason}")
75
+ if is_number:
76
+ x = AnonymousAxis(x)
77
+ self.identifiers.add(x)
78
+ if is_number:
79
+ self.has_non_unitary_anonymous_axes = True
80
+ if bracket_group is None:
81
+ self.composition.append([x])
82
+ else:
83
+ bracket_group.append(x)
84
+
85
+ current_identifier = None
86
+ for char in expression:
87
+ if char in "() ":
88
+ if current_identifier is not None:
89
+ add_axis_name(current_identifier)
90
+ current_identifier = None
91
+ if char == "(":
92
+ if bracket_group is not None:
93
+ raise EinopsError("Axis composition is one-level (brackets inside brackets not allowed)")
94
+ bracket_group = []
95
+ elif char == ")":
96
+ if bracket_group is None:
97
+ raise EinopsError("Brackets are not balanced")
98
+ self.composition.append(bracket_group)
99
+ bracket_group = None
100
+ elif str.isalnum(char) or char in ["_", _ellipsis]:
101
+ if current_identifier is None:
102
+ current_identifier = char
103
+ else:
104
+ current_identifier += char
105
+ else:
106
+ raise EinopsError(f"Unknown character '{char}'")
107
+
108
+ if bracket_group is not None:
109
+ raise EinopsError(f'Imbalanced parentheses in expression: "{expression}"')
110
+ if current_identifier is not None:
111
+ add_axis_name(current_identifier)
112
+
113
+ def flat_axes_order(self) -> List:
114
+ result = []
115
+ for composed_axis in self.composition:
116
+ assert isinstance(composed_axis, list), "does not work with ellipsis"
117
+ for axis in composed_axis:
118
+ result.append(axis)
119
+ return result
120
+
121
+ def has_composed_axes(self) -> bool:
122
+ # this will ignore 1 inside brackets
123
+ for axes in self.composition:
124
+ if isinstance(axes, list) and len(axes) > 1:
125
+ return True
126
+ return False
127
+
128
+ @staticmethod
129
+ def check_axis_name_return_reason(name: str, allow_underscore: bool = False) -> Tuple[bool, str]:
130
+ if not str.isidentifier(name):
131
+ return False, "not a valid python identifier"
132
+ elif name[0] == "_" or name[-1] == "_":
133
+ if name == "_" and allow_underscore:
134
+ return True, ""
135
+ return False, "axis name should should not start or end with underscore"
136
+ else:
137
+ if keyword.iskeyword(name):
138
+ warnings.warn(
139
+ f"It is discouraged to use axes names that are keywords: {name}",
140
+ RuntimeWarning,
141
+ stacklevel=2,
142
+ )
143
+ if name in ["axis"]:
144
+ warnings.warn(
145
+ "It is discouraged to use 'axis' as an axis name and will raise an error in future",
146
+ FutureWarning,
147
+ stacklevel=2,
148
+ )
149
+ return True, ""
150
+
151
+ @staticmethod
152
+ def check_axis_name(name: str) -> bool:
153
+ """
154
+ Valid axes names are python identifiers except keywords,
155
+ and additionally should not start or end with underscore
156
+ """
157
+ is_valid, _reason = ParsedExpression.check_axis_name_return_reason(name)
158
+ return is_valid
lib/python3.11/site-packages/einops/py.typed ADDED
File without changes
lib/python3.11/site-packages/einops/tests/__init__.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Common utils for testing.
3
+ These functions allow testing only some frameworks, not all.
4
+ """
5
+
6
+ import logging
7
+ import os
8
+ import warnings
9
+ from functools import lru_cache
10
+ from typing import List, Tuple
11
+
12
+ from einops import _backends
13
+
14
+ __author__ = "Alex Rogozhnikov"
15
+
16
+
17
+ # minimize noise in tests logging
18
+ logging.getLogger("tensorflow").disabled = True
19
+ logging.getLogger("matplotlib").disabled = True
20
+
21
+ FLOAT_REDUCTIONS = ("min", "max", "sum", "mean", "prod") # not includes any/all
22
+
23
+
24
+ def find_names_of_all_frameworks() -> List[str]:
25
+ backend_subclasses = []
26
+ backends = _backends.AbstractBackend.__subclasses__()
27
+ while backends:
28
+ backend = backends.pop()
29
+ backends += backend.__subclasses__()
30
+ backend_subclasses.append(backend)
31
+ return [b.framework_name for b in backend_subclasses]
32
+
33
+
34
+ ENVVAR_NAME = "EINOPS_TEST_BACKENDS"
35
+
36
+
37
+ def unparse_backends(backend_names: List[str]) -> Tuple[str, str]:
38
+ _known_backends = find_names_of_all_frameworks()
39
+ for backend_name in backend_names:
40
+ if backend_name not in _known_backends:
41
+ raise RuntimeError(f"Unknown framework: {backend_name}")
42
+ return ENVVAR_NAME, ",".join(backend_names)
43
+
44
+
45
+ @lru_cache(maxsize=1)
46
+ def parse_backends_to_test() -> List[str]:
47
+ if ENVVAR_NAME not in os.environ:
48
+ raise RuntimeError(f"Testing frameworks were not specified, env var {ENVVAR_NAME} not set")
49
+ parsed_backends = os.environ[ENVVAR_NAME].split(",")
50
+ _known_backends = find_names_of_all_frameworks()
51
+ for backend_name in parsed_backends:
52
+ if backend_name not in _known_backends:
53
+ raise RuntimeError(f"Unknown framework: {backend_name}")
54
+
55
+ return parsed_backends
56
+
57
+
58
+ def is_backend_tested(backend: str) -> bool:
59
+ """Used to skip test if corresponding backend is not tested"""
60
+ if backend not in find_names_of_all_frameworks():
61
+ raise RuntimeError(f"Unknown framework {backend}")
62
+ return backend in parse_backends_to_test()
63
+
64
+
65
+ def collect_test_backends(symbolic=False, layers=False) -> List[_backends.AbstractBackend]:
66
+ """
67
+ :param symbolic: symbolic or imperative frameworks?
68
+ :param layers: layers or operations?
69
+ :return: list of backends satisfying set conditions
70
+ """
71
+ if not symbolic:
72
+ if not layers:
73
+ backend_types = [
74
+ _backends.NumpyBackend,
75
+ _backends.JaxBackend,
76
+ _backends.TorchBackend,
77
+ _backends.TensorflowBackend,
78
+ _backends.OneFlowBackend,
79
+ _backends.PaddleBackend,
80
+ _backends.CupyBackend,
81
+ ]
82
+ else:
83
+ backend_types = [
84
+ _backends.TorchBackend,
85
+ _backends.OneFlowBackend,
86
+ _backends.PaddleBackend,
87
+ ]
88
+ else:
89
+ if not layers:
90
+ backend_types = [
91
+ _backends.PyTensorBackend,
92
+ ]
93
+ else:
94
+ backend_types = [
95
+ _backends.TFKerasBackend,
96
+ ]
97
+
98
+ backend_names_to_test = parse_backends_to_test()
99
+ result = []
100
+ for backend_type in backend_types:
101
+ if backend_type.framework_name not in backend_names_to_test:
102
+ continue
103
+ try:
104
+ result.append(backend_type())
105
+ except ImportError:
106
+ # problem with backend installation fails a specific test function,
107
+ # but will be skipped in all other test cases
108
+ warnings.warn(f"backend could not be initialized for tests: {backend_type}", stacklevel=1)
109
+ return result
lib/python3.11/site-packages/einops/tests/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (4.88 kB). View file