ml-pipes-tensor 0.1.0rc2__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.
- ml_pipes_tensor-0.1.0rc2/.gitignore +44 -0
- ml_pipes_tensor-0.1.0rc2/LICENSE +201 -0
- ml_pipes_tensor-0.1.0rc2/PKG-INFO +53 -0
- ml_pipes_tensor-0.1.0rc2/README.md +26 -0
- ml_pipes_tensor-0.1.0rc2/docs/README.md +196 -0
- ml_pipes_tensor-0.1.0rc2/pyproject.toml +53 -0
- ml_pipes_tensor-0.1.0rc2/src/ml_pipes/tensor/__init__.py +56 -0
- ml_pipes_tensor-0.1.0rc2/src/ml_pipes/tensor/ops.py +473 -0
- ml_pipes_tensor-0.1.0rc2/src/ml_pipes/tensor/types.py +44 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# macOS / editor noise
|
|
2
|
+
.DS_Store
|
|
3
|
+
.idea/
|
|
4
|
+
/tmp/
|
|
5
|
+
|
|
6
|
+
# Python caches
|
|
7
|
+
__pycache__/
|
|
8
|
+
*.py[cod]
|
|
9
|
+
*.pyo
|
|
10
|
+
*.pyd
|
|
11
|
+
|
|
12
|
+
# Test and tool caches
|
|
13
|
+
.pytest_cache/
|
|
14
|
+
.mypy_cache/
|
|
15
|
+
.ruff_cache/
|
|
16
|
+
.coverage
|
|
17
|
+
.coverage.*
|
|
18
|
+
htmlcov/
|
|
19
|
+
|
|
20
|
+
# Virtual environments
|
|
21
|
+
.venv/
|
|
22
|
+
venv/
|
|
23
|
+
|
|
24
|
+
# Packaging / build artifacts
|
|
25
|
+
build/
|
|
26
|
+
dist/
|
|
27
|
+
packages/*/dist-noiso/
|
|
28
|
+
*.whl
|
|
29
|
+
*.egg-info/
|
|
30
|
+
.eggs/
|
|
31
|
+
pip-wheel-metadata/
|
|
32
|
+
|
|
33
|
+
# Downloaded demo assets and runtime outputs
|
|
34
|
+
.example_assets/
|
|
35
|
+
examples/.example_assets/
|
|
36
|
+
*.onnx
|
|
37
|
+
*.pt
|
|
38
|
+
*.jpg
|
|
39
|
+
*.png
|
|
40
|
+
*.mp4
|
|
41
|
+
*.pkl
|
|
42
|
+
|
|
43
|
+
# Tracked GitHub-facing promo/docs assets
|
|
44
|
+
!.github/assets/**
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ml-pipes-tensor
|
|
3
|
+
Version: 0.1.0rc2
|
|
4
|
+
Summary: Tensor payloads and tensor registry operators for ml-pipes
|
|
5
|
+
Project-URL: Homepage, https://github.com/trained-by-humans/ml-pipes
|
|
6
|
+
Project-URL: Documentation, https://github.com/trained-by-humans/ml-pipes/blob/main/packages/tensor/docs/INDEX.md
|
|
7
|
+
Project-URL: Repository, https://github.com/trained-by-humans/ml-pipes
|
|
8
|
+
Project-URL: Issues, https://github.com/trained-by-humans/ml-pipes/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/trained-by-humans/ml-pipes/releases
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: machine-learning,numpy,pipelines,postprocess,tensor
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Requires-Dist: ml-pipes-core==0.1.0rc2
|
|
25
|
+
Requires-Dist: numpy>=1.26
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# ml-pipes-tensor
|
|
29
|
+
|
|
30
|
+
`ml-pipes-tensor` is the shared tensor workbench for `ml-pipes`.
|
|
31
|
+
|
|
32
|
+
Use this package when a pipeline needs NumPy-side tensor shaping, ranking,
|
|
33
|
+
masking, filtering, collation, or light arithmetic between a runtime boundary
|
|
34
|
+
and a typed task result. In practice, it often carries the reusable tensor
|
|
35
|
+
postprocess that sits after ONNX or Torch output extraction and before a task
|
|
36
|
+
package such as vision finalizes the result.
|
|
37
|
+
|
|
38
|
+
Operators can be used as plain callables, but this package is best used inside
|
|
39
|
+
an `ml-pipes` pipeline.
|
|
40
|
+
|
|
41
|
+
## Package Reference
|
|
42
|
+
|
|
43
|
+
| Field | Value |
|
|
44
|
+
|----------------|------------------------------------------------------------------------------------------------------------------|
|
|
45
|
+
| Package | `ml-pipes-tensor` |
|
|
46
|
+
| Guide | [`docs/README.md`](https://github.com/trained-by-humans/ml-pipes/blob/main/packages/tensor/docs/README.md) |
|
|
47
|
+
| Reference | [`docs/INDEX.md`](https://github.com/trained-by-humans/ml-pipes/blob/main/packages/tensor/docs/INDEX.md) |
|
|
48
|
+
| Depends on | `ml-pipes-core` |
|
|
49
|
+
| Public modules | `ml_pipes.tensor` |
|
|
50
|
+
| Content | shared tensor values; NumPy-side tensor shaping and selection; masking, ranking, collation, and light arithmetic |
|
|
51
|
+
|
|
52
|
+
See [`docs/PACKAGES.md`](https://github.com/trained-by-humans/ml-pipes/blob/main/docs/PACKAGES.md)
|
|
53
|
+
for direct package installs, umbrella profiles, and the full package matrix.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# ml-pipes-tensor
|
|
2
|
+
|
|
3
|
+
`ml-pipes-tensor` is the shared tensor workbench for `ml-pipes`.
|
|
4
|
+
|
|
5
|
+
Use this package when a pipeline needs NumPy-side tensor shaping, ranking,
|
|
6
|
+
masking, filtering, collation, or light arithmetic between a runtime boundary
|
|
7
|
+
and a typed task result. In practice, it often carries the reusable tensor
|
|
8
|
+
postprocess that sits after ONNX or Torch output extraction and before a task
|
|
9
|
+
package such as vision finalizes the result.
|
|
10
|
+
|
|
11
|
+
Operators can be used as plain callables, but this package is best used inside
|
|
12
|
+
an `ml-pipes` pipeline.
|
|
13
|
+
|
|
14
|
+
## Package Reference
|
|
15
|
+
|
|
16
|
+
| Field | Value |
|
|
17
|
+
|----------------|------------------------------------------------------------------------------------------------------------------|
|
|
18
|
+
| Package | `ml-pipes-tensor` |
|
|
19
|
+
| Guide | [`docs/README.md`](https://github.com/trained-by-humans/ml-pipes/blob/main/packages/tensor/docs/README.md) |
|
|
20
|
+
| Reference | [`docs/INDEX.md`](https://github.com/trained-by-humans/ml-pipes/blob/main/packages/tensor/docs/INDEX.md) |
|
|
21
|
+
| Depends on | `ml-pipes-core` |
|
|
22
|
+
| Public modules | `ml_pipes.tensor` |
|
|
23
|
+
| Content | shared tensor values; NumPy-side tensor shaping and selection; masking, ranking, collation, and light arithmetic |
|
|
24
|
+
|
|
25
|
+
See [`docs/PACKAGES.md`](https://github.com/trained-by-humans/ml-pipes/blob/main/docs/PACKAGES.md)
|
|
26
|
+
for direct package installs, umbrella profiles, and the full package matrix.
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
# Tensor Postprocess Domain
|
|
2
|
+
|
|
3
|
+
`ml_pipes.tensor` is the shared NumPy-side tensor workbench between runtime
|
|
4
|
+
packages and task packages.
|
|
5
|
+
|
|
6
|
+
For the full package surface, aliases, and operator catalog, see
|
|
7
|
+
[`INDEX.md`](./INDEX.md).
|
|
8
|
+
|
|
9
|
+
## Package Profile
|
|
10
|
+
|
|
11
|
+
| Dimension | Classification |
|
|
12
|
+
|-----------------|-------------------------------------------------------------------------|
|
|
13
|
+
| Role / Function | `Inference (Scaffold)` |
|
|
14
|
+
| Task Type | Mostly `Vision`; reusable across other tensor-returning inference flows |
|
|
15
|
+
| Data Type | `Tensors` |
|
|
16
|
+
|
|
17
|
+
## Scope And Use Cases
|
|
18
|
+
|
|
19
|
+
`ml_pipes.tensor` owns the small, explicit, generic NumPy-side tensor
|
|
20
|
+
operators and value types that sit around runtime handoff and shared
|
|
21
|
+
postprocess. It does not own runtime execution, model-specific decode logic,
|
|
22
|
+
task finalization, or image/media preparation.
|
|
23
|
+
|
|
24
|
+
Use this package when a pipeline needs a reusable NumPy-side tensor segment
|
|
25
|
+
between runtime output handoff and task finalization, especially during model
|
|
26
|
+
scaffolding or shared postprocess.
|
|
27
|
+
|
|
28
|
+
## Design Principles
|
|
29
|
+
|
|
30
|
+
Every operator in this package is designed to uphold the following properties.
|
|
31
|
+
They are not style guidelines; they are what makes operators safe to compose
|
|
32
|
+
and swap without side effects.
|
|
33
|
+
|
|
34
|
+
- **Model-agnostic.** No operator knows which model produced the tensors it
|
|
35
|
+
processes. `Softmax`, `ArgMax`, and `Slice` are generic. Model-specific
|
|
36
|
+
adaptations stay in the pipeline list as individual operators, not inside
|
|
37
|
+
shared infrastructure.
|
|
38
|
+
- **Precision-agnostic.** Operators preserve the dtype of their input. A
|
|
39
|
+
pipeline that runs in `float32` runs in `float16` without modifying any
|
|
40
|
+
operator. A preprocessing step such as `Normalize()` sets the working
|
|
41
|
+
precision before data enters the Tensor domain.
|
|
42
|
+
- **Runtime-agnostic.** Operators use NumPy. They impose no dependency on
|
|
43
|
+
PyTorch, TensorFlow, or any specific hardware. Runtime packages own the
|
|
44
|
+
inference step; the Tensor domain stays plain NumPy and transfers to any
|
|
45
|
+
compute environment.
|
|
46
|
+
- **Backend-explicit.** Unlike the points above, operators are not
|
|
47
|
+
backend-agnostic. They do not pretend to be one backend-polymorphic tensor
|
|
48
|
+
layer. Runtime-specific execution stays in the owning runtime packages.
|
|
49
|
+
- **Small and explicit.** Each operator should stay small and explicit in the
|
|
50
|
+
pipeline list and should own one clear tensor step.
|
|
51
|
+
|
|
52
|
+
## Runtime Types
|
|
53
|
+
|
|
54
|
+
The Tensor package uses explicit runtime values instead of passing bare
|
|
55
|
+
`np.ndarray` objects through every step. `TensorPayload` covers one
|
|
56
|
+
model-ready tensor together with layout and dtype metadata, while
|
|
57
|
+
`TensorRegistry` covers a named working set of tensors for postprocess.
|
|
58
|
+
|
|
59
|
+
### TensorPayload
|
|
60
|
+
|
|
61
|
+
`TensorPayload` is the one-tensor value type.
|
|
62
|
+
|
|
63
|
+
Use it when one array should move through the pipeline as one value and the
|
|
64
|
+
next step needs its layout and working dtype together with the tensor:
|
|
65
|
+
|
|
66
|
+
- `array`: the NumPy tensor
|
|
67
|
+
- `layout`: the semantic axis order such as `NHWC` or `NCHW`
|
|
68
|
+
- `dtype`: the working dtype recorded for the payload
|
|
69
|
+
|
|
70
|
+
It is commonly created by preprocessing operators such as `Normalize()`, then
|
|
71
|
+
consumed by operators such as `Infer()`, `ToTorch()`, or `Collate()`.
|
|
72
|
+
|
|
73
|
+
This is the common runtime handoff:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from ml_pipes.core import Pipeline
|
|
77
|
+
from ml_pipes.onnx import Infer
|
|
78
|
+
from ml_pipes.vision import Normalize
|
|
79
|
+
|
|
80
|
+
pipeline = Pipeline([
|
|
81
|
+
Normalize(), # -> TensorPayload
|
|
82
|
+
Infer(model_path),
|
|
83
|
+
])
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### TensorRegistry
|
|
87
|
+
|
|
88
|
+
`TensorRegistry` is the named multi-tensor working set for postprocess.
|
|
89
|
+
|
|
90
|
+
Use it when postprocess needs multiple intermediate tensors to stay named and
|
|
91
|
+
aligned. Tensor operators then refine those named tensors step by step until a
|
|
92
|
+
task package turns them into the final result.
|
|
93
|
+
|
|
94
|
+
This is the common postprocess shape:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from ml_pipes.core import Pipeline
|
|
98
|
+
from ml_pipes.onnx import Extract
|
|
99
|
+
from ml_pipes.tensor import ArgMax, GatherScores
|
|
100
|
+
|
|
101
|
+
pipeline = Pipeline([
|
|
102
|
+
Extract("scores", as_="class_scores"), # -> TensorRegistry
|
|
103
|
+
ArgMax("class_scores", as_="classes"),
|
|
104
|
+
GatherScores("class_scores", "classes", as_="scores"),
|
|
105
|
+
])
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Where Tensor Fits
|
|
109
|
+
|
|
110
|
+
Tensor sits between runtime packages and task packages. It does not own the
|
|
111
|
+
runtime step itself.
|
|
112
|
+
|
|
113
|
+
The nearby package crossings are:
|
|
114
|
+
|
|
115
|
+
- `Normalize()` from `ml_pipes.vision` creates a `TensorPayload`
|
|
116
|
+
- `Extract()` from `ml_pipes.onnx` creates a `TensorRegistry`
|
|
117
|
+
- `ToNumpy()` and `ToNumpyRegistry()` from `ml_pipes.torch` return back to the
|
|
118
|
+
Tensor domain
|
|
119
|
+
- `ToDetections()`, `ToSegmentations()`, and `ToDensityPrediction()` from
|
|
120
|
+
`ml_pipes.vision` finalize typed task results
|
|
121
|
+
|
|
122
|
+
At a high level, a common flow looks like this:
|
|
123
|
+
|
|
124
|
+
```text
|
|
125
|
+
┌──────────────────────────────────────────────────────────┐
|
|
126
|
+
│ Input / Task Domain │
|
|
127
|
+
├─ Decode -> Resize -> Normalize -> ... │
|
|
128
|
+
└────────┬─────────────────────────────────────────────────┘
|
|
129
|
+
|
|
|
130
|
+
| TensorPayload
|
|
131
|
+
▼
|
|
132
|
+
┌──────────────────────────────────────────────────────────┐
|
|
133
|
+
│ Runtime Domain │
|
|
134
|
+
├─ Infer / TorchInfer / ... │
|
|
135
|
+
└────────┬─────────────────────────────────────────────────┘
|
|
136
|
+
|
|
|
137
|
+
| Extract / ToNumpyRegistry
|
|
138
|
+
▼
|
|
139
|
+
┌──────────────────────────────────────────────────────────┐
|
|
140
|
+
│ Tensor Domain │
|
|
141
|
+
├─ Squeeze -> Slice -> Softmax -> ArgMax -> FilterTensors │
|
|
142
|
+
└────────┬─────────────────────────────────────────────────┘
|
|
143
|
+
|
|
|
144
|
+
| ToDetections / ToSegmentations / ...
|
|
145
|
+
▼
|
|
146
|
+
┌──────────────────────────────────────────────────────────┐
|
|
147
|
+
│ Task Result Domain │
|
|
148
|
+
└──────────────────────────────────────────────────────────┘
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
That split keeps runtime integration, shared tensor postprocess, and
|
|
152
|
+
task-specific finalization as separate stages.
|
|
153
|
+
|
|
154
|
+
## Using Tensor In Pipelines
|
|
155
|
+
|
|
156
|
+
This section shows only the Tensor-owned slice: start from extracted named
|
|
157
|
+
tensors, apply small registry operators to refine them, then hand the final
|
|
158
|
+
tensors to a task package.
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
from ml_pipes.core import Pipeline
|
|
162
|
+
from ml_pipes.onnx import Extract
|
|
163
|
+
from ml_pipes.tensor import ArgMax, GatherScores, Slice, Squeeze, Transpose
|
|
164
|
+
from ml_pipes.vision import ConvertBoxFormat, ToDetections
|
|
165
|
+
|
|
166
|
+
pipeline = Pipeline([
|
|
167
|
+
...,
|
|
168
|
+
Extract("output0", as_="preds"),
|
|
169
|
+
Squeeze("preds"),
|
|
170
|
+
Transpose("preds"),
|
|
171
|
+
Slice("preds", slice(None, 4), as_="boxes"),
|
|
172
|
+
Slice("preds", slice(4, None), as_="scores"),
|
|
173
|
+
ArgMax("scores", as_="classes"),
|
|
174
|
+
GatherScores("scores", "classes"),
|
|
175
|
+
ConvertBoxFormat(from_="cxcywh"),
|
|
176
|
+
ToDetections(),
|
|
177
|
+
])
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
This is the shape used in
|
|
181
|
+
[`examples/run_yolo8_onnx.py`](../../../examples/run_yolo8_onnx.py) and
|
|
182
|
+
[`examples/run_rfdetr_nano.py`](../../../examples/run_rfdetr_nano.py).
|
|
183
|
+
|
|
184
|
+
For the full guide on how to build scaffolding around the model, see
|
|
185
|
+
[`SCAFFOLDING.md`](../../../docs/SCAFFOLDING.md).
|
|
186
|
+
|
|
187
|
+
## Further Reading
|
|
188
|
+
|
|
189
|
+
- [`INDEX.md`](./INDEX.md) for the full surface catalog
|
|
190
|
+
- [`docs/README.md`](../../../docs/README.md) for the shared framework docs index
|
|
191
|
+
- [`REGIONS.md`](../../../docs/REGIONS.md) for batching and regions
|
|
192
|
+
- [`Torch guide`](../../torch/docs/README.md) for Torch/NumPy crossover pipelines
|
|
193
|
+
- [`Vision guide`](../../vision/docs/README.md) for task-specific tensor operations and typed results in vision pipelines
|
|
194
|
+
- [`examples/README.md`](../../../examples/README.md) for runnable pipeline entry points
|
|
195
|
+
- [`examples/run_yolo8_onnx.py`](../../../examples/run_yolo8_onnx.py)
|
|
196
|
+
- [`examples/run_rfdetr_nano.py`](../../../examples/run_rfdetr_nano.py)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ml-pipes-tensor"
|
|
7
|
+
version = "0.1.0rc2"
|
|
8
|
+
description = "Tensor payloads and tensor registry operators for ml-pipes"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
keywords = [
|
|
13
|
+
"machine-learning",
|
|
14
|
+
"numpy",
|
|
15
|
+
"pipelines",
|
|
16
|
+
"postprocess",
|
|
17
|
+
"tensor",
|
|
18
|
+
]
|
|
19
|
+
classifiers = [
|
|
20
|
+
"Development Status :: 3 - Alpha",
|
|
21
|
+
"Intended Audience :: Developers",
|
|
22
|
+
"License :: OSI Approved :: Apache Software License",
|
|
23
|
+
"Programming Language :: Python :: 3",
|
|
24
|
+
"Programming Language :: Python :: 3.10",
|
|
25
|
+
"Programming Language :: Python :: 3.11",
|
|
26
|
+
"Programming Language :: Python :: 3.12",
|
|
27
|
+
"Programming Language :: Python :: 3.13",
|
|
28
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
29
|
+
"Topic :: Software Development :: Libraries :: Application Frameworks",
|
|
30
|
+
]
|
|
31
|
+
requires-python = ">=3.10"
|
|
32
|
+
dependencies = [
|
|
33
|
+
"ml-pipes-core==0.1.0rc2",
|
|
34
|
+
"numpy>=1.26",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
[project.urls]
|
|
38
|
+
Homepage = "https://github.com/trained-by-humans/ml-pipes"
|
|
39
|
+
Documentation = "https://github.com/trained-by-humans/ml-pipes/blob/main/packages/tensor/docs/INDEX.md"
|
|
40
|
+
Repository = "https://github.com/trained-by-humans/ml-pipes"
|
|
41
|
+
Issues = "https://github.com/trained-by-humans/ml-pipes/issues"
|
|
42
|
+
Changelog = "https://github.com/trained-by-humans/ml-pipes/releases"
|
|
43
|
+
|
|
44
|
+
[tool.hatch.build.targets.wheel]
|
|
45
|
+
packages = ["src/ml_pipes"]
|
|
46
|
+
|
|
47
|
+
[tool.hatch.build.targets.sdist]
|
|
48
|
+
include = [
|
|
49
|
+
"LICENSE",
|
|
50
|
+
"README.md",
|
|
51
|
+
"pyproject.toml",
|
|
52
|
+
"src/ml_pipes",
|
|
53
|
+
]
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .ops import (
|
|
4
|
+
ApplyTensorMask,
|
|
5
|
+
ArgMax,
|
|
6
|
+
AsType,
|
|
7
|
+
BinarizeTensor,
|
|
8
|
+
BinarizeTensorByThreshold,
|
|
9
|
+
Collate,
|
|
10
|
+
CreateTensorMask,
|
|
11
|
+
CreateTensorMaskByThreshold,
|
|
12
|
+
FilterTensors,
|
|
13
|
+
GatherRows,
|
|
14
|
+
GatherScores,
|
|
15
|
+
MapTensor,
|
|
16
|
+
MultiplyTensors,
|
|
17
|
+
Scale,
|
|
18
|
+
SelectTensors,
|
|
19
|
+
Sigmoid,
|
|
20
|
+
Slice,
|
|
21
|
+
Softmax,
|
|
22
|
+
SortTensorsBy,
|
|
23
|
+
Squeeze,
|
|
24
|
+
TopK,
|
|
25
|
+
TopKIndices2D,
|
|
26
|
+
Transpose,
|
|
27
|
+
)
|
|
28
|
+
from .types import TensorPayload, TensorRegistry
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"ApplyTensorMask",
|
|
32
|
+
"ArgMax",
|
|
33
|
+
"AsType",
|
|
34
|
+
"BinarizeTensor",
|
|
35
|
+
"BinarizeTensorByThreshold",
|
|
36
|
+
"Collate",
|
|
37
|
+
"CreateTensorMask",
|
|
38
|
+
"CreateTensorMaskByThreshold",
|
|
39
|
+
"FilterTensors",
|
|
40
|
+
"GatherRows",
|
|
41
|
+
"GatherScores",
|
|
42
|
+
"MapTensor",
|
|
43
|
+
"MultiplyTensors",
|
|
44
|
+
"Scale",
|
|
45
|
+
"SelectTensors",
|
|
46
|
+
"Sigmoid",
|
|
47
|
+
"Slice",
|
|
48
|
+
"Softmax",
|
|
49
|
+
"SortTensorsBy",
|
|
50
|
+
"Squeeze",
|
|
51
|
+
"TensorPayload",
|
|
52
|
+
"TensorRegistry",
|
|
53
|
+
"TopK",
|
|
54
|
+
"TopKIndices2D",
|
|
55
|
+
"Transpose",
|
|
56
|
+
]
|
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import Any, Generic, Literal, TypeAlias, TypeVar, cast, overload
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import numpy.typing as npt
|
|
8
|
+
|
|
9
|
+
from ml_pipes._operator_utils import resolve_multi_output_names
|
|
10
|
+
from ml_pipes._typing.annotation import is_assignable
|
|
11
|
+
from ml_pipes.operator import Operator
|
|
12
|
+
from .types import TensorPayload, TensorRegistry
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"ApplyTensorMask",
|
|
16
|
+
"ArgMax",
|
|
17
|
+
"AsType",
|
|
18
|
+
"BinarizeTensor",
|
|
19
|
+
"BinarizeTensorByThreshold",
|
|
20
|
+
"Collate",
|
|
21
|
+
"CreateTensorMask",
|
|
22
|
+
"CreateTensorMaskByThreshold",
|
|
23
|
+
"FilterTensors",
|
|
24
|
+
"GatherRows",
|
|
25
|
+
"GatherScores",
|
|
26
|
+
"MapTensor",
|
|
27
|
+
"MultiplyTensors",
|
|
28
|
+
"Scale",
|
|
29
|
+
"SelectTensors",
|
|
30
|
+
"Sigmoid",
|
|
31
|
+
"Slice",
|
|
32
|
+
"Softmax",
|
|
33
|
+
"SortTensorsBy",
|
|
34
|
+
"Squeeze",
|
|
35
|
+
"TensorPayload",
|
|
36
|
+
"TensorRegistry",
|
|
37
|
+
"TopK",
|
|
38
|
+
"TopKIndices2D",
|
|
39
|
+
"Transpose",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
TensorLike: TypeAlias = (
|
|
43
|
+
TensorPayload
|
|
44
|
+
| np.ndarray
|
|
45
|
+
| tuple[TensorPayload, ...]
|
|
46
|
+
| tuple[np.ndarray, ...]
|
|
47
|
+
| list[TensorPayload]
|
|
48
|
+
| list[np.ndarray]
|
|
49
|
+
)
|
|
50
|
+
TensorMask: TypeAlias = npt.NDArray[np.bool_]
|
|
51
|
+
TensorInput: TypeAlias = TensorLike | TensorRegistry
|
|
52
|
+
TensorValueT = TypeVar("TensorValueT", bound=TensorLike)
|
|
53
|
+
AsTypeModeT = TypeVar("AsTypeModeT", bound=bool)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _normalize_axis(axis: int, ndim: int) -> int:
|
|
57
|
+
normalized = axis if axis >= 0 else axis + ndim
|
|
58
|
+
if normalized < 0 or normalized >= ndim:
|
|
59
|
+
raise np.exceptions.AxisError(axis, ndim=ndim)
|
|
60
|
+
return normalized
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _shape_without_axis(shape: tuple[int, ...], axis: int) -> tuple[int, ...]:
|
|
64
|
+
return shape[:axis] + shape[axis + 1 :]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _flatten_leading_dim(array: np.ndarray) -> np.ndarray:
|
|
68
|
+
leading = int(array.shape[0])
|
|
69
|
+
trailing = int(np.prod(array.shape[1:], dtype=np.int64))
|
|
70
|
+
return array.reshape(leading, trailing)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@Operator
|
|
74
|
+
class AsType(Generic[AsTypeModeT]):
|
|
75
|
+
@overload
|
|
76
|
+
def __init__(
|
|
77
|
+
self: "AsType[Literal[False]]",
|
|
78
|
+
dtype: str,
|
|
79
|
+
src: None = None,
|
|
80
|
+
as_: None = None,
|
|
81
|
+
) -> None:
|
|
82
|
+
...
|
|
83
|
+
|
|
84
|
+
@overload
|
|
85
|
+
def __init__(
|
|
86
|
+
self: "AsType[Literal[True]]",
|
|
87
|
+
dtype: str,
|
|
88
|
+
src: str,
|
|
89
|
+
as_: str | None = None,
|
|
90
|
+
) -> None:
|
|
91
|
+
...
|
|
92
|
+
|
|
93
|
+
def __init__(self, dtype: str, src: str | None = None, as_: str | None = None):
|
|
94
|
+
if src is None and as_ is not None:
|
|
95
|
+
raise ValueError("AsType as_ requires src.")
|
|
96
|
+
self.dtype = np.dtype(dtype)
|
|
97
|
+
self.src = src
|
|
98
|
+
self.as_ = as_ or src
|
|
99
|
+
|
|
100
|
+
def resolve_contract(self, upstream_annotation, error_type):
|
|
101
|
+
if self.src is not None:
|
|
102
|
+
return (TensorRegistry,), TensorRegistry
|
|
103
|
+
if upstream_annotation is not Any and is_assignable(upstream_annotation, TensorLike):
|
|
104
|
+
return (upstream_annotation,), upstream_annotation
|
|
105
|
+
return (TensorLike,), TensorLike
|
|
106
|
+
|
|
107
|
+
@overload
|
|
108
|
+
def __call__(self: "AsType[Literal[False]]", value: TensorValueT) -> TensorValueT:
|
|
109
|
+
...
|
|
110
|
+
|
|
111
|
+
@overload
|
|
112
|
+
def __call__(self: "AsType[Literal[True]]", value: TensorRegistry) -> TensorRegistry:
|
|
113
|
+
...
|
|
114
|
+
|
|
115
|
+
def __call__(self, value: Any) -> Any:
|
|
116
|
+
if self.src is not None:
|
|
117
|
+
if not isinstance(value, TensorRegistry):
|
|
118
|
+
raise TypeError(f"AsType src={self.src!r} requires TensorRegistry, got {type(value)!r}")
|
|
119
|
+
value[self.as_] = self._cast_array(value[self.src])
|
|
120
|
+
return value
|
|
121
|
+
return self._cast_value(value)
|
|
122
|
+
|
|
123
|
+
def _cast_value(self, value: TensorValueT) -> TensorValueT:
|
|
124
|
+
if isinstance(value, TensorPayload):
|
|
125
|
+
return cast(
|
|
126
|
+
TensorValueT,
|
|
127
|
+
TensorPayload(array=value.array.astype(self.dtype, copy=False), layout=value.layout, dtype=str(self.dtype)),
|
|
128
|
+
)
|
|
129
|
+
if isinstance(value, np.ndarray):
|
|
130
|
+
return cast(TensorValueT, self._cast_array(value))
|
|
131
|
+
if isinstance(value, tuple):
|
|
132
|
+
return cast(TensorValueT, tuple(self._cast_sequence_item(item) for item in value))
|
|
133
|
+
if isinstance(value, list):
|
|
134
|
+
return cast(TensorValueT, [self._cast_sequence_item(item) for item in value])
|
|
135
|
+
raise TypeError(f"AsType does not support value type {type(value)!r}")
|
|
136
|
+
|
|
137
|
+
def _cast_sequence_item(self, value: object) -> TensorPayload | np.ndarray:
|
|
138
|
+
if isinstance(value, TensorPayload):
|
|
139
|
+
return TensorPayload(array=value.array.astype(self.dtype, copy=False), layout=value.layout, dtype=str(self.dtype))
|
|
140
|
+
if isinstance(value, np.ndarray):
|
|
141
|
+
return self._cast_array(value)
|
|
142
|
+
raise TypeError(f"AsType does not support sequence item type {type(value)!r}")
|
|
143
|
+
|
|
144
|
+
def _cast_array(self, value: np.ndarray) -> np.ndarray:
|
|
145
|
+
return np.asarray(value).astype(self.dtype, copy=False)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@Operator
|
|
149
|
+
class Squeeze:
|
|
150
|
+
def __init__(self, src: str, axis: int | tuple[int, ...] | None = None, as_: str | None = None):
|
|
151
|
+
self.src = src
|
|
152
|
+
self.axis = axis
|
|
153
|
+
self.as_ = as_ or src
|
|
154
|
+
|
|
155
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
156
|
+
tensor = registry[self.src]
|
|
157
|
+
registry[self.as_] = np.squeeze(tensor, axis=self.axis) if self.axis is not None else np.squeeze(tensor)
|
|
158
|
+
return registry
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@Operator
|
|
162
|
+
class Transpose:
|
|
163
|
+
def __init__(self, src: str, axes: tuple[int, ...] | None = None, as_: str | None = None):
|
|
164
|
+
self.src = src
|
|
165
|
+
self.axes = axes
|
|
166
|
+
self.as_ = as_ or src
|
|
167
|
+
|
|
168
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
169
|
+
registry[self.as_] = np.transpose(registry[self.src], self.axes)
|
|
170
|
+
return registry
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@Operator
|
|
174
|
+
class Slice:
|
|
175
|
+
def __init__(self, src: str, at: slice, as_: str | None = None):
|
|
176
|
+
self.src = src
|
|
177
|
+
self.at = at
|
|
178
|
+
self.as_ = as_ or src
|
|
179
|
+
|
|
180
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
181
|
+
registry[self.as_] = registry[self.src][:, self.at]
|
|
182
|
+
return registry
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@Operator
|
|
186
|
+
class GatherRows:
|
|
187
|
+
def __init__(self, src: str, indices: str, as_: str | None = None):
|
|
188
|
+
self.src = src
|
|
189
|
+
self.indices = indices
|
|
190
|
+
self.as_ = as_ or src
|
|
191
|
+
|
|
192
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
193
|
+
src = registry[self.src]
|
|
194
|
+
idx = registry[self.indices]
|
|
195
|
+
registry[self.as_] = src[np.arange(src.shape[0]), idx]
|
|
196
|
+
return registry
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
GatherScores = GatherRows
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@Operator
|
|
203
|
+
class TopK:
|
|
204
|
+
def __init__(self, src: str, k: int, values_as: str = "top_values", indices_as: str = "top_indices"):
|
|
205
|
+
self.src = src
|
|
206
|
+
self.k = k
|
|
207
|
+
self.values_as = values_as
|
|
208
|
+
self.indices_as = indices_as
|
|
209
|
+
|
|
210
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
211
|
+
values = registry[self.src]
|
|
212
|
+
if values.ndim != 1:
|
|
213
|
+
raise ValueError(f"TopK expects a 1D tensor, got shape {values.shape}")
|
|
214
|
+
size = int(values.shape[0])
|
|
215
|
+
top_k = min(self.k, size)
|
|
216
|
+
if top_k == 0:
|
|
217
|
+
registry[self.values_as] = values[:0]
|
|
218
|
+
registry[self.indices_as] = np.zeros((0,), dtype=np.int64)
|
|
219
|
+
return registry
|
|
220
|
+
top_indices = np.argpartition(values, -top_k)[-top_k:]
|
|
221
|
+
order = np.argsort(values[top_indices])[::-1]
|
|
222
|
+
top_indices = top_indices[order].astype(np.int64, copy=False)
|
|
223
|
+
registry[self.values_as] = values[top_indices]
|
|
224
|
+
registry[self.indices_as] = top_indices
|
|
225
|
+
return registry
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
@Operator
|
|
229
|
+
class TopKIndices2D:
|
|
230
|
+
def __init__(
|
|
231
|
+
self,
|
|
232
|
+
src: str,
|
|
233
|
+
k: int,
|
|
234
|
+
values_as: str = "top_values",
|
|
235
|
+
row_indices_as: str = "row_indices",
|
|
236
|
+
col_indices_as: str = "col_indices",
|
|
237
|
+
):
|
|
238
|
+
self.src = src
|
|
239
|
+
self.k = k
|
|
240
|
+
self.values_as = values_as
|
|
241
|
+
self.row_indices_as = row_indices_as
|
|
242
|
+
self.col_indices_as = col_indices_as
|
|
243
|
+
|
|
244
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
245
|
+
values = registry[self.src]
|
|
246
|
+
if values.ndim != 2:
|
|
247
|
+
raise ValueError(f"TopKIndices2D expects a 2D tensor, got shape {values.shape}")
|
|
248
|
+
rows, cols = values.shape
|
|
249
|
+
flat = values.reshape(-1)
|
|
250
|
+
top_k = min(self.k, int(flat.shape[0]))
|
|
251
|
+
if top_k == 0:
|
|
252
|
+
registry[self.values_as] = flat[:0]
|
|
253
|
+
registry[self.row_indices_as] = np.zeros((0,), dtype=np.int64)
|
|
254
|
+
registry[self.col_indices_as] = np.zeros((0,), dtype=np.int64)
|
|
255
|
+
return registry
|
|
256
|
+
top_indices = np.argpartition(flat, -top_k)[-top_k:]
|
|
257
|
+
order = np.argsort(flat[top_indices])[::-1]
|
|
258
|
+
top_indices = top_indices[order].astype(np.int64, copy=False)
|
|
259
|
+
registry[self.values_as] = flat[top_indices]
|
|
260
|
+
registry[self.row_indices_as] = (top_indices // cols).astype(np.int64, copy=False)
|
|
261
|
+
registry[self.col_indices_as] = (top_indices % cols).astype(np.int64, copy=False)
|
|
262
|
+
return registry
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
@Operator
|
|
266
|
+
class ArgMax:
|
|
267
|
+
def __init__(self, src: str, axis: int = -1, as_: str | None = None):
|
|
268
|
+
self.src = src
|
|
269
|
+
self.axis = axis
|
|
270
|
+
self.as_ = as_ or src
|
|
271
|
+
|
|
272
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
273
|
+
tensor = registry[self.src]
|
|
274
|
+
axis = _normalize_axis(self.axis, tensor.ndim)
|
|
275
|
+
if tensor.shape[axis] == 0:
|
|
276
|
+
registry[self.as_] = np.zeros(_shape_without_axis(tensor.shape, axis), dtype=np.int32)
|
|
277
|
+
return registry
|
|
278
|
+
registry[self.as_] = np.argmax(tensor, axis=axis).astype(np.int32)
|
|
279
|
+
return registry
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
@Operator
|
|
283
|
+
class Softmax:
|
|
284
|
+
def __init__(self, src: str, axis: int = -1, as_: str | None = None):
|
|
285
|
+
self.src = src
|
|
286
|
+
self.axis = axis
|
|
287
|
+
self.as_ = as_ or src
|
|
288
|
+
|
|
289
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
290
|
+
x = registry[self.src]
|
|
291
|
+
axis = _normalize_axis(self.axis, x.ndim)
|
|
292
|
+
if x.shape[axis] == 0:
|
|
293
|
+
registry[self.as_] = x.copy()
|
|
294
|
+
return registry
|
|
295
|
+
shifted = x - np.max(x, axis=axis, keepdims=True)
|
|
296
|
+
exp = np.exp(shifted)
|
|
297
|
+
registry[self.as_] = exp / np.sum(exp, axis=axis, keepdims=True)
|
|
298
|
+
return registry
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
@Operator
|
|
302
|
+
class Sigmoid:
|
|
303
|
+
def __init__(self, src: str, as_: str | None = None):
|
|
304
|
+
self.src = src
|
|
305
|
+
self.as_ = as_ or src
|
|
306
|
+
|
|
307
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
308
|
+
x = registry[self.src]
|
|
309
|
+
positive = x >= 0
|
|
310
|
+
result = np.empty_like(x)
|
|
311
|
+
result[positive] = 1.0 / (1.0 + np.exp(-x[positive]))
|
|
312
|
+
exp_values = np.exp(x[~positive])
|
|
313
|
+
result[~positive] = exp_values / (1.0 + exp_values)
|
|
314
|
+
registry[self.as_] = result
|
|
315
|
+
return registry
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
@Operator
|
|
319
|
+
class MultiplyTensors:
|
|
320
|
+
def __init__(self, left: str, right: str, as_: str | None = None):
|
|
321
|
+
self.left = left
|
|
322
|
+
self.right = right
|
|
323
|
+
self.as_ = as_ or left
|
|
324
|
+
|
|
325
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
326
|
+
registry[self.as_] = registry[self.left] * registry[self.right]
|
|
327
|
+
return registry
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
@Operator
|
|
331
|
+
class CreateTensorMask:
|
|
332
|
+
def __init__(self, src: str, predicate: Callable[[np.ndarray], TensorMask], as_: str):
|
|
333
|
+
self.src = src
|
|
334
|
+
self.as_ = as_
|
|
335
|
+
self.predicate = predicate
|
|
336
|
+
|
|
337
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
338
|
+
registry[self.as_] = np.asarray(self.predicate(registry[self.src]), dtype=bool)
|
|
339
|
+
return registry
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
BinarizeTensor = CreateTensorMask
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
@Operator
|
|
346
|
+
class CreateTensorMaskByThreshold:
|
|
347
|
+
def __init__(self, src: str, threshold: float, as_: str | None = None):
|
|
348
|
+
self._inner = CreateTensorMask(
|
|
349
|
+
src=src,
|
|
350
|
+
as_=as_ or src,
|
|
351
|
+
predicate=lambda tensor: tensor >= threshold,
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
355
|
+
return self._inner(registry)
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
BinarizeTensorByThreshold = CreateTensorMaskByThreshold
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
@Operator
|
|
362
|
+
class ApplyTensorMask:
|
|
363
|
+
def __init__(self, *srcs: str, mask: str, as_: str | tuple[str, ...] | None = None):
|
|
364
|
+
self.srcs = srcs
|
|
365
|
+
self.mask = mask
|
|
366
|
+
self.dst_names = resolve_multi_output_names("ApplyTensorMask", srcs, as_)
|
|
367
|
+
|
|
368
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
369
|
+
mask = registry[self.mask]
|
|
370
|
+
for src, dst in zip(self.srcs, self.dst_names, strict=True):
|
|
371
|
+
registry[dst] = registry[src][mask]
|
|
372
|
+
return registry
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
@Operator
|
|
376
|
+
class SelectTensors:
|
|
377
|
+
def __init__(self, *srcs: str, indices: str, as_: str | tuple[str, ...] | None = None):
|
|
378
|
+
self.srcs = srcs
|
|
379
|
+
self.indices = indices
|
|
380
|
+
self.dst_names = resolve_multi_output_names("SelectTensors", srcs, as_)
|
|
381
|
+
|
|
382
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
383
|
+
indices = registry[self.indices]
|
|
384
|
+
if np.issubdtype(indices.dtype, np.bool_):
|
|
385
|
+
raise TypeError("SelectTensors indices must be integers; use ApplyTensorMask for boolean masks.")
|
|
386
|
+
for src, dst in zip(self.srcs, self.dst_names, strict=True):
|
|
387
|
+
registry[dst] = registry[src][indices]
|
|
388
|
+
return registry
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
@Operator
|
|
392
|
+
class FilterTensors:
|
|
393
|
+
def __init__(
|
|
394
|
+
self,
|
|
395
|
+
*srcs: str,
|
|
396
|
+
by: str,
|
|
397
|
+
predicate: Callable[[np.ndarray], TensorMask],
|
|
398
|
+
as_: str | tuple[str, ...] | None = None,
|
|
399
|
+
):
|
|
400
|
+
self.srcs = srcs
|
|
401
|
+
self.by = by
|
|
402
|
+
self.predicate = predicate
|
|
403
|
+
self.dst_names = resolve_multi_output_names("FilterTensors", srcs, as_)
|
|
404
|
+
|
|
405
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
406
|
+
mask = np.asarray(self.predicate(registry[self.by]))
|
|
407
|
+
if not np.issubdtype(mask.dtype, np.bool_):
|
|
408
|
+
raise TypeError("FilterTensors predicate must return a boolean mask.")
|
|
409
|
+
for src, dst in zip(self.srcs, self.dst_names, strict=True):
|
|
410
|
+
registry[dst] = registry[src][mask]
|
|
411
|
+
return registry
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
@Operator
|
|
415
|
+
class MapTensor:
|
|
416
|
+
def __init__(self, src: str, fn: Callable[[np.ndarray], np.ndarray], as_: str | None = None):
|
|
417
|
+
self.src = src
|
|
418
|
+
self.fn = fn
|
|
419
|
+
self.as_ = as_ or src
|
|
420
|
+
|
|
421
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
422
|
+
registry[self.as_] = self.fn(registry[self.src])
|
|
423
|
+
return registry
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
@Operator
|
|
427
|
+
class SortTensorsBy:
|
|
428
|
+
def __init__(
|
|
429
|
+
self,
|
|
430
|
+
*srcs: str,
|
|
431
|
+
by: str,
|
|
432
|
+
descending: bool = True,
|
|
433
|
+
as_: str | tuple[str, ...] | None = None,
|
|
434
|
+
):
|
|
435
|
+
all_srcs = (by,) + tuple(src for src in srcs if src != by)
|
|
436
|
+
self.srcs = all_srcs
|
|
437
|
+
self.by = by
|
|
438
|
+
self.descending = descending
|
|
439
|
+
self.dst_names = resolve_multi_output_names("SortTensorsBy", all_srcs, as_)
|
|
440
|
+
|
|
441
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
442
|
+
order = np.argsort(registry[self.by])
|
|
443
|
+
if self.descending:
|
|
444
|
+
order = order[::-1]
|
|
445
|
+
for src, dst in zip(self.srcs, self.dst_names, strict=True):
|
|
446
|
+
registry[dst] = registry[src][order]
|
|
447
|
+
return registry
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
@Operator
|
|
451
|
+
class Collate:
|
|
452
|
+
def __call__(self, tensors: list[TensorPayload]) -> TensorPayload:
|
|
453
|
+
if not tensors:
|
|
454
|
+
raise ValueError("Collate received an empty list")
|
|
455
|
+
arrays = [t.array for t in tensors]
|
|
456
|
+
if arrays[0].ndim == 4 and arrays[0].shape[0] == 1:
|
|
457
|
+
batched = np.concatenate(arrays, axis=0)
|
|
458
|
+
else:
|
|
459
|
+
batched = np.stack(arrays, axis=0)
|
|
460
|
+
return TensorPayload(array=batched, layout=tensors[0].layout, dtype=tensors[0].dtype)
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
@Operator
|
|
464
|
+
class Scale:
|
|
465
|
+
def __init__(self, src: str, by: float | tuple | list, as_: str | None = None):
|
|
466
|
+
self.src = src
|
|
467
|
+
self.by = np.asarray(by)
|
|
468
|
+
self.as_ = as_ or src
|
|
469
|
+
|
|
470
|
+
def __call__(self, registry: TensorRegistry) -> TensorRegistry:
|
|
471
|
+
tensor = registry[self.src]
|
|
472
|
+
registry[self.as_] = tensor * self.by.astype(tensor.dtype)
|
|
473
|
+
return registry
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"TensorPayload",
|
|
9
|
+
"TensorRegistry",
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class TensorPayload:
|
|
15
|
+
array: np.ndarray
|
|
16
|
+
layout: str
|
|
17
|
+
dtype: str
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class TensorRegistry:
|
|
21
|
+
"""Mutable named store for intermediate tensors during post-processing."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, tensors: dict[str, np.ndarray] | None = None):
|
|
24
|
+
self._tensors: dict[str, np.ndarray] = dict(tensors) if tensors else {}
|
|
25
|
+
|
|
26
|
+
def __getitem__(self, name: str) -> np.ndarray:
|
|
27
|
+
try:
|
|
28
|
+
return self._tensors[name]
|
|
29
|
+
except KeyError:
|
|
30
|
+
available = sorted(self._tensors)
|
|
31
|
+
raise KeyError(f"Tensor {name!r} not found in registry. Available: {available}")
|
|
32
|
+
|
|
33
|
+
def __setitem__(self, name: str, value: np.ndarray) -> None:
|
|
34
|
+
self._tensors[name] = value
|
|
35
|
+
|
|
36
|
+
def __contains__(self, name: str) -> bool:
|
|
37
|
+
return name in self._tensors
|
|
38
|
+
|
|
39
|
+
def keys(self) -> object:
|
|
40
|
+
return self._tensors.keys()
|
|
41
|
+
|
|
42
|
+
def __repr__(self) -> str:
|
|
43
|
+
shapes = {k: v.shape for k, v in self._tensors.items()}
|
|
44
|
+
return f"TensorRegistry({shapes})"
|