tensorguard 0.1.2__tar.gz → 1.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. tensorguard-1.0.1/LICENSE +202 -0
  2. tensorguard-1.0.1/PKG-INFO +96 -0
  3. {tensorguard-0.1.2 → tensorguard-1.0.1}/README.md +3 -0
  4. {tensorguard-0.1.2 → tensorguard-1.0.1}/setup.py +9 -3
  5. tensorguard-1.0.1/tensorguard/__init__.py +189 -0
  6. {tensorguard-0.1.2 → tensorguard-1.0.1}/tensorguard/tools.py +8 -3
  7. tensorguard-1.0.1/tensorguard.egg-info/PKG-INFO +96 -0
  8. {tensorguard-0.1.2 → tensorguard-1.0.1}/tensorguard.egg-info/SOURCES.txt +1 -1
  9. tensorguard-1.0.1/test-requirements.txt +4 -0
  10. {tensorguard-0.1.2 → tensorguard-1.0.1}/tests/test_global_accessors.py +10 -5
  11. {tensorguard-0.1.2 → tensorguard-1.0.1}/tests/test_guard.py +14 -1
  12. {tensorguard-0.1.2 → tensorguard-1.0.1}/tests/test_match.py +10 -1
  13. tensorguard-0.1.2/PKG-INFO +0 -76
  14. tensorguard-0.1.2/tensorguard/__init__.py +0 -105
  15. tensorguard-0.1.2/tensorguard.egg-info/PKG-INFO +0 -76
  16. tensorguard-0.1.2/test-requirements.txt +0 -4
  17. tensorguard-0.1.2/tests/__init__.py +0 -11
  18. {tensorguard-0.1.2 → tensorguard-1.0.1}/MANIFEST.in +0 -0
  19. {tensorguard-0.1.2 → tensorguard-1.0.1}/requirements.txt +0 -0
  20. {tensorguard-0.1.2 → tensorguard-1.0.1}/setup.cfg +0 -0
  21. {tensorguard-0.1.2 → tensorguard-1.0.1}/tensorguard/dim_specs.py +0 -0
  22. {tensorguard-0.1.2 → tensorguard-1.0.1}/tensorguard/exception.py +0 -0
  23. {tensorguard-0.1.2 → tensorguard-1.0.1}/tensorguard/guard.py +0 -0
  24. {tensorguard-0.1.2 → tensorguard-1.0.1}/tensorguard/parser.py +0 -0
  25. {tensorguard-0.1.2 → tensorguard-1.0.1}/tensorguard/shape_spec.py +0 -0
  26. {tensorguard-0.1.2 → tensorguard-1.0.1}/tensorguard/shape_spec_parser.py +0 -0
  27. {tensorguard-0.1.2 → tensorguard-1.0.1}/tensorguard.egg-info/dependency_links.txt +0 -0
  28. {tensorguard-0.1.2 → tensorguard-1.0.1}/tensorguard.egg-info/requires.txt +0 -0
  29. {tensorguard-0.1.2 → tensorguard-1.0.1}/tensorguard.egg-info/top_level.txt +0 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.4
2
+ Name: tensorguard
3
+ Version: 1.0.1
4
+ Summary: TensorGuard helps to guard against bad Tensor Shapes
5
+ Home-page: https://github.com/Michedev/tensorguard
6
+ Author: mikedev
7
+ Author-email: mik3dev@gmail.com
8
+ License: Apache-2.0
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.6
16
+ Classifier: Programming Language :: Python :: 3.7
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: Implementation :: CPython
24
+ Requires-Python: >=3.6
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: typing_extensions>=3.7.4.3
28
+ Dynamic: author
29
+ Dynamic: author-email
30
+ Dynamic: classifier
31
+ Dynamic: description
32
+ Dynamic: description-content-type
33
+ Dynamic: home-page
34
+ Dynamic: license
35
+ Dynamic: license-file
36
+ Dynamic: requires-dist
37
+ Dynamic: requires-python
38
+ Dynamic: summary
39
+
40
+ # Tensor Guard
41
+ <img src="https://github.com/user-attachments/assets/dfddbe05-87e5-48df-8608-e25bf6087044" alt="tensorguard logo" width="300">
42
+
43
+ [![PyPI version fury.io](https://badge.fury.io/py/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
44
+ [![PyPI pyversions](https://img.shields.io/pypi/pyversions/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
45
+ [![PyPI download month](https://img.shields.io/pypi/dm/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
46
+ [![GitHub followers](https://img.shields.io/github/followers/Michedev.svg?style=social&label=Follow&maxAge=2592000)](https://github.com/Michedev?tab=followers)
47
+
48
+ ---
49
+
50
+ TensorGuard helps to guard against bad Tensor shapes in any tensor based library (e.g. Numpy, Pytorch, Tensorflow) using an intuitive symbolic-based syntax
51
+
52
+ ### Installation
53
+ `pip install tensorguard`
54
+
55
+
56
+ ## Basic Usage
57
+
58
+ ```python
59
+ import numpy as np # could be tensorflow or torch as well
60
+ import tensorguard as tg
61
+
62
+ # tensorguard = tg.TensorGuard() #could be done in a OOP fashion
63
+ img = np.ones([64, 32, 32, 3])
64
+ flat_img = np.ones([64, 1024])
65
+ labels = np.ones([64])
66
+
67
+ # check shape consistency
68
+ tg.guard(img, "B, H, W, C")
69
+ tg.guard(labels, "B, 1") # raises error because of rank mismatch
70
+ tg.guard(flat_img, "B, H*W*C") # raises error because 1024 != 32*32*3
71
+
72
+ # guard also returns the tensor, so it can be inlined
73
+ mean_img = tg.guard(np.mean(img, axis=0), "H, W, C")
74
+
75
+ # more readable reshapes
76
+ flat_img = tg.reshape(img, 'B, H*W*C')
77
+
78
+ # evaluate templates
79
+ assert tg.get_dims('H, W*C+1') == [32, 97]
80
+
81
+ ```
82
+
83
+
84
+ ## Shape Template Syntax
85
+ The shape template mini-DSL supports many different ways of specifying shapes:
86
+
87
+ * numbers: `"64, 32, 32, 3"`
88
+ * named dimensions: `"B, width, height2, channels"`
89
+ * wildcards: `"B, *, *, *"`
90
+ * ellipsis: `"B, ..., 3"`
91
+ * addition, subtraction, multiplication, division: `"B*N, W/2, H*(C+1)"`
92
+ * dynamic dimensions: `"?, H, W, C"` *(only matches `[None, H, W, C]`)*
93
+
94
+
95
+
96
+ ### Original Repo link: https://github.com/Qwlouse/shapeguard
@@ -1,10 +1,13 @@
1
1
  # Tensor Guard
2
+ <img src="https://github.com/user-attachments/assets/dfddbe05-87e5-48df-8608-e25bf6087044" alt="tensorguard logo" width="300">
2
3
 
3
4
  [![PyPI version fury.io](https://badge.fury.io/py/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
4
5
  [![PyPI pyversions](https://img.shields.io/pypi/pyversions/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
5
6
  [![PyPI download month](https://img.shields.io/pypi/dm/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
6
7
  [![GitHub followers](https://img.shields.io/github/followers/Michedev.svg?style=social&label=Follow&maxAge=2592000)](https://github.com/Michedev?tab=followers)
7
8
 
9
+ ---
10
+
8
11
  TensorGuard helps to guard against bad Tensor shapes in any tensor based library (e.g. Numpy, Pytorch, Tensorflow) using an intuitive symbolic-based syntax
9
12
 
10
13
  ### Installation
@@ -12,8 +12,8 @@ with open(ROOT / 'requirements.txt') as f:
12
12
  with open(ROOT / 'README.md') as f:
13
13
  readme = f.read()
14
14
 
15
- class PytestCmd(cmd.Command):
16
15
 
16
+ class PytestCmd(cmd.Command):
17
17
  user_options = []
18
18
  description = 'run pytest on this project'
19
19
 
@@ -26,9 +26,10 @@ class PytestCmd(cmd.Command):
26
26
  def run(self) -> None:
27
27
  os.system(f'cd {ROOT.absolute()} && pytest')
28
28
 
29
+
29
30
  setup(
30
31
  name='tensorguard',
31
- version='0.1.2',
32
+ version='1.0.1',
32
33
  packages=['tensorguard'],
33
34
  url='https://github.com/Michedev/tensorguard',
34
35
  license='Apache-2.0',
@@ -40,7 +41,7 @@ setup(
40
41
  install_requires=install_requirements,
41
42
  long_description=readme,
42
43
  long_description_content_type='text/markdown',
43
- python_requires='>=3.6.0',
44
+ python_requires='>=3.6',
44
45
  classifiers=[
45
46
  # Trove classifiers
46
47
  # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
@@ -53,6 +54,11 @@ setup(
53
54
  'Programming Language :: Python :: 3.6',
54
55
  'Programming Language :: Python :: 3.7',
55
56
  'Programming Language :: Python :: 3.8',
57
+ 'Programming Language :: Python :: 3.9',
58
+ 'Programming Language :: Python :: 3.10',
59
+ 'Programming Language :: Python :: 3.11',
60
+ 'Programming Language :: Python :: 3.12',
61
+ 'Programming Language :: Python :: 3.13',
56
62
  'Programming Language :: Python :: Implementation :: CPython',
57
63
  ],
58
64
  cmdclass={
@@ -0,0 +1,189 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License");
2
+ # you may not use this file except in compliance with the License.
3
+ # You may obtain a copy of the License at
4
+ #
5
+ # https://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+
13
+ """This python module contains ShapeGuard."""
14
+ from copy import copy
15
+ from typing import Optional, List, Any, Union, Dict
16
+
17
+ from tensorguard import tools
18
+ from tensorguard.exception import ShapeError
19
+ from tensorguard.guard import TensorGuard
20
+
21
+ __version__ = "1.0.0"
22
+
23
+ __author__ = "Michele De Vita"
24
+ __author_email__ = "mik3dev@gmail.com"
25
+
26
+ __url__ = "https://github.com/Michedev/shapeguard"
27
+
28
+ from tensorguard.tools import ShapedTensor
29
+
30
+ __tg = TensorGuard()
31
+
32
+
33
+ def reset():
34
+ """
35
+ Reset global tensorguard
36
+ """
37
+ global __tg
38
+ __tg = TensorGuard()
39
+
40
+
41
+ def matches(tensor: Union[ShapedTensor, List[int]], template: str) -> bool:
42
+ """
43
+ Return True if tensor shape matches template
44
+ """
45
+ return tools.matches(tensor, template, __tg.dims)
46
+
47
+
48
+ def guard(tensor: Union[ShapedTensor, List[int]], template: str) -> Union[ShapedTensor, List[int]]:
49
+ """
50
+ Check if tensor shape matches template. If not, raise ShapeError
51
+ :param tensor: Tensor or list of integers
52
+ :param template: Template string that should match tensor shape
53
+ :type template: str
54
+ :return: input tensor
55
+ """
56
+ inferred_dims = tools.guard(tensor, template, __tg.dims)
57
+ __tg.dims.update(inferred_dims)
58
+ return tensor
59
+
60
+
61
+ def reshape(tensor: Union[ShapedTensor, List[int]], template: str):
62
+ return tools.reshape(tensor, template, __tg.dims)
63
+
64
+
65
+ def evaluate(template: str, **kwargs) -> List[Optional[int]]:
66
+ local_dims = copy(__tg.dims)
67
+ local_dims.update(kwargs)
68
+ return tools.evaluate(template, local_dims)
69
+
70
+
71
+ def get_dims(template: Optional[str] = None) -> Union[Dict[str, int], List[Optional[int]]]:
72
+ """
73
+ If template is None return dictionary of all {token_shape: token_value}.
74
+ If token template is provided returns the corresponding list of token values.
75
+
76
+ Example:
77
+
78
+ >>> import tensorguard as tg
79
+ >>> tg.get_dims("B, C, H, W")
80
+ [16, 3, 224, 224]
81
+ >>> tg.get_dims()
82
+ {'B': 32, 'C': 3, 'H': 224, 'W': 224}
83
+
84
+ :param template: Optional template value
85
+ :type template:
86
+ :return:
87
+ :rtype:
88
+ """
89
+ if template is None:
90
+ return __tg.dims
91
+ else:
92
+ return tools.evaluate(template, __tg.dims)
93
+
94
+
95
+ def get_dim(item: str) -> Any:
96
+ """
97
+ Return corresponding value to shape token. If not exists, raise KeyError.
98
+ :param item:
99
+ :type item:
100
+ :return:
101
+ :rtype:
102
+ """
103
+ try:
104
+ return __tg.dims[item]
105
+ except KeyError:
106
+ raise KeyError(item)
107
+
108
+
109
+ def safe_get_dim(item: str) -> Any:
110
+ """
111
+ Return corresponding value to shape token. If not exists doesn't raise an Exception
112
+ :param item: the shape token
113
+ :type item: str
114
+ :return: shape token value
115
+ """
116
+ if has_dim(item):
117
+ return get_dim(item)
118
+
119
+
120
+ def has_dim(key: str) -> bool:
121
+ return key in __tg.dims
122
+
123
+
124
+ def set_dim(key: str, value: Any):
125
+ """
126
+ Set dimension in the global tensorguard guardian.
127
+ :param key: the key to set
128
+ :type key: str
129
+ :param value: the value corresponding to the key
130
+ :type value:
131
+ :return: None
132
+ """
133
+ __tg.dims[key] = value
134
+
135
+ def set_dims(**kwargs):
136
+ """
137
+ Set multiple dimensions in the global tensorguard guardian.
138
+
139
+ Example:
140
+
141
+ >>> import tensorguard as tg
142
+ >>> tg.set_dims(B=16, W=32, H=32, C=3)
143
+ """
144
+ for key, value in kwargs.items():
145
+ set_dim(key, value)
146
+
147
+ def del_dim(item: str):
148
+ """
149
+ Delete a shape token. If not exists, raise KeyError.
150
+ :param key:
151
+ :type key: str
152
+ :return: None
153
+ """
154
+ try:
155
+ del __tg.dims[item]
156
+ except KeyError:
157
+ raise KeyError(item)
158
+
159
+
160
+ def safe_del_dim(key: str):
161
+ """
162
+ Delete a key only if exists. If not exists does not raise exceptions.
163
+ :param key:
164
+ :type key: str
165
+ :return: None
166
+ """
167
+ if has_dim(key):
168
+ del_dim(key)
169
+
170
+
171
+ __all__ = (
172
+ "TensorGuard",
173
+ "__version__",
174
+ "__author__",
175
+ "__author_email__",
176
+ "ShapeError",
177
+ "guard",
178
+ "matches",
179
+ "reshape",
180
+ "evaluate",
181
+ "get_dim",
182
+ "set_dim",
183
+ "set_dims",
184
+ "safe_get_dim",
185
+ "has_dim",
186
+ "del_dim",
187
+ "safe_del_dim",
188
+ "get_dims"
189
+ )
@@ -20,11 +20,16 @@ from typing_extensions import Protocol
20
20
  from tensorguard import exception
21
21
  from tensorguard import parser
22
22
 
23
+ try:
24
+ import torch
25
+ except ImportError:
26
+ pass
27
+
23
28
 
24
29
  class ShapedTensor(Protocol):
25
- shape: Sequence[int]
30
+ shape: Union[Sequence[int], 'torch.Size']
26
31
 
27
- def reshape(self, shape: Sequence[int]) -> 'ShapedTensor':
32
+ def reshape(self, shape: Union[Sequence[int], 'torch.Size']) -> 'ShapedTensor':
28
33
  pass
29
34
 
30
35
 
@@ -73,7 +78,7 @@ def guard(tensor: ShapedTensor, template: str, dims: Dict[str, int]):
73
78
  return {k: v for k, v in inferred_dims.items() if not k.startswith("_")}
74
79
 
75
80
 
76
- def get_shape(tensor_or_shape: Union[Sequence[int], ShapedTensor]) -> List[int]:
81
+ def get_shape(tensor_or_shape: Union[Sequence[int], 'torch.Size', ShapedTensor]) -> List[int]:
77
82
  if isinstance(tensor_or_shape, (list, tuple)):
78
83
  return list(tensor_or_shape)
79
84
  elif hasattr(tensor_or_shape, 'shape') and hasattr(tensor_or_shape.shape, '__iter__'):
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.4
2
+ Name: tensorguard
3
+ Version: 1.0.1
4
+ Summary: TensorGuard helps to guard against bad Tensor Shapes
5
+ Home-page: https://github.com/Michedev/tensorguard
6
+ Author: mikedev
7
+ Author-email: mik3dev@gmail.com
8
+ License: Apache-2.0
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.6
16
+ Classifier: Programming Language :: Python :: 3.7
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: Implementation :: CPython
24
+ Requires-Python: >=3.6
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: typing_extensions>=3.7.4.3
28
+ Dynamic: author
29
+ Dynamic: author-email
30
+ Dynamic: classifier
31
+ Dynamic: description
32
+ Dynamic: description-content-type
33
+ Dynamic: home-page
34
+ Dynamic: license
35
+ Dynamic: license-file
36
+ Dynamic: requires-dist
37
+ Dynamic: requires-python
38
+ Dynamic: summary
39
+
40
+ # Tensor Guard
41
+ <img src="https://github.com/user-attachments/assets/dfddbe05-87e5-48df-8608-e25bf6087044" alt="tensorguard logo" width="300">
42
+
43
+ [![PyPI version fury.io](https://badge.fury.io/py/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
44
+ [![PyPI pyversions](https://img.shields.io/pypi/pyversions/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
45
+ [![PyPI download month](https://img.shields.io/pypi/dm/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
46
+ [![GitHub followers](https://img.shields.io/github/followers/Michedev.svg?style=social&label=Follow&maxAge=2592000)](https://github.com/Michedev?tab=followers)
47
+
48
+ ---
49
+
50
+ TensorGuard helps to guard against bad Tensor shapes in any tensor based library (e.g. Numpy, Pytorch, Tensorflow) using an intuitive symbolic-based syntax
51
+
52
+ ### Installation
53
+ `pip install tensorguard`
54
+
55
+
56
+ ## Basic Usage
57
+
58
+ ```python
59
+ import numpy as np # could be tensorflow or torch as well
60
+ import tensorguard as tg
61
+
62
+ # tensorguard = tg.TensorGuard() #could be done in a OOP fashion
63
+ img = np.ones([64, 32, 32, 3])
64
+ flat_img = np.ones([64, 1024])
65
+ labels = np.ones([64])
66
+
67
+ # check shape consistency
68
+ tg.guard(img, "B, H, W, C")
69
+ tg.guard(labels, "B, 1") # raises error because of rank mismatch
70
+ tg.guard(flat_img, "B, H*W*C") # raises error because 1024 != 32*32*3
71
+
72
+ # guard also returns the tensor, so it can be inlined
73
+ mean_img = tg.guard(np.mean(img, axis=0), "H, W, C")
74
+
75
+ # more readable reshapes
76
+ flat_img = tg.reshape(img, 'B, H*W*C')
77
+
78
+ # evaluate templates
79
+ assert tg.get_dims('H, W*C+1') == [32, 97]
80
+
81
+ ```
82
+
83
+
84
+ ## Shape Template Syntax
85
+ The shape template mini-DSL supports many different ways of specifying shapes:
86
+
87
+ * numbers: `"64, 32, 32, 3"`
88
+ * named dimensions: `"B, width, height2, channels"`
89
+ * wildcards: `"B, *, *, *"`
90
+ * ellipsis: `"B, ..., 3"`
91
+ * addition, subtraction, multiplication, division: `"B*N, W/2, H*(C+1)"`
92
+ * dynamic dimensions: `"?, H, W, C"` *(only matches `[None, H, W, C]`)*
93
+
94
+
95
+
96
+ ### Original Repo link: https://github.com/Qwlouse/shapeguard
@@ -1,3 +1,4 @@
1
+ LICENSE
1
2
  MANIFEST.in
2
3
  README.md
3
4
  requirements.txt
@@ -16,7 +17,6 @@ tensorguard.egg-info/SOURCES.txt
16
17
  tensorguard.egg-info/dependency_links.txt
17
18
  tensorguard.egg-info/requires.txt
18
19
  tensorguard.egg-info/top_level.txt
19
- tests/__init__.py
20
20
  tests/test_global_accessors.py
21
21
  tests/test_guard.py
22
22
  tests/test_match.py
@@ -0,0 +1,4 @@
1
+ pytest
2
+ tensorflow-cpu
3
+ torch
4
+ numpy
@@ -26,8 +26,9 @@ def test_get_dim():
26
26
  x = np.zeros([32, 2, 5])
27
27
  tg.guard(x, "B, C, W")
28
28
  assert tg.get_dim("W") == 5
29
- with pytest.raises(AttributeError):
30
- tg.get_dim("W* 5")
29
+ with pytest.raises(KeyError):
30
+ tg.get_dim("W_FAKE")
31
+ assert tg.safe_get_dim("W_FAKE") is None
31
32
 
32
33
 
33
34
  def test_set_dim():
@@ -40,6 +41,10 @@ def test_set_dim():
40
41
  assert tg.get_dim("W") == 10
41
42
  tg.set_dim("WF", 40)
42
43
  assert tg.get_dim("WF") == 40
44
+ assert tg.safe_get_dim("W_FAKE") is None
45
+ tg.set_dims(WW=32, HH=55)
46
+ assert tg.get_dim("WW") == 32
47
+ assert tg.safe_get_dim("HH") == 55
43
48
 
44
49
 
45
50
  def test_del_dim():
@@ -49,6 +54,6 @@ def test_del_dim():
49
54
  tg.guard(x, "B, C, W")
50
55
  assert tg.get_dim("W") == 5
51
56
  tg.del_dim("W")
52
- with pytest.raises(AttributeError):
53
- tg.get_dim("W")
54
-
57
+ with pytest.raises(KeyError):
58
+ tg.del_dim("W")
59
+ tg.safe_del_dim("W")
@@ -12,14 +12,18 @@
12
12
 
13
13
  import pytest
14
14
  import torch
15
- import tensorflow as tf
16
15
  import numpy as np
17
16
 
18
17
  from tensorguard import ShapeError
19
18
  from tensorguard import TensorGuard
20
19
 
20
+ try:
21
+ import tensorflow as tf
22
+ except ImportError:
23
+ tf = None
21
24
 
22
25
 
26
+ @pytest.mark.skipif(tf is None, reason="TensorFlow not installed")
23
27
  def test_guard_raises_tensorflow():
24
28
  tg = TensorGuard()
25
29
  a = tf.ones([1, 2, 3])
@@ -27,6 +31,7 @@ def test_guard_raises_tensorflow():
27
31
  tg.guard(a, "3, 2, 1")
28
32
 
29
33
 
34
+ @pytest.mark.skipif(tf is None, reason="TensorFlow not installed")
30
35
  def test_guard_infers_dimensions_tensorflow():
31
36
  tg = TensorGuard()
32
37
  a = tf.ones([1, 2, 3])
@@ -34,6 +39,7 @@ def test_guard_infers_dimensions_tensorflow():
34
39
  assert tg.dims == {"A": 1, "B": 2, "C": 3}
35
40
 
36
41
 
42
+ @pytest.mark.skipif(tf is None, reason="TensorFlow not installed")
37
43
  def test_guard_infers_dimensions_complex_tensorflow():
38
44
  tg = TensorGuard()
39
45
  a = tf.ones([1, 2, 3])
@@ -41,6 +47,7 @@ def test_guard_infers_dimensions_complex_tensorflow():
41
47
  assert tg.dims == {"A": 1, "B": 1, "C": 2}
42
48
 
43
49
 
50
+ @pytest.mark.skipif(tf is None, reason="TensorFlow not installed")
44
51
  def test_guard_infers_dimensions_operator_priority_tensorflow():
45
52
  tg = TensorGuard()
46
53
  a = tf.ones([1, 2, 8])
@@ -48,6 +55,7 @@ def test_guard_infers_dimensions_operator_priority_tensorflow():
48
55
  assert tg.dims == {"A": 1, "B": 2, "C": 3}
49
56
 
50
57
 
58
+ @pytest.mark.skipif(tf is None, reason="TensorFlow not installed")
51
59
  def test_guard_raises_complex_tensorflow():
52
60
  tg = TensorGuard()
53
61
  a = tf.ones([1, 2, 3])
@@ -55,6 +63,7 @@ def test_guard_raises_complex_tensorflow():
55
63
  tg.guard(a, "A, B, B")
56
64
 
57
65
 
66
+ @pytest.mark.skipif(tf is None, reason="TensorFlow not installed")
58
67
  def test_guard_raises_inferred_tensorflow():
59
68
  tg = TensorGuard()
60
69
  a = tf.ones([1, 2, 3])
@@ -64,6 +73,7 @@ def test_guard_raises_inferred_tensorflow():
64
73
  tg.guard(b, "C, B, A")
65
74
 
66
75
 
76
+ @pytest.mark.skipif(tf is None, reason="TensorFlow not installed")
67
77
  def test_guard_ignores_wildcard_tensorflow():
68
78
  tg = TensorGuard()
69
79
  a = tf.ones([1, 2, 3])
@@ -71,6 +81,7 @@ def test_guard_ignores_wildcard_tensorflow():
71
81
  assert tg.dims == {}
72
82
 
73
83
 
84
+ @pytest.mark.skipif(tf is None, reason="TensorFlow not installed")
74
85
  def test_guard_dynamic_shape_tensorflow():
75
86
  tg = TensorGuard()
76
87
  with pytest.raises(ShapeError):
@@ -81,6 +92,7 @@ def test_guard_dynamic_shape_tensorflow():
81
92
  tg.guard([None, 2, 3], "C?, B, A")
82
93
 
83
94
 
95
+ @pytest.mark.skipif(tf is None, reason="TensorFlow not installed")
84
96
  def test_guard_ellipsis_tensorflow():
85
97
  tg = TensorGuard()
86
98
  a = tf.ones([1, 2, 3, 4, 5])
@@ -99,6 +111,7 @@ def test_guard_ellipsis_tensorflow():
99
111
  tg.guard(a, "..., 1, 2, 3, 4, 5, 6")
100
112
 
101
113
 
114
+ @pytest.mark.skipif(tf is None, reason="TensorFlow not installed")
102
115
  def test_guard_ellipsis_infer_dims_tensorflow():
103
116
  tg = TensorGuard()
104
117
  a = tf.ones([1, 2, 3, 4, 5])
@@ -10,14 +10,20 @@
10
10
  # See the License for the specific language governing permissions and
11
11
  # limitations under the License.
12
12
 
13
- import tensorflow as tf
14
13
  import torch
15
14
  import numpy as np
16
15
  from tensorguard.guard import TensorGuard
16
+ import pytest
17
17
 
18
18
  # ======== tensorflow =================
19
19
 
20
+ try:
21
+ import tensorflow as tf
22
+ except ImportError:
23
+ tf = None
20
24
 
25
+
26
+ @pytest.mark.skipif(tf is None, reason="TensorFlow not installed")
21
27
  def test_matches_basic_numerical_tensorflow():
22
28
  tg = TensorGuard()
23
29
  a = tf.ones([1, 2, 3])
@@ -27,6 +33,7 @@ def test_matches_basic_numerical_tensorflow():
27
33
  assert not tg.matches(a, "1, 2")
28
34
 
29
35
 
36
+ @pytest.mark.skipif(tf is None, reason="TensorFlow not installed")
30
37
  def test_matches_ignores_spaces_tensorflow():
31
38
  tg = TensorGuard()
32
39
  a = tf.ones([1, 2, 3])
@@ -35,6 +42,7 @@ def test_matches_ignores_spaces_tensorflow():
35
42
  assert tg.matches(a, "1, 2,3 ")
36
43
 
37
44
 
45
+ @pytest.mark.skipif(tf is None, reason="TensorFlow not installed")
38
46
  def test_matches_named_dims_tensorflow():
39
47
  tg = TensorGuard(dims={"N": 24, "Z": 16})
40
48
  z = tf.ones([24, 16])
@@ -43,6 +51,7 @@ def test_matches_named_dims_tensorflow():
43
51
  assert not tg.matches(z, "N, N")
44
52
 
45
53
 
54
+ @pytest.mark.skipif(tf is None, reason="TensorFlow not installed")
46
55
  def test_matches_wildcards_tensorflow():
47
56
  tg = TensorGuard()
48
57
  z = tf.ones([1, 2, 4, 8])
@@ -1,76 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: tensorguard
3
- Version: 0.1.2
4
- Summary: TensorGuard helps to guard against bad Tensor Shapes
5
- Home-page: https://github.com/Michedev/tensorguard
6
- Author: mikedev
7
- Author-email: mik3dev@gmail.com
8
- License: Apache-2.0
9
- Description: # Tensor Guard
10
-
11
- [![PyPI version fury.io](https://badge.fury.io/py/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
12
- [![PyPI pyversions](https://img.shields.io/pypi/pyversions/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
13
- [![PyPI download month](https://img.shields.io/pypi/dm/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
14
- [![GitHub followers](https://img.shields.io/github/followers/Michedev.svg?style=social&label=Follow&maxAge=2592000)](https://github.com/Michedev?tab=followers)
15
-
16
- TensorGuard helps to guard against bad Tensor shapes in any tensor based library (e.g. Numpy, Pytorch, Tensorflow) using an intuitive symbolic-based syntax
17
-
18
- ### Installation
19
- `pip install tensorguard`
20
-
21
-
22
- ## Basic Usage
23
-
24
- ```python
25
- import numpy as np # could be tensorflow or torch as well
26
- import tensorguard as tg
27
-
28
- # tensorguard = tg.TensorGuard() #could be done in a OOP fashion
29
- img = np.ones([64, 32, 32, 3])
30
- flat_img = np.ones([64, 1024])
31
- labels = np.ones([64])
32
-
33
- # check shape consistency
34
- tg.guard(img, "B, H, W, C")
35
- tg.guard(labels, "B, 1") # raises error because of rank mismatch
36
- tg.guard(flat_img, "B, H*W*C") # raises error because 1024 != 32*32*3
37
-
38
- # guard also returns the tensor, so it can be inlined
39
- mean_img = tg.guard(np.mean(img, axis=0), "H, W, C")
40
-
41
- # more readable reshapes
42
- flat_img = tg.reshape(img, 'B, H*W*C')
43
-
44
- # evaluate templates
45
- assert tg.get_dims('H, W*C+1') == [32, 97]
46
-
47
- ```
48
-
49
-
50
- ## Shape Template Syntax
51
- The shape template mini-DSL supports many different ways of specifying shapes:
52
-
53
- * numbers: `"64, 32, 32, 3"`
54
- * named dimensions: `"B, width, height2, channels"`
55
- * wildcards: `"B, *, *, *"`
56
- * ellipsis: `"B, ..., 3"`
57
- * addition, subtraction, multiplication, division: `"B*N, W/2, H*(C+1)"`
58
- * dynamic dimensions: `"?, H, W, C"` *(only matches `[None, H, W, C]`)*
59
-
60
-
61
-
62
- ### Original Repo link: https://github.com/Qwlouse/shapeguard
63
-
64
- Platform: UNKNOWN
65
- Classifier: License :: OSI Approved :: Apache Software License
66
- Classifier: Intended Audience :: Developers
67
- Classifier: Intended Audience :: Science/Research
68
- Classifier: Operating System :: OS Independent
69
- Classifier: Programming Language :: Python
70
- Classifier: Programming Language :: Python :: 3
71
- Classifier: Programming Language :: Python :: 3.6
72
- Classifier: Programming Language :: Python :: 3.7
73
- Classifier: Programming Language :: Python :: 3.8
74
- Classifier: Programming Language :: Python :: Implementation :: CPython
75
- Requires-Python: >=3.6.0
76
- Description-Content-Type: text/markdown
@@ -1,105 +0,0 @@
1
- # Licensed under the Apache License, Version 2.0 (the "License");
2
- # you may not use this file except in compliance with the License.
3
- # You may obtain a copy of the License at
4
- #
5
- # https://www.apache.org/licenses/LICENSE-2.0
6
- #
7
- # Unless required by applicable law or agreed to in writing, software
8
- # distributed under the License is distributed on an "AS IS" BASIS,
9
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
- # See the License for the specific language governing permissions and
11
- # limitations under the License.
12
-
13
- """This python module contains ShapeGuard."""
14
- from copy import copy
15
- from typing import Optional, List, Any, Union, Dict
16
-
17
- from tensorguard import tools
18
- from tensorguard.exception import ShapeError
19
- from tensorguard.guard import TensorGuard
20
-
21
- __version__ = "0.1.1"
22
-
23
- __author__ = "Michele De Vita"
24
- __author_email__ = "mik3dev@gmail.com"
25
-
26
- __url__ = "https://github.com/Michedev/shapeguard"
27
-
28
- from tensorguard.tools import ShapedTensor
29
-
30
- __tg = TensorGuard()
31
-
32
-
33
- def reset():
34
- """
35
- Reset global tensorguard
36
- """
37
- global __tg
38
- __tg = TensorGuard()
39
-
40
-
41
- def matches(tensor: Union[ShapedTensor, List[int]], template: str) -> bool:
42
- """
43
- Return True if tensor shape matches template
44
- """
45
- return tools.matches(tensor, template, __tg.dims)
46
-
47
-
48
- def guard(tensor: Union[ShapedTensor, List[int]], template: str):
49
- inferred_dims = tools.guard(tensor, template, __tg.dims)
50
- __tg.dims.update(inferred_dims)
51
- return tensor
52
-
53
-
54
- def reshape(tensor: Union[ShapedTensor, List[int]], template: str):
55
- return tools.reshape(tensor, template, __tg.dims)
56
-
57
-
58
- def evaluate(template: str, **kwargs) -> List[Optional[int]]:
59
- local_dims = copy(__tg.dims)
60
- local_dims.update(kwargs)
61
- return tools.evaluate(template, local_dims)
62
-
63
-
64
- def get_dims(item: Optional[str] = None) -> Union[Dict[str, int], List[Optional[int]]]:
65
- if item is None:
66
- return __tg.dims
67
- else:
68
- return tools.evaluate(item, __tg.dims)
69
-
70
-
71
- def get_dim(item: str) -> Any:
72
- try:
73
- return __tg.dims[item]
74
- except KeyError:
75
- raise AttributeError(item)
76
-
77
-
78
- def set_dim(key: str, value: Any):
79
- try:
80
- __tg.dims[key] = value
81
- except KeyError:
82
- raise AttributeError(key)
83
-
84
-
85
- def del_dim(item: str):
86
- try:
87
- del __tg.dims[item]
88
- except KeyError:
89
- raise AttributeError(item)
90
-
91
-
92
- __all__ = (
93
- "TensorGuard",
94
- "__version__",
95
- "__author__",
96
- "__author_email__",
97
- "ShapeError",
98
- "guard",
99
- "matches",
100
- "reshape",
101
- "evaluate",
102
- "get_dim",
103
- "del_dim",
104
- "get_dims"
105
- )
@@ -1,76 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: tensorguard
3
- Version: 0.1.2
4
- Summary: TensorGuard helps to guard against bad Tensor Shapes
5
- Home-page: https://github.com/Michedev/tensorguard
6
- Author: mikedev
7
- Author-email: mik3dev@gmail.com
8
- License: Apache-2.0
9
- Description: # Tensor Guard
10
-
11
- [![PyPI version fury.io](https://badge.fury.io/py/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
12
- [![PyPI pyversions](https://img.shields.io/pypi/pyversions/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
13
- [![PyPI download month](https://img.shields.io/pypi/dm/tensorguard.svg)](https://pypi.python.org/pypi/tensorguard/)
14
- [![GitHub followers](https://img.shields.io/github/followers/Michedev.svg?style=social&label=Follow&maxAge=2592000)](https://github.com/Michedev?tab=followers)
15
-
16
- TensorGuard helps to guard against bad Tensor shapes in any tensor based library (e.g. Numpy, Pytorch, Tensorflow) using an intuitive symbolic-based syntax
17
-
18
- ### Installation
19
- `pip install tensorguard`
20
-
21
-
22
- ## Basic Usage
23
-
24
- ```python
25
- import numpy as np # could be tensorflow or torch as well
26
- import tensorguard as tg
27
-
28
- # tensorguard = tg.TensorGuard() #could be done in a OOP fashion
29
- img = np.ones([64, 32, 32, 3])
30
- flat_img = np.ones([64, 1024])
31
- labels = np.ones([64])
32
-
33
- # check shape consistency
34
- tg.guard(img, "B, H, W, C")
35
- tg.guard(labels, "B, 1") # raises error because of rank mismatch
36
- tg.guard(flat_img, "B, H*W*C") # raises error because 1024 != 32*32*3
37
-
38
- # guard also returns the tensor, so it can be inlined
39
- mean_img = tg.guard(np.mean(img, axis=0), "H, W, C")
40
-
41
- # more readable reshapes
42
- flat_img = tg.reshape(img, 'B, H*W*C')
43
-
44
- # evaluate templates
45
- assert tg.get_dims('H, W*C+1') == [32, 97]
46
-
47
- ```
48
-
49
-
50
- ## Shape Template Syntax
51
- The shape template mini-DSL supports many different ways of specifying shapes:
52
-
53
- * numbers: `"64, 32, 32, 3"`
54
- * named dimensions: `"B, width, height2, channels"`
55
- * wildcards: `"B, *, *, *"`
56
- * ellipsis: `"B, ..., 3"`
57
- * addition, subtraction, multiplication, division: `"B*N, W/2, H*(C+1)"`
58
- * dynamic dimensions: `"?, H, W, C"` *(only matches `[None, H, W, C]`)*
59
-
60
-
61
-
62
- ### Original Repo link: https://github.com/Qwlouse/shapeguard
63
-
64
- Platform: UNKNOWN
65
- Classifier: License :: OSI Approved :: Apache Software License
66
- Classifier: Intended Audience :: Developers
67
- Classifier: Intended Audience :: Science/Research
68
- Classifier: Operating System :: OS Independent
69
- Classifier: Programming Language :: Python
70
- Classifier: Programming Language :: Python :: 3
71
- Classifier: Programming Language :: Python :: 3.6
72
- Classifier: Programming Language :: Python :: 3.7
73
- Classifier: Programming Language :: Python :: 3.8
74
- Classifier: Programming Language :: Python :: Implementation :: CPython
75
- Requires-Python: >=3.6.0
76
- Description-Content-Type: text/markdown
@@ -1,4 +0,0 @@
1
- pytest==6.2.2
2
- tensorflow==2.4.1
3
- torch==1.7.1
4
- numpy==1.19.5
@@ -1,11 +0,0 @@
1
- # Licensed under the Apache License, Version 2.0 (the "License");
2
- # you may not use this file except in compliance with the License.
3
- # You may obtain a copy of the License at
4
- #
5
- # https://www.apache.org/licenses/LICENSE-2.0
6
- #
7
- # Unless required by applicable law or agreed to in writing, software
8
- # distributed under the License is distributed on an "AS IS" BASIS,
9
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
- # See the License for the specific language governing permissions and
11
- # limitations under the License.
File without changes
File without changes