assassinlike commited on
Commit
1d852b7
·
verified ·
1 Parent(s): 69ecd35

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/licenses/LICENSE +202 -0
  2. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/__init__.cpython-310.pyc +0 -0
  3. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/_impl.cpython-310.pyc +0 -0
  4. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/_version.cpython-310.pyc +0 -0
  5. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/__init__.py +0 -0
  6. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/__pycache__/__init__.cpython-310.pyc +0 -0
  7. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/__pycache__/test_sniffio.cpython-310.pyc +0 -0
  8. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/test_sniffio.py +84 -0
  9. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/fused_pad_token_groups.cu +241 -0
  10. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mx_block_rearrange_2d_M_groups.cu +878 -0
  11. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mxfp8_cuda.cu +131 -0
  12. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mxfp8_extension.cpp +428 -0
  13. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e4m3e4m3.cu +37 -0
  14. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e4m3e5m2.cu +37 -0
  15. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e5m2e4m3.cu +37 -0
  16. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e5m2e5m2.cu +37 -0
  17. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_f8f8.cu +72 -0
  18. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/to_sparse_semi_structured_cutlass_sm9x/to_sparse_semi_structured_cutlass_sm9x_f8.cu +44 -0
  19. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/experimental/ops/mps/__pycache__/utils.cpython-310.pyc +0 -0
  20. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/__init__.cpython-310.pyc +0 -0
  21. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/__main__.cpython-310.pyc +0 -0
  22. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_analytics.cpython-310.pyc +0 -0
  23. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_iterutils.cpython-310.pyc +0 -0
  24. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_strutils.cpython-310.pyc +0 -0
  25. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/data_types.cpython-310.pyc +0 -0
  26. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/env.cpython-310.pyc +0 -0
  27. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/jupyter.cpython-310.pyc +0 -0
  28. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/sklearn.cpython-310.pyc +0 -0
  29. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/trigger.cpython-310.pyc +0 -0
  30. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/util.cpython-310.pyc +0 -0
  31. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_agent.cpython-310.pyc +0 -0
  32. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_controller.cpython-310.pyc +0 -0
  33. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_run.cpython-310.pyc +0 -0
  34. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/__init__.py +39 -0
  35. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/base.py +145 -0
  36. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/field_types.py +21 -0
  37. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/pagination.py +90 -0
  38. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/utils.py +39 -0
  39. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/agents/__init__.py +0 -0
  40. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/agents/pyagent.py +393 -0
  41. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/analytics/__init__.py +3 -0
  42. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/analytics/sentry.py +306 -0
  43. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__init__.py +50 -0
  44. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/__init__.cpython-310.pyc +0 -0
  45. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/attrs.cpython-310.pyc +0 -0
  46. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/internal.cpython-310.pyc +0 -0
  47. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/normalize.cpython-310.pyc +0 -0
  48. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/paginator.cpython-310.pyc +0 -0
  49. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__init__.py +118 -0
  50. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/__init__.cpython-310.pyc +0 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/licenses/LICENSE ADDED
@@ -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.
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (438 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/_impl.cpython-310.pyc ADDED
Binary file (2.68 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/_version.cpython-310.pyc ADDED
Binary file (202 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/__init__.py ADDED
File without changes
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (188 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/__pycache__/test_sniffio.cpython-310.pyc ADDED
Binary file (2.13 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/test_sniffio.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ import pytest
5
+
6
+ from .. import (
7
+ current_async_library, AsyncLibraryNotFoundError,
8
+ current_async_library_cvar, thread_local
9
+ )
10
+
11
+
12
+ def test_basics_cvar():
13
+ with pytest.raises(AsyncLibraryNotFoundError):
14
+ current_async_library()
15
+
16
+ token = current_async_library_cvar.set("generic-lib")
17
+ try:
18
+ assert current_async_library() == "generic-lib"
19
+ finally:
20
+ current_async_library_cvar.reset(token)
21
+
22
+ with pytest.raises(AsyncLibraryNotFoundError):
23
+ current_async_library()
24
+
25
+
26
+ def test_basics_tlocal():
27
+ with pytest.raises(AsyncLibraryNotFoundError):
28
+ current_async_library()
29
+
30
+ old_name, thread_local.name = thread_local.name, "generic-lib"
31
+ try:
32
+ assert current_async_library() == "generic-lib"
33
+ finally:
34
+ thread_local.name = old_name
35
+
36
+ with pytest.raises(AsyncLibraryNotFoundError):
37
+ current_async_library()
38
+
39
+
40
+ def test_asyncio():
41
+ import asyncio
42
+
43
+ with pytest.raises(AsyncLibraryNotFoundError):
44
+ current_async_library()
45
+
46
+ ran = []
47
+
48
+ async def this_is_asyncio():
49
+ assert current_async_library() == "asyncio"
50
+ # Call it a second time to exercise the caching logic
51
+ assert current_async_library() == "asyncio"
52
+ ran.append(True)
53
+
54
+ asyncio.run(this_is_asyncio())
55
+ assert ran == [True]
56
+
57
+ with pytest.raises(AsyncLibraryNotFoundError):
58
+ current_async_library()
59
+
60
+
61
+ @pytest.mark.skipif(
62
+ sys.version_info >= (3, 12),
63
+ reason=
64
+ "curio broken on 3.12 (https://github.com/python-trio/sniffio/pull/42)",
65
+ )
66
+ def test_curio():
67
+ import curio
68
+
69
+ with pytest.raises(AsyncLibraryNotFoundError):
70
+ current_async_library()
71
+
72
+ ran = []
73
+
74
+ async def this_is_curio():
75
+ assert current_async_library() == "curio"
76
+ # Call it a second time to exercise the caching logic
77
+ assert current_async_library() == "curio"
78
+ ran.append(True)
79
+
80
+ curio.run(this_is_curio)
81
+ assert ran == [True]
82
+
83
+ with pytest.raises(AsyncLibraryNotFoundError):
84
+ current_async_library()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/fused_pad_token_groups.cu ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <cuda_runtime.h>
2
+ #include <cuda_bf16.h>
3
+ #include <cstdint>
4
+ #include <cstdio>
5
+
6
+ #define CUDA_CHECK(call) \
7
+ do { \
8
+ cudaError_t error = call; \
9
+ if (error != cudaSuccess) { \
10
+ fprintf(stderr, "CUDA error at %s:%d: %s\n", __FILE__, __LINE__, \
11
+ cudaGetErrorString(error)); \
12
+ exit(EXIT_FAILURE); \
13
+ } \
14
+ } while(0)
15
+
16
+ __host__ __device__ __forceinline__ int ceil_div(int a, int b) {
17
+ return (a + b - 1) / b;
18
+ }
19
+
20
+ __device__ __forceinline__ int find_group_id(
21
+ int row_idx,
22
+ const int32_t* __restrict__ group_end_offsets,
23
+ int num_groups
24
+ ) {
25
+ // linear prefix sum lookup (same or faster than binary search for small num groups, which ours are <= 32)
26
+ int group_id = 0;
27
+ while (group_id < num_groups - 1 && row_idx >= group_end_offsets[group_id]) {
28
+ ++group_id;
29
+ }
30
+ return group_id;
31
+ }
32
+
33
+ __global__ void fused_pad_token_groups_kernel(
34
+ const __nv_bfloat16* __restrict__ input,
35
+ const int32_t* __restrict__ group_end_offsets,
36
+ const int32_t* __restrict__ padded_group_start_offsets,
37
+ __nv_bfloat16* __restrict__ output,
38
+ int num_tokens,
39
+ int dim,
40
+ int num_groups
41
+ ) {
42
+ constexpr int WARP_SIZE = 32;
43
+ const int lane_id = threadIdx.x % WARP_SIZE;
44
+ const int warp_id_in_block = threadIdx.x / WARP_SIZE;
45
+ const int warps_per_block = blockDim.x / WARP_SIZE; // each warp handles 1 row
46
+ const int global_row_idx = blockIdx.x * warps_per_block + warp_id_in_block;
47
+
48
+ if (global_row_idx >= num_tokens) return;
49
+
50
+ // one thread finds which group this row belongs to, then broadcasts to other lanes via warp shuffle
51
+ int group_id;
52
+ if (lane_id == 0) {
53
+ group_id = find_group_id(global_row_idx, group_end_offsets, num_groups);
54
+ }
55
+ group_id = __shfl_sync(0xffffffff, group_id, 0);
56
+
57
+ int group_start = (group_id > 0) ? group_end_offsets[group_id - 1] : 0;
58
+ int padded_start = padded_group_start_offsets[group_id];
59
+ int offset_in_group = global_row_idx - group_start;
60
+ int output_row = padded_start + offset_in_group;
61
+
62
+ const __nv_bfloat16* row_in = input + global_row_idx * dim;
63
+ __nv_bfloat16* row_out = output + output_row * dim;
64
+
65
+ // vectorized copy for all complete float4 chunks (8 bf16 elements each)
66
+ int num_vecs = dim / 8;
67
+ if (num_vecs > 0) {
68
+ const float4* in_vec = reinterpret_cast<const float4*>(row_in);
69
+ float4* out_vec = reinterpret_cast<float4*>(row_out);
70
+
71
+ for (int i = lane_id; i < num_vecs; i += 32) {
72
+ out_vec[i] = in_vec[i];
73
+ }
74
+ }
75
+
76
+ // scalar copy for remaining elems
77
+ int elems_covered = num_vecs * 8;
78
+ for (int i = elems_covered + lane_id; i < dim; i += 32) {
79
+ row_out[i] = row_in[i];
80
+ }
81
+ }
82
+
83
+ __global__ void fused_unpad_token_groups_kernel(
84
+ const __nv_bfloat16* __restrict__ input,
85
+ const int32_t* __restrict__ group_end_offsets,
86
+ const int32_t* __restrict__ padded_group_start_offsets,
87
+ __nv_bfloat16* __restrict__ output,
88
+ int num_tokens,
89
+ int dim,
90
+ int num_groups
91
+ ) {
92
+ constexpr int WARP_SIZE = 32;
93
+ const int lane_id = threadIdx.x % WARP_SIZE;
94
+ const int warp_id_in_block = threadIdx.x / WARP_SIZE;
95
+ const int warps_per_block = blockDim.x / WARP_SIZE; // each warp handles 1 row
96
+ const int global_row_idx = blockIdx.x * warps_per_block + warp_id_in_block;
97
+
98
+ if (global_row_idx >= num_tokens) return;
99
+
100
+ // one thread finds which group this row belongs to, then broadcasts to other lanes via warp shuffle
101
+ int group_id;
102
+ if (lane_id == 0) {
103
+ group_id = find_group_id(global_row_idx, group_end_offsets, num_groups);
104
+ }
105
+ group_id = __shfl_sync(0xffffffff, group_id, 0);
106
+
107
+ int group_start = (group_id > 0) ? group_end_offsets[group_id - 1] : 0;
108
+ int padded_start = padded_group_start_offsets[group_id];
109
+ int offset_in_group = global_row_idx - group_start;
110
+ int input_row = padded_start + offset_in_group;
111
+
112
+ const __nv_bfloat16* row_in = input + input_row * dim;
113
+ __nv_bfloat16* row_out = output + global_row_idx * dim;
114
+
115
+ // vectorized copy for all complete float4 chunks (8 bf16 elements each)
116
+ int num_vecs = dim / 8;
117
+ if (num_vecs > 0) {
118
+ const float4* in_vec = reinterpret_cast<const float4*>(row_in);
119
+ float4* out_vec = reinterpret_cast<float4*>(row_out);
120
+
121
+ for (int i = lane_id; i < num_vecs; i += 32) {
122
+ out_vec[i] = in_vec[i];
123
+ }
124
+ }
125
+
126
+ // scalar copy for remaining elems
127
+ int elems_covered = num_vecs * 8;
128
+ for (int i = elems_covered + lane_id; i < dim; i += 32) {
129
+ row_out[i] = row_in[i];
130
+ }
131
+ }
132
+
133
+ __global__ void compute_padded_offsets_kernel(
134
+ const int32_t* __restrict__ group_end_offsets,
135
+ int32_t* __restrict__ padded_group_start_offsets,
136
+ int32_t* __restrict__ padded_group_end_offsets,
137
+ int num_groups,
138
+ int alignment_size
139
+ ) {
140
+ if (threadIdx.x == 0) {
141
+ int cumulative = 0;
142
+
143
+ for (int g = 0; g < num_groups; g++) {
144
+ int group_start = (g > 0) ? group_end_offsets[g - 1] : 0;
145
+ int group_end = group_end_offsets[g];
146
+ int group_size = group_end - group_start;
147
+
148
+ int padded_size = ((group_size + alignment_size - 1) / alignment_size) * alignment_size;
149
+
150
+ padded_group_start_offsets[g] = cumulative;
151
+ cumulative += padded_size;
152
+ padded_group_end_offsets[g] = cumulative;
153
+ }
154
+ }
155
+ }
156
+
157
+ namespace mxfp8 {
158
+
159
+ void launch_compute_padded_offsets_cuda(
160
+ const int32_t* group_end_offsets_ptr,
161
+ int32_t* padded_group_start_offsets_ptr,
162
+ int32_t* padded_group_end_offsets_ptr,
163
+ int num_groups,
164
+ int alignment_size,
165
+ cudaStream_t stream
166
+ ) {
167
+ // Single warp is enough for num_groups <= 32
168
+ compute_padded_offsets_kernel<<<1, 32, 0, stream>>>(
169
+ group_end_offsets_ptr,
170
+ padded_group_start_offsets_ptr,
171
+ padded_group_end_offsets_ptr,
172
+ num_groups,
173
+ alignment_size
174
+ );
175
+
176
+ CUDA_CHECK(cudaGetLastError());
177
+ }
178
+
179
+ void launch_fused_pad_token_groups_cuda(
180
+ const void* input_ptr,
181
+ const int32_t* group_end_offsets_ptr,
182
+ const int32_t* padded_group_start_offsets_ptr,
183
+ void* output_ptr,
184
+ int num_tokens,
185
+ int dim,
186
+ int num_groups,
187
+ int dtype_size,
188
+ int dtype_enum,
189
+ cudaStream_t stream
190
+ ) {
191
+ const int WARPS_PER_BLOCK = 8;
192
+ const int THREADS_PER_WARP = 32;
193
+ const int THREADS_PER_BLOCK = WARPS_PER_BLOCK * THREADS_PER_WARP; // 256 threads
194
+
195
+ const int num_blocks = ceil_div(num_tokens, WARPS_PER_BLOCK);
196
+
197
+ fused_pad_token_groups_kernel<<<num_blocks, THREADS_PER_BLOCK, 0, stream>>>(
198
+ reinterpret_cast<const __nv_bfloat16*>(input_ptr),
199
+ group_end_offsets_ptr,
200
+ padded_group_start_offsets_ptr,
201
+ reinterpret_cast<__nv_bfloat16*>(output_ptr),
202
+ num_tokens,
203
+ dim,
204
+ num_groups
205
+ );
206
+
207
+ CUDA_CHECK(cudaGetLastError());
208
+ }
209
+
210
+ void launch_fused_unpad_token_groups_cuda(
211
+ const void* input_ptr,
212
+ const int32_t* group_end_offsets_ptr,
213
+ const int32_t* padded_group_start_offsets_ptr,
214
+ void* output_ptr,
215
+ int num_tokens,
216
+ int dim,
217
+ int num_groups,
218
+ int dtype_size,
219
+ int dtype_enum,
220
+ cudaStream_t stream
221
+ ) {
222
+ const int WARPS_PER_BLOCK = 8;
223
+ const int THREADS_PER_WARP = 32;
224
+ const int THREADS_PER_BLOCK = WARPS_PER_BLOCK * THREADS_PER_WARP; // 256 threads
225
+
226
+ const int num_blocks = ceil_div(num_tokens, WARPS_PER_BLOCK);
227
+
228
+ fused_unpad_token_groups_kernel<<<num_blocks, THREADS_PER_BLOCK, 0, stream>>>(
229
+ reinterpret_cast<const __nv_bfloat16*>(input_ptr),
230
+ group_end_offsets_ptr,
231
+ padded_group_start_offsets_ptr,
232
+ reinterpret_cast<__nv_bfloat16*>(output_ptr),
233
+ num_tokens,
234
+ dim,
235
+ num_groups
236
+ );
237
+
238
+ CUDA_CHECK(cudaGetLastError());
239
+ }
240
+
241
+ } // namespace mxfp8
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mx_block_rearrange_2d_M_groups.cu ADDED
@@ -0,0 +1,878 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * MX Block Rearrange 2D Kernel for M-Groups (Groups along row dimension)
3
+ *
4
+ * TERMINOLOGY:
5
+ * - SF Tile: A 128x4 scale factor tile (512 bytes in blocked layout)
6
+ * - SF_ROWS = 128 rows
7
+ * - SF_COLS = 4 columns
8
+ * - Each SF tile is stored contiguously in the output blocked layout
9
+ *
10
+ * - Chunk: A 128xCHUNK_WIDTH region (128 rows × 16, 32, 64, or 128 columns)
11
+ * - One TMA load brings one chunk from GMEM to SMEM
12
+ * - Contains multiple SF tiles horizontally (CHUNK_WIDTH/SF_COLS = 4, 8, 16, or 32)
13
+ * - Each chunk is processed independently in the pipeline
14
+ *
15
+ * - Superblock: CHUNKS_PER_TB chunks stacked vertically
16
+ * - Processed by one thread block
17
+ * - Height = SF_ROWS * CHUNKS_PER_TB (128, 512, 1024, or 2048 rows)
18
+ * - Width = CHUNK_WIDTH (16, 32, 64, or 128 columns)
19
+ * - Grid is organized as (num_col_chunks, num_row_superblocks)
20
+ */
21
+ #include <cstdint>
22
+ #include <cstdio>
23
+ #include <cstdlib>
24
+
25
+ #include <cuda.h>
26
+ #include <cuda_runtime.h>
27
+ #include <cudaTypedefs.h>
28
+ #include "ptx.cuh"
29
+
30
+ // Overloaded error checking for both CUDA driver API (CUresult) and runtime API (cudaError_t)
31
+ inline void cuda_check_impl(CUresult result, const char* file, int line) {
32
+ if (result != CUDA_SUCCESS) {
33
+ fprintf(stderr, "CUDA Driver Error at %s:%d - Error code: %d\n", file, line, (int)result);
34
+ exit(EXIT_FAILURE);
35
+ }
36
+ }
37
+
38
+ inline void cuda_check_impl(cudaError_t result, const char* file, int line) {
39
+ if (result != cudaSuccess) {
40
+ fprintf(stderr, "CUDA Runtime Error at %s:%d - %s\n", file, line,
41
+ cudaGetErrorString(result));
42
+ exit(EXIT_FAILURE);
43
+ }
44
+ }
45
+
46
+ #define CUDA_CHECK(result) cuda_check_impl((result), __FILE__, __LINE__)
47
+
48
+ // Get the driver entry point for cuTensorMapEncodeTiled (used for TMA tensor maps)
49
+ inline void* get_driver_ptr() {
50
+ static void *driver_ptr = nullptr;
51
+ if (!driver_ptr) {
52
+ cudaDriverEntryPointQueryResult result;
53
+ CUDA_CHECK(cudaGetDriverEntryPoint("cuTensorMapEncodeTiled", &driver_ptr,
54
+ cudaEnableDefault, &result));
55
+ }
56
+ return driver_ptr;
57
+ }
58
+
59
+ // Device helper: ceiling division
60
+ __device__ __forceinline__ int ceil_div(int a, int b) {
61
+ return (a + b - 1) / b;
62
+ }
63
+
64
+ #define SF_ROWS 128
65
+ #define SF_COLS 4
66
+
67
+ // Each thread reads 16 bytes (vectorized uint4 load)
68
+ #define BYTES_PER_THREAD 16
69
+
70
+ // Double buffering for pipelined TMA loads/stores
71
+ #define NUM_BUFFERS 2
72
+
73
+
74
+
75
+ // Here the chunks are 128x64/128x128 and superblock contains multiple vertical chunks (e.g., 4 chunks of 128x64 would be 512x64).
76
+ template <int CHUNKS_PER_TB>
77
+ __device__ void find_group_and_local_offset_for_superblock(
78
+ int row_superblock_pid,
79
+ const int32_t* __restrict__ input_group_end_offsets,
80
+ int num_groups,
81
+ int* __restrict__ smem_data,
82
+ int& group_id,
83
+ int& superblock_idx_in_group,
84
+ int& superblocks_until_end
85
+ ) {
86
+ // Thread 0 computes how many superblocks span each group
87
+ if (threadIdx.x == 0) {
88
+ constexpr int SUPERBLOCK_ROWS = SF_ROWS * CHUNKS_PER_TB;
89
+ int superblock_cumsum = 0;
90
+ for (int g = 0; g < num_groups; g++) {
91
+ int input_group_start = (g > 0) ? input_group_end_offsets[g - 1] : 0;
92
+ int input_group_end = input_group_end_offsets[g];
93
+ int group_size = input_group_end - input_group_start;
94
+ int num_superblocks_in_group = ceil_div(group_size, SUPERBLOCK_ROWS);
95
+ smem_data[g] = num_superblocks_in_group;
96
+ superblock_cumsum += num_superblocks_in_group;
97
+ smem_data[num_groups + g] = superblock_cumsum;
98
+ }
99
+ }
100
+ __syncthreads();
101
+
102
+ // All threads use the SMEM cumsum to find their group
103
+ group_id = 0;
104
+ int superblock_cumsum_before = 0;
105
+ for (int g = 0; g < num_groups; g++) {
106
+ int cumsum_at_g = smem_data[num_groups + g];
107
+ if (row_superblock_pid < cumsum_at_g) {
108
+ group_id = g;
109
+ superblock_idx_in_group = row_superblock_pid - superblock_cumsum_before;
110
+ int superblocks_in_group = smem_data[g];
111
+ superblocks_until_end = superblocks_in_group - superblock_idx_in_group;
112
+ return;
113
+ }
114
+ superblock_cumsum_before = cumsum_at_g;
115
+ }
116
+
117
+ superblock_idx_in_group = 0;
118
+ superblocks_until_end = 0;
119
+ }
120
+
121
+ /**
122
+ * Compute the starting row in the output buffer for a given group.
123
+ * Each group is padded to a multiple of SF_ROWS (128) in the output.
124
+ */
125
+ __device__ __forceinline__ int compute_output_group_start_row(
126
+ int group_id,
127
+ const int32_t* input_group_end_offsets,
128
+ int num_groups,
129
+ int padding_size
130
+ ) {
131
+ int start_idx = 0;
132
+ for (int i = 0; i < group_id; i++) {
133
+ int prev_offset = (i > 0) ? input_group_end_offsets[i - 1] : 0;
134
+ int curr_offset = input_group_end_offsets[i];
135
+ int group_size = curr_offset - prev_offset;
136
+ int padded_size = ceil_div(group_size, padding_size) * padding_size;
137
+ start_idx += padded_size;
138
+ }
139
+ return start_idx;
140
+ }
141
+
142
+ /**
143
+ * Pipelined kernel for rearranging row-major scale data to blocked layout.
144
+ *
145
+ * Template parameters:
146
+ * - CHUNK_WIDTH: Width of each chunk (16, 32, 64, or 128 columns)
147
+ * - CHUNKS_PER_TB: Number of chunks per superblock (1, 4, 8, or 16)
148
+ *
149
+ * Grid dimensions:
150
+ * - blockIdx.x = column chunk index
151
+ * - blockIdx.y = row superblock index
152
+ *
153
+ * Thread block dimensions:
154
+ * - 128 threads for CHUNK_WIDTH=16 (128 rows × 1 thread/row)
155
+ * - 256 threads for CHUNK_WIDTH=32 (128 rows × 2 threads/row)
156
+ * - 512 threads for CHUNK_WIDTH=64 (128 rows × 4 threads/row)
157
+ * - 1024 threads for CHUNK_WIDTH=128 (128 rows × 8 threads/row)
158
+ */
159
+ template <int CHUNK_WIDTH, int CHUNKS_PER_TB>
160
+ __global__ void mx_blocked_layout_2d_M_groups_kernel(
161
+ const uint8_t* __restrict__ input_scales,
162
+ const int input_scale_stride_dim0,
163
+ const int scale_rows,
164
+ const int scale_cols,
165
+ const int padded_rows,
166
+ const int32_t* __restrict__ input_group_end_offsets,
167
+ uint8_t* __restrict__ output_scales,
168
+ const int output_stride_per_row_of_sf_tiles,
169
+ const int num_groups,
170
+ const __grid_constant__ CUtensorMap input_tensor_map
171
+ ) {
172
+ constexpr int output_stride_per_sf_tile = SF_ROWS * SF_COLS; // 512 bytes per SF tile
173
+ const int row_superblock_pid = blockIdx.y;
174
+ const int col_chunk_pid = blockIdx.x;
175
+ const int tid = threadIdx.x;
176
+ const bool is_master_thread = tid == 0;
177
+ constexpr int THREADS_PER_ROW = CHUNK_WIDTH / BYTES_PER_THREAD;
178
+ const int row_idx = tid / THREADS_PER_ROW;
179
+ const int col_idx = tid % THREADS_PER_ROW;
180
+
181
+ constexpr int CHUNK_SIZE_BYTES = SF_ROWS * CHUNK_WIDTH;
182
+
183
+ __shared__ int smem_group_data[64]; // Max 32 groups: [0..31] = superblocks per group, [32..63] = cumsum
184
+ __shared__ __align__(128) uint8_t smem_buffers[NUM_BUFFERS][CHUNK_SIZE_BYTES];
185
+
186
+ // Find which group this superblock belongs to and compute offsets
187
+ int group_idx;
188
+ int superblock_idx_in_group;
189
+ int superblocks_until_end;
190
+ find_group_and_local_offset_for_superblock<CHUNKS_PER_TB>(
191
+ row_superblock_pid,
192
+ input_group_end_offsets,
193
+ num_groups,
194
+ smem_group_data,
195
+ group_idx,
196
+ superblock_idx_in_group,
197
+ superblocks_until_end
198
+ );
199
+
200
+ // Early exit for padding superblocks beyond all groups
201
+ if (superblocks_until_end <= 0) {
202
+ return;
203
+ }
204
+
205
+ // Thread 0 computes group boundaries and broadcasts via SMEM
206
+ __shared__ int s_input_group_start_row;
207
+ __shared__ int s_input_group_end_row;
208
+ __shared__ int s_output_group_start_row;
209
+ if (tid == 0) {
210
+ s_input_group_start_row = (group_idx > 0) ? input_group_end_offsets[group_idx - 1] : 0;
211
+ s_input_group_end_row = input_group_end_offsets[group_idx];
212
+ s_output_group_start_row = compute_output_group_start_row(
213
+ group_idx, input_group_end_offsets, num_groups, SF_ROWS);
214
+ }
215
+ __syncthreads();
216
+ uint input_group_start_row = s_input_group_start_row;
217
+ uint input_group_end_row = s_input_group_end_row;
218
+ uint output_group_start_row = s_output_group_start_row;
219
+
220
+ // Compute base addresses for this superblock
221
+ constexpr int SUPERBLOCK_ROWS = SF_ROWS * CHUNKS_PER_TB;
222
+ const uint global_row_base = input_group_start_row + (superblock_idx_in_group * SUPERBLOCK_ROWS);
223
+ const uint global_col_base = col_chunk_pid * CHUNK_WIDTH;
224
+
225
+ // Thread's column offset and first SF tile index
226
+ const uint thread_col_start = col_idx * BYTES_PER_THREAD;
227
+ const uint first_sf_tile_idx = thread_col_start / SF_COLS;
228
+
229
+ // Initialize mbarriers for TMA load coordination
230
+ constexpr int NUM_THREADS = SF_ROWS * THREADS_PER_ROW;
231
+ __shared__ __align__(8) uint64_t mbar[NUM_BUFFERS];
232
+ initialize_barriers<NUM_BUFFERS, NUM_THREADS>(mbar, is_master_thread);
233
+
234
+ // Track barrier parity for double-buffered pipeline
235
+ int buf_parity[NUM_BUFFERS] = {0};
236
+
237
+ // Compute columns in this chunk (may be less than CHUNK_WIDTH for partial chunks)
238
+ // This is used for SMEM read stride and output bounds checking
239
+ // NOTE: TMA always loads the full tensor map box size regardless of this value
240
+ auto compute_cols_in_chunk = [&]() -> int {
241
+ const int remaining_cols = scale_cols - global_col_base;
242
+ return min(CHUNK_WIDTH, remaining_cols);
243
+ };
244
+ const int cols_in_chunk = compute_cols_in_chunk();
245
+
246
+ // The tensor map box width is min(CHUNK_WIDTH, scale_cols)
247
+ // TMA always loads this full box size (with OOB elements zero-filled)
248
+ const int tma_box_width = min(CHUNK_WIDTH, scale_cols);
249
+
250
+ // Func for async TMA load of a chunk of data to the given SMEM buffer
251
+ auto load_chunk = [&](int chunk_idx, int buf_idx) {
252
+ if (chunk_idx >= NUM_BUFFERS) {
253
+ // Wait for pending TMA stores to finish reading the SMEM buffer we're about to re-use
254
+ ptx::cp_async_bulk_wait_group_read<0>();
255
+ __syncthreads();
256
+ }
257
+
258
+ uint64_t* mbar_ptr = &mbar[buf_idx];
259
+ const uint32_t tma_x = global_col_base;
260
+ const uint32_t tma_y = global_row_base + (chunk_idx * SF_ROWS);
261
+
262
+ // IMPORTANT: TMA with OOB_FILL_NONE zero-fills OOB elements but reports
263
+ // the FULL box size to mbarrier, not the clamped size. The box size is
264
+ // fixed in the tensor map descriptor as (tma_box_width x SF_ROWS).
265
+ const int expected_bytes = SF_ROWS * tma_box_width;
266
+
267
+ copy_2d_to_shared(
268
+ (void*)&smem_buffers[buf_idx],
269
+ reinterpret_cast<const void*>(&input_tensor_map),
270
+ tma_x,
271
+ tma_y,
272
+ expected_bytes,
273
+ mbar_ptr,
274
+ is_master_thread
275
+ );
276
+ };
277
+
278
+ // Precompute blocked layout offset for this thread's row
279
+ int r_div_32 = row_idx >> 5; // row_idx / 32
280
+ int r_mod_32 = row_idx & 31; // row_idx % 32
281
+ int blocked_layout_row_offset = (r_mod_32 << 4) + (r_div_32 << 2); // r_mod_32 * 16 + r_div_32 * 4
282
+
283
+ // Func to process blocked layout transform in SMEM then store result to GMEM
284
+ auto process_chunk = [&](int chunk_idx, int buf_idx) {
285
+ // Wait for TMA load to complete
286
+ uint64_t* mbar_ptr = &mbar[buf_idx];
287
+ ptx::mbarrier_wait_parity(mbar_ptr, buf_parity[buf_idx]);
288
+ buf_parity[buf_idx] ^= 1;
289
+
290
+ // Fence to ensure TMA-written data is visible to all threads
291
+ ptx::fence_proxy_async_shared_cta();
292
+
293
+ // Read 16 bytes from row-major layout in SMEM. Coalesced, vectorized reads.
294
+ // TMA writes rows with stride = tma_box_width (the tensor map box size)
295
+ uint4 row_data = make_uint4(0, 0, 0, 0);
296
+ const uint32_t chunk_start_row = global_row_base + (chunk_idx * SF_ROWS);
297
+ const bool row_valid = chunk_start_row + row_idx < input_group_end_row;
298
+ const bool col_valid = thread_col_start < static_cast<uint>(cols_in_chunk);
299
+
300
+ if (row_valid && col_valid) {
301
+ row_data = *reinterpret_cast<uint4*>(
302
+ &smem_buffers[buf_idx][row_idx * tma_box_width + thread_col_start]);
303
+ }
304
+ __syncthreads(); // All threads must finish reading before overwriting
305
+
306
+ // Scatter 16 bytes to blocked layout (4 bytes per SF tile)
307
+ // Only write to SMEM if this thread's columns are within the valid range
308
+ constexpr int SF_TILES_PER_THREAD = BYTES_PER_THREAD / SF_COLS;
309
+ if (col_valid) {
310
+ #pragma unroll
311
+ for (int i = 0; i < SF_TILES_PER_THREAD; i++) {
312
+ const int sf_tile_idx = first_sf_tile_idx + i;
313
+ const uint32_t data = reinterpret_cast<const uint32_t*>(&row_data)[i];
314
+ *reinterpret_cast<uint32_t*>(
315
+ &smem_buffers[buf_idx][blocked_layout_row_offset + sf_tile_idx * output_stride_per_sf_tile]
316
+ ) = data;
317
+ }
318
+ }
319
+ __syncthreads();
320
+
321
+ // Fence to ensure SMEM writes are visible to TMA async proxy
322
+ ptx::fence_proxy_async_shared_cta();
323
+
324
+ // Compute output tile coordinates
325
+ const int chunk_sf_row_tile = (superblock_idx_in_group * CHUNKS_PER_TB) + chunk_idx;
326
+ const int global_sf_row_tile = (output_group_start_row / SF_ROWS) + chunk_sf_row_tile;
327
+
328
+ // Number of valid SF tiles horizontally in this chunk (may be fewer for partial chunks)
329
+ const int valid_sf_tiles = ceil_div(cols_in_chunk, SF_COLS);
330
+ constexpr int SF_TILES_PER_CHUNK = CHUNK_WIDTH / SF_COLS; // Max tiles for full chunk
331
+ const int col_sf_tile_start = col_chunk_pid * SF_TILES_PER_CHUNK;
332
+
333
+ // Check if this chunk has valid data
334
+ const uint32_t rows_remaining_in_group = (input_group_end_row > chunk_start_row)
335
+ ? (input_group_end_row - chunk_start_row) : 0;
336
+
337
+ // Issue TMA 1D stores for each valid SF tile
338
+ // Each store moves one 512-byte SF tile from SMEM to GMEM
339
+ if (rows_remaining_in_group > 0 && is_master_thread) {
340
+ constexpr int SF_TILE_SIZE_BYTES = SF_ROWS * SF_COLS; // 512 bytes
341
+ const int sf_tiles_per_row = output_stride_per_row_of_sf_tiles / output_stride_per_sf_tile;
342
+
343
+ // Only store valid SF tiles (not the full CHUNK_WIDTH for partial chunks)
344
+ for (int tile = 0; tile < valid_sf_tiles; tile++) {
345
+ const int col_sf_tile = col_sf_tile_start + tile;
346
+ const int linear_sf_tile_idx = global_sf_row_tile * sf_tiles_per_row + col_sf_tile;
347
+
348
+ uint64_t* dst_gmem = reinterpret_cast<uint64_t*>(
349
+ output_scales + linear_sf_tile_idx * SF_TILE_SIZE_BYTES);
350
+ const uint32_t smem_sf_tile_offset = tile * SF_TILE_SIZE_BYTES;
351
+
352
+ ptx::cp_async_bulk_tensor_1d_shared_to_global(
353
+ dst_gmem,
354
+ reinterpret_cast<const uint64_t*>(&smem_buffers[buf_idx][smem_sf_tile_offset]),
355
+ SF_TILE_SIZE_BYTES
356
+ );
357
+ }
358
+ ptx::cp_async_bulk_commit_group();
359
+ }
360
+ };
361
+
362
+ // --- Main processing loop for superblock ---
363
+ // Compute how many chunks to process in this superblock
364
+ constexpr int BUFFER_MOD = NUM_BUFFERS - 1;
365
+ const int first_row_in_superblock = input_group_start_row + (superblock_idx_in_group * SUPERBLOCK_ROWS);
366
+ const int remaining_rows_in_group = input_group_end_row - first_row_in_superblock;
367
+ const int remaining_chunks = ceil_div(remaining_rows_in_group, SF_ROWS);
368
+ const int chunks_to_process = min(CHUNKS_PER_TB, remaining_chunks);
369
+
370
+ if (chunks_to_process == 0) {
371
+ destroy_barriers<NUM_BUFFERS>(mbar, is_master_thread);
372
+ return;
373
+ }
374
+
375
+ // Pipeline to overlap loads of chunk N+1 with process + store of chunk N
376
+ for (int chunk = 0; chunk < chunks_to_process; chunk++) {
377
+ int buf_idx = chunk & BUFFER_MOD; // chunk % num_buffers
378
+ load_chunk(chunk, buf_idx);
379
+ if (chunk > 0) {
380
+ int prev_buf_idx = (chunk - 1) & BUFFER_MOD; // (chunk - 1) % num_buffers
381
+ process_chunk(chunk - 1, prev_buf_idx);
382
+ }
383
+ }
384
+
385
+ // Process last chunk
386
+ int last_buf_idx = (chunks_to_process - 1) & BUFFER_MOD;
387
+ process_chunk(chunks_to_process - 1, last_buf_idx);
388
+
389
+ // Wait for all pending TMA stores to complete before exiting
390
+ ptx::cp_async_bulk_wait_group();
391
+
392
+ // Clean up barriers
393
+ destroy_barriers<NUM_BUFFERS>(mbar, is_master_thread);
394
+ }
395
+
396
+ // Reference: https://docs.nvidia.com/cuda/cuda-c-programming-guide/#using-tma-to-transfer-multi-dimensional-arrays
397
+ void create_tensor_map(
398
+ void* tensor_ptr,
399
+ CUtensorMap& tensor_map,
400
+ const uint64_t gmem_width,
401
+ const uint64_t gmem_height,
402
+ const uint32_t smem_width,
403
+ const uint32_t smem_height
404
+ ) {
405
+ // Validate tensor pointer
406
+ if (tensor_ptr == nullptr) {
407
+ fprintf(stderr, "ERROR: tensor_ptr is NULL!\n");
408
+ exit(EXIT_FAILURE);
409
+ }
410
+
411
+ constexpr uint32_t rank = 2;
412
+ uint64_t size[rank] = {gmem_width, gmem_height};
413
+ uint64_t stride[rank - 1] = {gmem_width}; // Row major, 1 byte per e8m0
414
+ uint32_t box_size[rank] = {smem_width, smem_height};
415
+ uint32_t elem_stride[rank] = {1, 1};
416
+
417
+ // Validate TMA requirements for 2D transfers
418
+ // Reference: https://docs.nvidia.com/cuda/archive/12.6.3/cuda-driver-api/group__CUDA__TENSOR__MEMORY.html
419
+ // For 2D TMA transfers, the stride must be a multiple of 16 bytes.
420
+ // Since we use row-major layout with stride[0] = gmem_width (in bytes), gmem_width must be divisible by 16.
421
+ if (gmem_width % 16 != 0) {
422
+ fprintf(stderr, "ERROR: TMA requirement for 2D transfers: stride must be a multiple of 16 bytes.\n");
423
+ fprintf(stderr, " Current stride (gmem_width): %lu bytes (remainder: %lu)\n",
424
+ gmem_width, gmem_width % 16);
425
+ fprintf(stderr, " Requested: gmem_width=%lu, gmem_height=%lu, smem_width=%u, smem_height=%u\n",
426
+ gmem_width, gmem_height, smem_width, smem_height);
427
+ fprintf(stderr, " For row-major layout, stride[0] = gmem_width must be divisible by 16.\n");
428
+ fprintf(stderr, " Consider using Triton kernel instead with use_cuda_kernel_for_blocked_layout=False.\n");
429
+ exit(EXIT_FAILURE);
430
+ }
431
+
432
+ void *driver_ptr = get_driver_ptr();
433
+ auto cuTensorMapEncodeTiled = reinterpret_cast<PFN_cuTensorMapEncodeTiled_v12000>(driver_ptr);
434
+
435
+ CUresult res = cuTensorMapEncodeTiled(
436
+ &tensor_map,
437
+ CUtensorMapDataType::CU_TENSOR_MAP_DATA_TYPE_UINT8,
438
+ rank,
439
+ tensor_ptr,
440
+ size,
441
+ stride,
442
+ box_size,
443
+ elem_stride,
444
+ CUtensorMapInterleave::CU_TENSOR_MAP_INTERLEAVE_NONE,
445
+ CUtensorMapSwizzle::CU_TENSOR_MAP_SWIZZLE_NONE,
446
+ CUtensorMapL2promotion::CU_TENSOR_MAP_L2_PROMOTION_NONE,
447
+ CUtensorMapFloatOOBfill::CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE
448
+ );
449
+ CUDA_CHECK(res);
450
+ }
451
+
452
+
453
+ namespace mxfp8 {
454
+
455
+ void launch_mx_block_rearrange_2d_M_groups_cuda(
456
+ const uint8_t* scales_ptr,
457
+ int scale_stride_dim0,
458
+ int scale_rows,
459
+ int scale_cols,
460
+ int padded_rows,
461
+ const int32_t* input_group_end_offsets,
462
+ uint8_t* output_scales_ptr,
463
+ int num_groups,
464
+ int chunk_width,
465
+ int chunks_per_tb, // Chunks per superblock: 4, 8, or 16
466
+ cudaStream_t stream
467
+ ) {
468
+ // Calculate grid dimensions
469
+ int rows_per_superblock = SF_ROWS * chunks_per_tb;
470
+
471
+ // Upper bound on superblocks: each group may add 1 due to ceiling division
472
+ int num_row_superblocks = (scale_rows + rows_per_superblock - 1) / rows_per_superblock + num_groups;
473
+ int num_col_chunks = (scale_cols + chunk_width - 1) / chunk_width;
474
+
475
+ // Output strides for SF tile addressing
476
+ int sf_tiles_per_row = (scale_cols + SF_COLS - 1) / SF_COLS;
477
+ int output_stride_per_sf_tile = SF_ROWS * SF_COLS; // 512 bytes
478
+ int output_stride_per_row_of_sf_tiles = output_stride_per_sf_tile * sf_tiles_per_row;
479
+
480
+ // Create TMA tensor map for input (chunk size = SF_ROWS × effective_chunk_width)
481
+ // When scale_cols < chunk_width, use scale_cols as box width to avoid OOB issues
482
+ const int effective_chunk_width = min(chunk_width, scale_cols);
483
+ alignas(128) CUtensorMap input_tensor_map = {};
484
+ create_tensor_map(
485
+ (void*)scales_ptr,
486
+ input_tensor_map,
487
+ scale_cols,
488
+ scale_rows,
489
+ effective_chunk_width,
490
+ SF_ROWS
491
+ );
492
+
493
+ dim3 grid(num_col_chunks, num_row_superblocks);
494
+
495
+ if (chunk_width == 16) {
496
+ dim3 block(128); // 128 rows × 1 thread/row
497
+ switch (chunks_per_tb) {
498
+ case 1:
499
+ mx_blocked_layout_2d_M_groups_kernel<16, 1><<<grid, block, 0, stream>>>(
500
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
501
+ input_group_end_offsets, output_scales_ptr,
502
+ output_stride_per_row_of_sf_tiles,
503
+ num_groups, input_tensor_map);
504
+ break;
505
+ case 4:
506
+ mx_blocked_layout_2d_M_groups_kernel<16, 4><<<grid, block, 0, stream>>>(
507
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
508
+ input_group_end_offsets, output_scales_ptr,
509
+ output_stride_per_row_of_sf_tiles,
510
+ num_groups, input_tensor_map);
511
+ break;
512
+ case 8:
513
+ mx_blocked_layout_2d_M_groups_kernel<16, 8><<<grid, block, 0, stream>>>(
514
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
515
+ input_group_end_offsets, output_scales_ptr,
516
+ output_stride_per_row_of_sf_tiles,
517
+ num_groups, input_tensor_map);
518
+ break;
519
+ case 16:
520
+ mx_blocked_layout_2d_M_groups_kernel<16, 16><<<grid, block, 0, stream>>>(
521
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
522
+ input_group_end_offsets, output_scales_ptr,
523
+ output_stride_per_row_of_sf_tiles,
524
+ num_groups, input_tensor_map);
525
+ break;
526
+ default:
527
+ printf("CUDA Error: chunks_per_tb must be 1, 4, 8, or 16, got %d\n", chunks_per_tb);
528
+ return;
529
+ }
530
+ } else if (chunk_width == 32) {
531
+ dim3 block(256); // 128 rows × 2 threads/row
532
+ switch (chunks_per_tb) {
533
+ case 1:
534
+ mx_blocked_layout_2d_M_groups_kernel<32, 1><<<grid, block, 0, stream>>>(
535
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
536
+ input_group_end_offsets, output_scales_ptr,
537
+ output_stride_per_row_of_sf_tiles,
538
+ num_groups, input_tensor_map);
539
+ break;
540
+ case 4:
541
+ mx_blocked_layout_2d_M_groups_kernel<32, 4><<<grid, block, 0, stream>>>(
542
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
543
+ input_group_end_offsets, output_scales_ptr,
544
+ output_stride_per_row_of_sf_tiles,
545
+ num_groups, input_tensor_map);
546
+ break;
547
+ case 8:
548
+ mx_blocked_layout_2d_M_groups_kernel<32, 8><<<grid, block, 0, stream>>>(
549
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
550
+ input_group_end_offsets, output_scales_ptr,
551
+ output_stride_per_row_of_sf_tiles,
552
+ num_groups, input_tensor_map);
553
+ break;
554
+ case 16:
555
+ mx_blocked_layout_2d_M_groups_kernel<32, 16><<<grid, block, 0, stream>>>(
556
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
557
+ input_group_end_offsets, output_scales_ptr,
558
+ output_stride_per_row_of_sf_tiles,
559
+ num_groups, input_tensor_map);
560
+ break;
561
+ default:
562
+ printf("CUDA Error: chunks_per_tb must be 1, 4, 8, or 16, got %d\n", chunks_per_tb);
563
+ return;
564
+ }
565
+ } else if (chunk_width == 64) {
566
+ dim3 block(512); // 128 rows × 4 threads/row
567
+ switch (chunks_per_tb) {
568
+ case 1:
569
+ mx_blocked_layout_2d_M_groups_kernel<64, 1><<<grid, block, 0, stream>>>(
570
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
571
+ input_group_end_offsets, output_scales_ptr,
572
+ output_stride_per_row_of_sf_tiles,
573
+ num_groups, input_tensor_map);
574
+ break;
575
+ case 4:
576
+ mx_blocked_layout_2d_M_groups_kernel<64, 4><<<grid, block, 0, stream>>>(
577
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
578
+ input_group_end_offsets, output_scales_ptr,
579
+ output_stride_per_row_of_sf_tiles,
580
+ num_groups, input_tensor_map);
581
+ break;
582
+ case 8:
583
+ mx_blocked_layout_2d_M_groups_kernel<64, 8><<<grid, block, 0, stream>>>(
584
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
585
+ input_group_end_offsets, output_scales_ptr,
586
+ output_stride_per_row_of_sf_tiles,
587
+ num_groups, input_tensor_map);
588
+ break;
589
+ case 16:
590
+ mx_blocked_layout_2d_M_groups_kernel<64, 16><<<grid, block, 0, stream>>>(
591
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
592
+ input_group_end_offsets, output_scales_ptr,
593
+ output_stride_per_row_of_sf_tiles,
594
+ num_groups, input_tensor_map);
595
+ break;
596
+ default:
597
+ printf("CUDA Error: chunks_per_tb must be 1, 4, 8, or 16, got %d\n", chunks_per_tb);
598
+ return;
599
+ }
600
+ } else if (chunk_width == 128) {
601
+ dim3 block(1024); // 128 rows × 8 threads/row
602
+ switch (chunks_per_tb) {
603
+ case 1:
604
+ mx_blocked_layout_2d_M_groups_kernel<128, 1><<<grid, block, 0, stream>>>(
605
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
606
+ input_group_end_offsets, output_scales_ptr,
607
+ output_stride_per_row_of_sf_tiles,
608
+ num_groups, input_tensor_map);
609
+ break;
610
+ case 4:
611
+ mx_blocked_layout_2d_M_groups_kernel<128, 4><<<grid, block, 0, stream>>>(
612
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
613
+ input_group_end_offsets, output_scales_ptr,
614
+ output_stride_per_row_of_sf_tiles,
615
+ num_groups, input_tensor_map);
616
+ break;
617
+ case 8:
618
+ mx_blocked_layout_2d_M_groups_kernel<128, 8><<<grid, block, 0, stream>>>(
619
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
620
+ input_group_end_offsets, output_scales_ptr,
621
+ output_stride_per_row_of_sf_tiles,
622
+ num_groups, input_tensor_map);
623
+ break;
624
+ case 16:
625
+ mx_blocked_layout_2d_M_groups_kernel<128, 16><<<grid, block, 0, stream>>>(
626
+ scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows,
627
+ input_group_end_offsets, output_scales_ptr,
628
+ output_stride_per_row_of_sf_tiles,
629
+ num_groups, input_tensor_map);
630
+ break;
631
+ default:
632
+ printf("CUDA Error: chunks_per_tb must be 1, 4, 8, or 16, got %d\n", chunks_per_tb);
633
+ return;
634
+ }
635
+ } else {
636
+ printf("CUDA Error: chunk_width must be 16, 32, 64, or 128, got %d\n", chunk_width);
637
+ return;
638
+ }
639
+ }
640
+
641
+ // Non-pipelined kernel without TMA for loads, but uses TMA for stores
642
+ // Handles M-groups with one chunk per threadblock (equivalent to CHUNKS_PER_TB=1)
643
+ // Assumes input tensor is contiguous/row-major (stride = scale_cols)
644
+ template <int CHUNK_WIDTH>
645
+ __global__ void mx_blocked_layout_2d_simple_kernel(
646
+ const uint8_t* __restrict__ input_scales,
647
+ const int scale_rows,
648
+ const int scale_cols,
649
+ const int32_t* __restrict__ input_group_end_offsets,
650
+ uint8_t* __restrict__ output_scales,
651
+ const int output_stride_per_row_of_sf_tiles,
652
+ const int num_groups
653
+ ) {
654
+ constexpr int THREADS_PER_ROW = CHUNK_WIDTH / BYTES_PER_THREAD;
655
+ constexpr int SF_TILES_PER_THREAD = BYTES_PER_THREAD / SF_COLS; // 4 tiles per thread
656
+ constexpr int SF_TILES_PER_CHUNK = CHUNK_WIDTH / SF_COLS;
657
+ constexpr int OUTPUT_STRIDE_PER_SF_TILE = SF_ROWS * SF_COLS; // 512 bytes
658
+ constexpr int CHUNK_SIZE_BYTES = SF_ROWS * CHUNK_WIDTH;
659
+
660
+ const int row_chunk_pid = blockIdx.y; // Each chunk is one superblock with CHUNKS_PER_TB=1
661
+ const int col_chunk_pid = blockIdx.x;
662
+ const int tid = threadIdx.x;
663
+ const int row_idx = tid / THREADS_PER_ROW;
664
+ const int col_idx = tid % THREADS_PER_ROW;
665
+ const bool is_master_thread = tid == 0;
666
+
667
+ // Shared memory: group offset computation + data buffer for blocked layout
668
+ __shared__ int smem_group_data[64]; // Max 32 groups: [0..31] = chunks per group, [32..63] = cumsum
669
+ __shared__ __align__(128) uint8_t smem_chunk_buffer[CHUNK_SIZE_BYTES];
670
+
671
+ // Find which group this chunk belongs to (using CHUNKS_PER_TB=1)
672
+ int group_idx;
673
+ int chunk_idx_in_group;
674
+ int chunks_until_end;
675
+ find_group_and_local_offset_for_superblock<1>( // 1 chunk per superblock (i.e., 1 chunk per threadblock) since we aren't pipelining
676
+ row_chunk_pid,
677
+ input_group_end_offsets,
678
+ num_groups,
679
+ smem_group_data,
680
+ group_idx,
681
+ chunk_idx_in_group,
682
+ chunks_until_end
683
+ );
684
+
685
+ // Early exit for padding chunks beyond all groups
686
+ if (chunks_until_end <= 0) {
687
+ return;
688
+ }
689
+
690
+ // Thread 0 computes group boundaries and broadcasts via SMEM
691
+ __shared__ int s_input_group_start_row;
692
+ __shared__ int s_input_group_end_row;
693
+ __shared__ int s_output_group_start_row;
694
+ if (tid == 0) {
695
+ s_input_group_start_row = (group_idx > 0) ? input_group_end_offsets[group_idx - 1] : 0;
696
+ s_input_group_end_row = input_group_end_offsets[group_idx];
697
+ s_output_group_start_row = compute_output_group_start_row(
698
+ group_idx, input_group_end_offsets, num_groups, SF_ROWS);
699
+ }
700
+ __syncthreads();
701
+ const int input_group_start_row = s_input_group_start_row;
702
+ const int input_group_end_row = s_input_group_end_row;
703
+ const int output_group_start_row = s_output_group_start_row;
704
+
705
+ // Compute input row for this thread (within the group)
706
+ const int chunk_start_row = input_group_start_row + (chunk_idx_in_group * SF_ROWS);
707
+ const int global_row = chunk_start_row + row_idx;
708
+ const int global_col_base = col_chunk_pid * CHUNK_WIDTH + col_idx * BYTES_PER_THREAD;
709
+
710
+ // Check if this is a valid row (not a padding row)
711
+ const bool row_valid = global_row < input_group_end_row && global_row < scale_rows;
712
+
713
+ // Load data with vectorized loads, falling back to smaller loads at boundaries
714
+ // For padding rows, row_data stays zero (important for correct padding in output)
715
+ uint4 row_data = make_uint4(0, 0, 0, 0);
716
+ const uint8_t* read_ptr = input_scales + global_row * scale_cols + global_col_base;
717
+
718
+ // TODO: the efficiency of loads can be improved but the kernel is already several times faster
719
+ // than Triton and we are going to port these to CuteDSL anyway so don't want to sink more time into this.
720
+ // Problem: this code will often result in single byte loads when stride is not a multiple of 16/8,
721
+ // because many reads will not meet alignment requirements for vectorized loads.
722
+ // We also can't use 2d TMA to read 128xCHUNK_SIZE chunks because 2d tma also requires global stride by multiple of 16 bytes.
723
+ if (row_valid) {
724
+ // Check alignment and bounds for vectorized loads
725
+ const bool is_aligned_16 = (reinterpret_cast<uintptr_t>(read_ptr) % 16) == 0;
726
+ const bool is_aligned_8 = (reinterpret_cast<uintptr_t>(read_ptr) % 8) == 0;
727
+
728
+ if (global_col_base + 16 <= scale_cols && is_aligned_16) {
729
+ // Can safely load 16 bytes (int4) with proper alignment
730
+ row_data = *reinterpret_cast<const uint4*>(read_ptr);
731
+ } else if (global_col_base + 8 <= scale_cols && is_aligned_8) {
732
+ // Can safely load 8 bytes (int2) with proper alignment
733
+ int2 data = *reinterpret_cast<const int2*>(read_ptr);
734
+ row_data.x = data.x;
735
+ row_data.y = data.y;
736
+ // Load remaining bytes individually if needed
737
+ const int remaining = scale_cols - (global_col_base + 8);
738
+ #pragma unroll
739
+ for (int i = 0; i < remaining && i < 8; i++) {
740
+ reinterpret_cast<uint8_t*>(&row_data)[8 + i] = read_ptr[8 + i];
741
+ }
742
+ } else if (global_col_base < scale_cols) {
743
+ // Load remaining bytes individually (unaligned or small)
744
+ const int remaining = min(16, scale_cols - global_col_base);
745
+ #pragma unroll
746
+ for (int i = 0; i < remaining; i++) {
747
+ reinterpret_cast<uint8_t*>(&row_data)[i] = read_ptr[i];
748
+ }
749
+ }
750
+ }
751
+
752
+ // Compute blocked layout position within SF tile
753
+ // The blocked layout groups rows into blocks of 32
754
+ int r_div_32 = row_idx >> 5; // row_idx / 32
755
+ int r_mod_32 = row_idx & 31; // row_idx % 32
756
+ int blocked_layout_row_offset = (r_mod_32 << 4) + (r_div_32 << 2); // r_mod_32 * 16 + r_div_32 * 4
757
+
758
+ // Compute SF tile indices for this thread
759
+ const int thread_col_start = col_idx * BYTES_PER_THREAD;
760
+ const int first_sf_tile_idx = thread_col_start / SF_COLS;
761
+
762
+ // Compute output tile coordinates (accounting for group padding)
763
+ const int chunk_sf_tile_col_base = col_chunk_pid * SF_TILES_PER_CHUNK;
764
+ const int chunk_sf_tile_row = (output_group_start_row / SF_ROWS) + chunk_idx_in_group;
765
+ const int sf_tiles_per_row = output_stride_per_row_of_sf_tiles / OUTPUT_STRIDE_PER_SF_TILE;
766
+
767
+ // Compute columns in this chunk (based on chunk start, not thread start)
768
+ const int chunk_col_base = col_chunk_pid * CHUNK_WIDTH;
769
+ const int remaining_cols_in_chunk = scale_cols - chunk_col_base;
770
+ const int cols_in_chunk = (remaining_cols_in_chunk < CHUNK_WIDTH) ? remaining_cols_in_chunk : CHUNK_WIDTH;
771
+
772
+ // Scatter 16 bytes to SMEM in blocked layout (4 bytes per SF tile)
773
+ // Each thread writes 4 separate 4-byte chunks to different SF tiles in SMEM
774
+ // NOTE: this will cause bank conflicts but resolving them would prevent us
775
+ // from doing direct TMA stores for 128x4=512b contiguous bytes, which is worse in my prev experiments
776
+ #pragma unroll
777
+ for (int i = 0; i < SF_TILES_PER_THREAD; i++) {
778
+ // Check if this SF tile column is within bounds
779
+ if ((first_sf_tile_idx + i) * SF_COLS < cols_in_chunk) {
780
+ const uint32_t data = reinterpret_cast<const uint32_t*>(&row_data)[i];
781
+ // Offset within the SMEM chunk buffer for this SF tile
782
+ const int sf_tile_offset_in_chunk = (first_sf_tile_idx + i) * OUTPUT_STRIDE_PER_SF_TILE;
783
+ *reinterpret_cast<uint32_t*>(&smem_chunk_buffer[sf_tile_offset_in_chunk + blocked_layout_row_offset]) = data;
784
+ }
785
+ }
786
+
787
+ // Ensure threads finish their smem writes and use explicit fence to ensure visibility to async proxy for TMA
788
+ __syncthreads();
789
+ ptx::fence_proxy_async_shared_cta();
790
+
791
+ if (is_master_thread) {
792
+ // Issue separate 1D TMA stores for each valid SF tile
793
+ // Each store moves one 512-byte SF tile from SMEM to GMEM
794
+ constexpr int SF_TILE_SIZE_BYTES = SF_ROWS * SF_COLS; // 512 bytes
795
+ const int num_valid_sf_tiles = (cols_in_chunk + SF_COLS - 1) / SF_COLS;
796
+
797
+ // Loop over each SF tile and do a separate TMA transfer
798
+ for (int tile = 0; tile < num_valid_sf_tiles; tile++) {
799
+ const int col_sf_tile = chunk_sf_tile_col_base + tile;
800
+ const int linear_sf_tile_idx = chunk_sf_tile_row * sf_tiles_per_row + col_sf_tile;
801
+
802
+ uint64_t* dst_gmem = reinterpret_cast<uint64_t*>(
803
+ output_scales + linear_sf_tile_idx * SF_TILE_SIZE_BYTES);
804
+ const int smem_sf_tile_offset = tile * SF_TILE_SIZE_BYTES;
805
+
806
+ ptx::cp_async_bulk_tensor_1d_shared_to_global(
807
+ dst_gmem,
808
+ reinterpret_cast<const uint64_t*>(&smem_chunk_buffer[smem_sf_tile_offset]),
809
+ SF_TILE_SIZE_BYTES
810
+ );
811
+ }
812
+ ptx::cp_async_bulk_commit_group();
813
+ }
814
+
815
+ // Wait for TMA transfer to complete
816
+ ptx::cp_async_bulk_wait_group();
817
+ }
818
+
819
+
820
+ void launch_mx_block_rearrange_2d_simple_cuda(
821
+ const uint8_t* scales_ptr,
822
+ int scale_rows,
823
+ int scale_cols,
824
+ const int32_t* input_group_end_offsets,
825
+ uint8_t* output_scales_ptr,
826
+ int num_groups,
827
+ int chunk_width,
828
+ cudaStream_t stream
829
+ ) {
830
+ // Calculate grid dimensions (upper bound to account for group padding)
831
+ int num_row_chunks = (scale_rows + SF_ROWS - 1) / SF_ROWS + num_groups;
832
+ int num_col_chunks = (scale_cols + chunk_width - 1) / chunk_width;
833
+
834
+ // Output strides for SF tile addressing
835
+ int sf_tiles_per_row = (scale_cols + SF_COLS - 1) / SF_COLS;
836
+ int output_stride_per_sf_tile = SF_ROWS * SF_COLS; // 512 bytes
837
+ int output_stride_per_row_of_sf_tiles = output_stride_per_sf_tile * sf_tiles_per_row;
838
+
839
+ dim3 grid(num_col_chunks, num_row_chunks);
840
+
841
+ // Launch appropriate kernel based on chunk width
842
+ if (chunk_width == 16) {
843
+ dim3 block(128); // 128 rows × 1 thread/row
844
+ mx_blocked_layout_2d_simple_kernel<16><<<grid, block, 0, stream>>>(
845
+ scales_ptr, scale_rows, scale_cols,
846
+ input_group_end_offsets, output_scales_ptr,
847
+ output_stride_per_row_of_sf_tiles, num_groups);
848
+ } else if (chunk_width == 32) {
849
+ dim3 block(256); // 128 rows × 2 threads/row
850
+ mx_blocked_layout_2d_simple_kernel<32><<<grid, block, 0, stream>>>(
851
+ scales_ptr, scale_rows, scale_cols,
852
+ input_group_end_offsets, output_scales_ptr,
853
+ output_stride_per_row_of_sf_tiles, num_groups);
854
+ } else if (chunk_width == 64) {
855
+ dim3 block(512); // 128 rows × 4 threads/row
856
+ mx_blocked_layout_2d_simple_kernel<64><<<grid, block, 0, stream>>>(
857
+ scales_ptr, scale_rows, scale_cols,
858
+ input_group_end_offsets, output_scales_ptr,
859
+ output_stride_per_row_of_sf_tiles, num_groups);
860
+ } else if (chunk_width == 128) {
861
+ dim3 block(1024); // 128 rows × 8 threads/row
862
+ mx_blocked_layout_2d_simple_kernel<128><<<grid, block, 0, stream>>>(
863
+ scales_ptr, scale_rows, scale_cols,
864
+ input_group_end_offsets, output_scales_ptr,
865
+ output_stride_per_row_of_sf_tiles, num_groups);
866
+ } else {
867
+ fprintf(stderr, "CUDA Error: chunk_width must be 16, 32, 64, or 128, got %d\n", chunk_width);
868
+ return;
869
+ }
870
+
871
+ // Check for launch errors
872
+ cudaError_t err = cudaGetLastError();
873
+ if (err != cudaSuccess) {
874
+ fprintf(stderr, "CUDA kernel launch error: %s\n", cudaGetErrorString(err));
875
+ }
876
+ }
877
+
878
+ } // namespace mxfp8
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mxfp8_cuda.cu ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD 3-Clause license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ // CUDA bridge for MXFP8 quantization
8
+
9
+ #include "mxfp8_quantize.cuh"
10
+
11
+ #include <torch/csrc/stable/tensor.h>
12
+ #include <torch/csrc/inductor/aoti_torch/c/shim.h>
13
+ #include <torch/headeronly/core/ScalarType.h>
14
+ #include <torch/headeronly/util/Exception.h>
15
+ #include <torch/headeronly/util/shim_utils.h>
16
+
17
+ #include <cuda_runtime.h>
18
+ #include <string>
19
+
20
+ using torch::stable::Tensor;
21
+
22
+ namespace mxfp8 {
23
+
24
+ // Convert PyTorch scalar type to our DType enum
25
+ DType get_input_dtype(const Tensor &t) {
26
+ switch (t.scalar_type()) {
27
+ case torch::headeronly::ScalarType::Float:
28
+ return DType::kFloat32;
29
+ case torch::headeronly::ScalarType::Half:
30
+ return DType::kFloat16;
31
+ case torch::headeronly::ScalarType::BFloat16:
32
+ return DType::kBFloat16;
33
+ case torch::headeronly::ScalarType::Byte:
34
+ return DType::kByte;
35
+ default:
36
+ STD_TORCH_CHECK(false, "Unsupported input tensor dtype: ", t.scalar_type());
37
+ }
38
+ }
39
+
40
+ ScaleCalculationMode get_scaling_mode(const std::string &scaling_mode) {
41
+ if (scaling_mode.compare("floor") == 0) {
42
+ return ScaleCalculationMode::FLOOR;
43
+ } else if (scaling_mode.compare("rceil") == 0) {
44
+ return ScaleCalculationMode::RCEIL;
45
+ } else {
46
+ STD_TORCH_CHECK(false, "Unsupported scaling mode: ", scaling_mode, ". Only ['floor', 'rceil'] are supported.");
47
+ }
48
+ }
49
+
50
+ // Convert FP8 format string to DType enum
51
+ DType get_output_dtype(const std::string &fp8_format) {
52
+ if (fp8_format.compare("e4m3") == 0) {
53
+ return DType::kFloat8E4M3;
54
+ } else {
55
+ STD_TORCH_CHECK(false, "Unsupported FP8 format: ", fp8_format,
56
+ ". Only 'e4m3' is supported.");
57
+ }
58
+ }
59
+
60
+ void mxfp8_quantize_cuda(const Tensor &input,
61
+ Tensor &output_rowwise,
62
+ Tensor &output_colwise,
63
+ Tensor &scales_rowwise,
64
+ Tensor &scales_colwise,
65
+ int64_t scale_dim_x,
66
+ int64_t scale_dim_y,
67
+ const std::string &fp8_format,
68
+ const std::string &scaling_mode) {
69
+
70
+ // Get tensor properties
71
+ const int64_t rows = input.size(0);
72
+ const int64_t cols = input.size(1);
73
+
74
+ // Get data pointers
75
+ const void *input_ptr = input.data_ptr();
76
+ void *output_rowwise_ptr =
77
+ output_rowwise.numel() > 0 ? output_rowwise.data_ptr() : nullptr;
78
+ void *output_colwise_ptr =
79
+ output_colwise.numel() > 0 ? output_colwise.data_ptr() : nullptr;
80
+ e8m0_t *scales_rowwise_ptr =
81
+ scales_rowwise.numel() > 0
82
+ ? reinterpret_cast<e8m0_t *>(scales_rowwise.data_ptr())
83
+ : nullptr;
84
+ e8m0_t *scales_colwise_ptr =
85
+ scales_colwise.numel() > 0
86
+ ? reinterpret_cast<e8m0_t *>(scales_colwise.data_ptr())
87
+ : nullptr;
88
+
89
+ // Get CUDA stream using stable ABI
90
+ void* stream_ptr = nullptr;
91
+ TORCH_ERROR_CODE_CHECK(aoti_torch_get_current_cuda_stream(input.get_device_index(), &stream_ptr));
92
+ cudaStream_t stream = static_cast<cudaStream_t>(stream_ptr);
93
+
94
+ // Get strides of scale ptrs (guard against 1D empty tensors when rowwise/colwise is false)
95
+ int64_t scale_rowwise_stride_dim0 = scales_rowwise.dim() >= 2 ? scales_rowwise.stride(0) : 0;
96
+ int64_t scale_rowwise_stride_dim1 = scales_rowwise.dim() >= 2 ? scales_rowwise.stride(1) : 0;
97
+ int64_t scale_colwise_stride_dim0 = scales_colwise.dim() >= 2 ? scales_colwise.stride(0) : 0;
98
+ int64_t scale_colwise_stride_dim1 = scales_colwise.dim() >= 2 ? scales_colwise.stride(1) : 0;
99
+
100
+ #if defined(DEBUG)
101
+ printf("mxfp8_quantize_cuda:\n");
102
+ printf("Quantizing input tensor of size %ld x %ld\n", rows, cols);
103
+ printf("scaling_mode: %s\n", scaling_mode.c_str());
104
+ printf("Scale dim x: %ld\n", scale_dim_x);
105
+ printf("Scale dim y: %ld\n", scale_dim_y);
106
+ printf("Rowwise scale shape: %ld x %ld\n",
107
+ scales_rowwise.dim() >= 1 ? scales_rowwise.size(0) : 0,
108
+ scales_rowwise.dim() >= 2 ? scales_rowwise.size(1) : 0);
109
+ printf("Colwise scale shape: %ld x %ld\n",
110
+ scales_colwise.dim() >= 1 ? scales_colwise.size(0) : 0,
111
+ scales_colwise.dim() >= 2 ? scales_colwise.size(1) : 0);
112
+ printf("scale_rowwise_stride_dim0 = %ld\n", scale_rowwise_stride_dim0);
113
+ printf("scale_rowwise_stride_dim1 = %ld\n", scale_rowwise_stride_dim1);
114
+ printf("scale_colwise_stride_dim0 = %ld\n", scale_colwise_stride_dim0);
115
+ printf("scale_colwise_stride_dim1 = %ld\n", scale_colwise_stride_dim1);
116
+ #endif
117
+
118
+ // Call the quantization kernel
119
+ MXFP8Quantizer::quantize(input_ptr,
120
+ output_rowwise_ptr, output_colwise_ptr,
121
+ scales_rowwise_ptr, scales_colwise_ptr,
122
+ scale_rowwise_stride_dim0, scale_rowwise_stride_dim1,
123
+ scale_colwise_stride_dim0, scale_colwise_stride_dim1,
124
+ rows, cols,
125
+ get_input_dtype(input), get_output_dtype(fp8_format),
126
+ scale_dim_x, scale_dim_y,
127
+ get_scaling_mode(scaling_mode),
128
+ stream);
129
+ }
130
+
131
+ } // namespace mxfp8
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mxfp8_extension.cpp ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // MXFP8 extension using STABLE_TORCH_LIBRARY (ABI stable)
2
+ #include <torch/csrc/stable/tensor.h>
3
+ #include <torch/csrc/stable/library.h>
4
+ #include <torch/csrc/stable/ops.h>
5
+ #include <torch/csrc/stable/accelerator.h>
6
+ #include <torch/csrc/inductor/aoti_torch/c/shim.h>
7
+
8
+ #include <torch/headeronly/core/ScalarType.h>
9
+ #include <torch/headeronly/util/Exception.h>
10
+ #include <torch/headeronly/util/shim_utils.h>
11
+
12
+ #include <cuda_runtime.h>
13
+ #include <cstdint>
14
+ #include <string>
15
+
16
+ using torch::stable::Tensor;
17
+ namespace tsa = torch::stable::accelerator;
18
+
19
+ namespace mxfp8 {
20
+
21
+ // Forward declarations
22
+ void mxfp8_quantize_cuda(const Tensor &input,
23
+ Tensor &output_rowwise,
24
+ Tensor &output_columnwise,
25
+ Tensor &scales_rowwise,
26
+ Tensor &scales_colwise,
27
+ int64_t scale_dim_x,
28
+ int64_t scale_dim_y,
29
+ const std::string &fp8_format,
30
+ const std::string &scaling_mode);
31
+
32
+ void launch_mx_block_rearrange_2d_M_groups_cuda(
33
+ const uint8_t* scales_ptr,
34
+ int scale_stride_dim0,
35
+ int scale_rows,
36
+ int scale_cols,
37
+ int padded_rows,
38
+ const int32_t* input_group_end_offsets,
39
+ uint8_t* output_scales_ptr,
40
+ int num_groups,
41
+ int chunk_width, // Template selector: 64 or 128
42
+ int chunks_per_tb,
43
+ cudaStream_t stream);
44
+
45
+ void launch_mx_block_rearrange_2d_simple_cuda(
46
+ const uint8_t* scales_ptr,
47
+ int scale_rows,
48
+ int scale_cols,
49
+ const int32_t* input_group_end_offsets,
50
+ uint8_t* output_scales_ptr,
51
+ int num_groups,
52
+ int chunk_width,
53
+ cudaStream_t stream);
54
+
55
+ void launch_compute_padded_offsets_cuda(
56
+ const int32_t* group_end_offsets_ptr,
57
+ int32_t* padded_group_start_offsets_ptr,
58
+ int32_t* padded_group_end_offsets_ptr,
59
+ int num_groups,
60
+ int alignment_size,
61
+ cudaStream_t stream);
62
+
63
+ void launch_fused_pad_token_groups_cuda(
64
+ const void* input_ptr,
65
+ const int32_t* group_end_offsets_ptr,
66
+ const int32_t* padded_group_start_offsets_ptr,
67
+ void* output_ptr,
68
+ int num_tokens,
69
+ int dim,
70
+ int num_groups,
71
+ int dtype_size,
72
+ int dtype_enum,
73
+ cudaStream_t stream);
74
+
75
+ void launch_fused_unpad_token_groups_cuda(
76
+ const void* input_ptr,
77
+ const int32_t* group_end_offsets_ptr,
78
+ const int32_t* padded_group_start_offsets_ptr,
79
+ void* output_ptr,
80
+ int num_tokens,
81
+ int dim,
82
+ int num_groups,
83
+ int dtype_size,
84
+ int dtype_enum,
85
+ cudaStream_t stream);
86
+
87
+ // Helper for tensor validation
88
+ void check_cuda_tensor(const Tensor &t, const char *name) {
89
+ STD_TORCH_CHECK(t.is_cuda(), name, " must be a CUDA tensor");
90
+ STD_TORCH_CHECK(t.is_contiguous(), name, " must be contiguous");
91
+ }
92
+
93
+ // Helper to validate FP8 format
94
+ void validate_fp8_format(const std::string &fp8_format) {
95
+ STD_TORCH_CHECK(fp8_format.compare("e4m3") == 0,
96
+ "fp8_format must be 'e4m3', got: ", fp8_format);
97
+ }
98
+
99
+ // Helper to validate scale dimensions
100
+ void validate_scale_dimensions(int64_t scale_dim_x, int64_t scale_dim_y) {
101
+ STD_TORCH_CHECK(scale_dim_x == 1 || scale_dim_x == 32,
102
+ "scale_dim_x must be 1 or 32, got: ", scale_dim_x);
103
+ STD_TORCH_CHECK(scale_dim_y == 1 || scale_dim_y == 32,
104
+ "scale_dim_y must be 1 or 32, got: ", scale_dim_y);
105
+ }
106
+
107
+ // Main quantization function
108
+ std::tuple<Tensor, Tensor, Tensor, Tensor>
109
+ mxfp8_quantize(const Tensor& input, bool rowwise, bool colwise,
110
+ int64_t scale_dim_x, int64_t scale_dim_y,
111
+ const std::string &fp8_format,
112
+ const std::string &scaling_mode) {
113
+
114
+ // Validate inputs
115
+ STD_TORCH_CHECK(!rowwise, "rowwise scaling is not supported yet");
116
+ STD_TORCH_CHECK(input.is_cuda(), "input must be a CUDA tensor");
117
+ STD_TORCH_CHECK(input.is_contiguous(), "input must be contiguous");
118
+ STD_TORCH_CHECK(input.dim() == 2, "input must be 2D");
119
+ STD_TORCH_CHECK(input.scalar_type() == torch::headeronly::ScalarType::Float ||
120
+ input.scalar_type() == torch::headeronly::ScalarType::Half ||
121
+ input.scalar_type() == torch::headeronly::ScalarType::BFloat16,
122
+ "Input must be float32, float16, or bfloat16");
123
+ STD_TORCH_CHECK(rowwise || colwise,
124
+ "At least one of rowwise or colwise must be true");
125
+
126
+ validate_scale_dimensions(scale_dim_x, scale_dim_y);
127
+ validate_fp8_format(fp8_format);
128
+
129
+ const int64_t rows = input.size(0);
130
+ const int64_t cols = input.size(1);
131
+ STD_TORCH_CHECK((rows >= 32) && (rows % 32 == 0), "rows must be a multiple of 32");
132
+ STD_TORCH_CHECK((cols >= 32) && (cols % 32 == 0), "cols must be a multiple of 32");
133
+
134
+ tsa::DeviceGuard device_guard(input.get_device_index());
135
+
136
+ // Allocate output tensors
137
+ Tensor output_rowwise, output_colwise;
138
+ Tensor scales_rowwise, scales_colwise;
139
+
140
+ if (rowwise) {
141
+ const int64_t num_col_blocks = (cols + scale_dim_x - 1) / scale_dim_x;
142
+ output_rowwise = torch::stable::new_empty(input, {rows, cols}, torch::headeronly::ScalarType::Float8_e4m3fn);
143
+ scales_rowwise = torch::stable::new_empty(input, {rows, num_col_blocks}, torch::headeronly::ScalarType::Float8_e8m0fnu);
144
+ } else {
145
+ output_rowwise = torch::stable::new_empty(input, {0}, torch::headeronly::ScalarType::Float8_e4m3fn);
146
+ scales_rowwise = torch::stable::new_empty(input, {0}, torch::headeronly::ScalarType::Float8_e8m0fnu);
147
+ }
148
+
149
+ if (colwise) {
150
+ const int64_t num_row_blocks = (rows + scale_dim_y - 1) / scale_dim_y;
151
+ // Create column-major tensor by creating transposed shape and transposing
152
+ // We need shape {rows, cols} with strides {1, rows}, so create {cols, rows} and transpose
153
+ Tensor output_colwise_tmp = torch::stable::new_empty(input, {cols, rows}, torch::headeronly::ScalarType::Float8_e4m3fn);
154
+ output_colwise = torch::stable::transpose(output_colwise_tmp, 0, 1);
155
+ // For scales_colwise: need shape {cols, num_row_blocks} with strides {1, cols}
156
+ // Create {num_row_blocks, cols} and transpose
157
+ Tensor scales_colwise_tmp = torch::stable::new_empty(input, {num_row_blocks, cols}, torch::headeronly::ScalarType::Float8_e8m0fnu);
158
+ scales_colwise = torch::stable::transpose(scales_colwise_tmp, 0, 1);
159
+ } else {
160
+ output_colwise = torch::stable::new_empty(input, {0}, torch::headeronly::ScalarType::Float8_e4m3fn);
161
+ scales_colwise = torch::stable::new_empty(input, {0}, torch::headeronly::ScalarType::Float8_e8m0fnu);
162
+ }
163
+
164
+ // Call CUDA kernels
165
+ mxfp8_quantize_cuda(input,
166
+ output_rowwise, output_colwise,
167
+ scales_rowwise, scales_colwise,
168
+ rowwise ? scale_dim_x : 1, // scale_dim_x
169
+ colwise ? scale_dim_y : 1, // scale_dim_y
170
+ fp8_format, scaling_mode);
171
+
172
+ return std::make_tuple(output_rowwise, output_colwise, scales_rowwise,
173
+ scales_colwise);
174
+ }
175
+
176
+ Tensor mx_block_rearrange_2d_M_groups(
177
+ Tensor scales_tensor,
178
+ Tensor input_group_end_offsets,
179
+ int64_t chunks_per_tb) {
180
+
181
+ // Validate inputs
182
+ check_cuda_tensor(scales_tensor, "scales_tensor");
183
+ check_cuda_tensor(input_group_end_offsets, "input_group_end_offsets");
184
+
185
+ STD_TORCH_CHECK(scales_tensor.dim() == 2, "scales_tensor must be 2D");
186
+ STD_TORCH_CHECK(scales_tensor.is_contiguous(), "scales_tensor must be contiguous (row-major)");
187
+ STD_TORCH_CHECK(scales_tensor.scalar_type() == torch::headeronly::ScalarType::Byte || // uint8
188
+ scales_tensor.scalar_type() == torch::headeronly::ScalarType::Float8_e8m0fnu,
189
+ "scales_tensor must be uint8 or e8m0");
190
+ STD_TORCH_CHECK(input_group_end_offsets.scalar_type() == torch::headeronly::ScalarType::Int,
191
+ "input_group_end_offsets must be int32");
192
+ STD_TORCH_CHECK(input_group_end_offsets.dim() == 1,
193
+ "input_group_end_offsets must be 1D");
194
+ STD_TORCH_CHECK(chunks_per_tb == 1 || chunks_per_tb == 4 || chunks_per_tb == 8 || chunks_per_tb == 16,
195
+ "chunks_per_tb must be 1, 4, 8, or 16, got: ", chunks_per_tb);
196
+ tsa::DeviceGuard device_guard(scales_tensor.get_device_index());
197
+
198
+ const int rows = scales_tensor.size(0);
199
+ const int cols = scales_tensor.size(1);
200
+ const int num_groups = input_group_end_offsets.size(0);
201
+ STD_TORCH_CHECK(num_groups <= 32, "num_groups must be <= 32");
202
+
203
+ // Automatically select chunk_width based on scale_cols
204
+ int chunk_width;
205
+ if (cols >= 64) {
206
+ chunk_width = 64;
207
+ } else if (cols >= 32) {
208
+ chunk_width = 32;
209
+ } else {
210
+ chunk_width = 16;
211
+ }
212
+
213
+ // Calculate blocks needed - uses 128-row blocks
214
+ // For M groups, groups are along rows, so we pad each group to 128 rows
215
+ const int BLOCK_ROWS = 128;
216
+ const int BLOCK_COLS = 4;
217
+
218
+ // Each group is padded to 128 rows upper bound
219
+ const int padded_rows = rows + num_groups * BLOCK_ROWS;
220
+
221
+ // Columns are padded to multiple of BLOCK_COLS
222
+ const int num_col_blocks = (cols + BLOCK_COLS - 1) / BLOCK_COLS;
223
+ const int padded_cols = num_col_blocks * BLOCK_COLS;
224
+
225
+ // Create output tensor
226
+ auto output = torch::stable::new_zeros(scales_tensor, {padded_rows, padded_cols}, scales_tensor.scalar_type());
227
+
228
+ // Get raw pointers
229
+ const uint8_t* scales_ptr = reinterpret_cast<const uint8_t*>(scales_tensor.data_ptr());
230
+ const int32_t* offsets_ptr = input_group_end_offsets.const_data_ptr<int32_t>();
231
+ uint8_t* output_ptr = reinterpret_cast<uint8_t*>(output.data_ptr());
232
+
233
+ // Get CUDA stream using stable ABI
234
+ void* stream_ptr = nullptr;
235
+ TORCH_ERROR_CODE_CHECK(aoti_torch_get_current_cuda_stream(scales_tensor.get_device_index(), &stream_ptr));
236
+ cudaStream_t stream = static_cast<cudaStream_t>(stream_ptr);
237
+
238
+ // pipelined kernel will be used if input meets 2d TMA constraint (cols >= 16 and cols % 16 bytes == 0)
239
+ // Otherwise, a fallback kernel will be used (slightly slower but supports any column count)
240
+ const bool can_use_pipelined_kernel = cols >= 16 && cols % 16 == 0;
241
+ if (can_use_pipelined_kernel)
242
+ {
243
+ // Launch pipelined TMA kernel
244
+ launch_mx_block_rearrange_2d_M_groups_cuda(
245
+ scales_ptr,
246
+ scales_tensor.stride(0),
247
+ rows,
248
+ cols,
249
+ padded_rows,
250
+ offsets_ptr,
251
+ output_ptr,
252
+ num_groups,
253
+ static_cast<int>(chunk_width),
254
+ static_cast<int>(chunks_per_tb),
255
+ stream);
256
+ }
257
+ else
258
+ {
259
+ // Launch simplified kernel (no TMA, works with any column dimension)
260
+ launch_mx_block_rearrange_2d_simple_cuda(
261
+ scales_ptr,
262
+ rows,
263
+ cols,
264
+ offsets_ptr,
265
+ output_ptr,
266
+ num_groups,
267
+ static_cast<int>(chunk_width),
268
+ stream);
269
+ }
270
+ return output;
271
+ }
272
+
273
+ std::tuple<Tensor, Tensor, Tensor> fused_pad_token_groups(
274
+ Tensor inputs,
275
+ Tensor group_end_offsets,
276
+ int64_t alignment_size) {
277
+
278
+ // Validate inputs
279
+ check_cuda_tensor(inputs, "inputs");
280
+ check_cuda_tensor(group_end_offsets, "group_end_offsets");
281
+
282
+ STD_TORCH_CHECK(inputs.dim() == 2, "inputs must be 2D, got: ", inputs.dim());
283
+ STD_TORCH_CHECK(inputs.is_contiguous(), "inputs must be contiguous");
284
+ STD_TORCH_CHECK(group_end_offsets.dim() == 1, "group_end_offsets must be 1D");
285
+ STD_TORCH_CHECK(group_end_offsets.scalar_type() == torch::headeronly::ScalarType::Int,
286
+ "group_end_offsets must be int32");
287
+ STD_TORCH_CHECK(inputs.scalar_type() == torch::headeronly::ScalarType::Float ||
288
+ inputs.scalar_type() == torch::headeronly::ScalarType::BFloat16,
289
+ "inputs must be float32 or bfloat16");
290
+
291
+ tsa::DeviceGuard device_guard(inputs.get_device_index());
292
+
293
+ const int num_tokens = inputs.size(0);
294
+ const int dim = inputs.size(1);
295
+ const int num_groups = group_end_offsets.size(0);
296
+
297
+ STD_TORCH_CHECK(num_groups <= 32, "num_groups must be <= 32, got: ", num_groups);
298
+ STD_TORCH_CHECK(alignment_size == 32, "alignment_size must be 32 for now");
299
+
300
+ // Allocate tensors for padded group offsets
301
+ Tensor padded_group_start_offsets = torch::stable::new_empty(group_end_offsets, {num_groups}, group_end_offsets.scalar_type());
302
+ Tensor padded_group_end_offsets = torch::stable::new_empty(group_end_offsets, {num_groups}, group_end_offsets.scalar_type());
303
+
304
+ // Get CUDA stream using stable ABI
305
+ void* stream_ptr = nullptr;
306
+ TORCH_ERROR_CODE_CHECK(aoti_torch_get_current_cuda_stream(inputs.get_device_index(), &stream_ptr));
307
+ cudaStream_t stream = static_cast<cudaStream_t>(stream_ptr);
308
+
309
+ // Launch GPU kernel to compute padded offsets (avoids multiple torch op launches)
310
+ launch_compute_padded_offsets_cuda(
311
+ reinterpret_cast<int32_t*>(group_end_offsets.data_ptr()),
312
+ reinterpret_cast<int32_t*>(padded_group_start_offsets.data_ptr()),
313
+ reinterpret_cast<int32_t*>(padded_group_end_offsets.data_ptr()),
314
+ num_groups,
315
+ static_cast<int>(alignment_size),
316
+ stream
317
+ );
318
+
319
+ // Calculate output size with upper bound padding, rounded up to alignment
320
+ // (required for quantization operations that expect aligned dimensions)
321
+ int output_rows = num_tokens + num_groups * alignment_size;
322
+ output_rows = ((output_rows + alignment_size - 1) / alignment_size) * alignment_size;
323
+
324
+ // Allocate zero-initialized output (zeros for padding required by quantization)
325
+ Tensor output = torch::stable::new_zeros(inputs, {output_rows, dim}, inputs.scalar_type());
326
+
327
+ // Determine dtype parameters
328
+ int dtype_size = inputs.element_size();
329
+ int dtype_enum = 0; // 0=fp32, 1=bf16
330
+ if (inputs.scalar_type() == torch::headeronly::ScalarType::BFloat16) {
331
+ dtype_enum = 1;
332
+ }
333
+
334
+ // Launch copy kernel (overwrites zeros with real data)
335
+ launch_fused_pad_token_groups_cuda(
336
+ inputs.data_ptr(),
337
+ reinterpret_cast<const int32_t*>(group_end_offsets.data_ptr()),
338
+ reinterpret_cast<const int32_t*>(padded_group_start_offsets.data_ptr()),
339
+ output.data_ptr(),
340
+ num_tokens,
341
+ dim,
342
+ num_groups,
343
+ dtype_size,
344
+ dtype_enum,
345
+ stream
346
+ );
347
+
348
+ return std::make_tuple(output, padded_group_start_offsets, padded_group_end_offsets);
349
+ }
350
+
351
+ Tensor fused_unpad_token_groups(
352
+ Tensor inputs,
353
+ Tensor group_end_offsets,
354
+ Tensor padded_group_start_offsets,
355
+ int64_t num_tokens,
356
+ int64_t alignment_size) {
357
+
358
+ // Validate inputs
359
+ check_cuda_tensor(inputs, "inputs");
360
+ check_cuda_tensor(group_end_offsets, "group_end_offsets");
361
+ check_cuda_tensor(padded_group_start_offsets, "padded_group_start_offsets");
362
+
363
+ STD_TORCH_CHECK(inputs.dim() == 2, "inputs must be 2D, got: ", inputs.dim());
364
+ STD_TORCH_CHECK(inputs.is_contiguous(), "inputs must be contiguous");
365
+ STD_TORCH_CHECK(group_end_offsets.dim() == 1, "group_end_offsets must be 1D");
366
+ STD_TORCH_CHECK(padded_group_start_offsets.dim() == 1, "padded_group_start_offsets must be 1D");
367
+ STD_TORCH_CHECK(group_end_offsets.scalar_type() == torch::headeronly::ScalarType::Int,
368
+ "group_end_offsets must be int32");
369
+ STD_TORCH_CHECK(padded_group_start_offsets.scalar_type() == torch::headeronly::ScalarType::Int,
370
+ "padded_group_start_offsets must be int32");
371
+ STD_TORCH_CHECK(inputs.scalar_type() == torch::headeronly::ScalarType::Float ||
372
+ inputs.scalar_type() == torch::headeronly::ScalarType::BFloat16,
373
+ "inputs must be float32 or bfloat16");
374
+
375
+ tsa::DeviceGuard device_guard(inputs.get_device_index());
376
+
377
+ const int dim = inputs.size(1);
378
+ const int num_groups = group_end_offsets.size(0);
379
+
380
+ STD_TORCH_CHECK(num_groups <= 32, "num_groups must be <= 32, got: ", num_groups);
381
+ STD_TORCH_CHECK(alignment_size == 32, "alignment_size must be 32 for now");
382
+ STD_TORCH_CHECK(padded_group_start_offsets.size(0) == num_groups,
383
+ "padded_group_start_offsets must have same length as num_groups");
384
+ STD_TORCH_CHECK(num_tokens > 0, "num_tokens must be positive, got: ", num_tokens);
385
+
386
+ // Allocate output tensor for unpadded data
387
+ Tensor output = torch::stable::new_empty(inputs, {num_tokens, dim}, inputs.scalar_type());
388
+
389
+ // Determine dtype parameters
390
+ int dtype_size = inputs.element_size();
391
+ int dtype_enum = 0; // 0=fp32, 1=bf16
392
+ if (inputs.scalar_type() == torch::headeronly::ScalarType::BFloat16) {
393
+ dtype_enum = 1;
394
+ }
395
+
396
+ // Get CUDA stream using stable ABI
397
+ void* stream_ptr = nullptr;
398
+ TORCH_ERROR_CODE_CHECK(aoti_torch_get_current_cuda_stream(inputs.get_device_index(), &stream_ptr));
399
+ cudaStream_t stream = static_cast<cudaStream_t>(stream_ptr);
400
+
401
+ // Launch unpad kernel
402
+ launch_fused_unpad_token_groups_cuda(
403
+ inputs.data_ptr(),
404
+ reinterpret_cast<const int32_t*>(group_end_offsets.data_ptr()),
405
+ reinterpret_cast<const int32_t*>(padded_group_start_offsets.data_ptr()),
406
+ output.data_ptr(),
407
+ num_tokens,
408
+ dim,
409
+ num_groups,
410
+ dtype_size,
411
+ dtype_enum,
412
+ stream
413
+ );
414
+
415
+ return output;
416
+ }
417
+
418
+
419
+ } // namespace mxfp8
420
+
421
+
422
+ // Register CUDA implementations using stable ABI
423
+ STABLE_TORCH_LIBRARY_IMPL(torchao, CUDA, m) {
424
+ m.impl("mxfp8_quantize", TORCH_BOX(&mxfp8::mxfp8_quantize));
425
+ m.impl("mx_block_rearrange_2d_M_groups", TORCH_BOX(&mxfp8::mx_block_rearrange_2d_M_groups));
426
+ m.impl("fused_pad_token_groups", TORCH_BOX(&mxfp8::fused_pad_token_groups));
427
+ m.impl("fused_unpad_token_groups", TORCH_BOX(&mxfp8::fused_unpad_token_groups));
428
+ }
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e4m3e4m3.cu ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD 3-Clause license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+ #include "rowwise_scaled_linear_sparse_cutlass.cuh"
7
+ #include "rowwise_scaled_linear_sparse_cutlass_e4m3e4m3.h"
8
+
9
+ namespace torchao {
10
+
11
+ using torch::stable::Tensor;
12
+
13
+ Tensor
14
+ rowwise_scaled_linear_sparse_cutlass_e4m3e4m3(
15
+ const Tensor& Xq, const Tensor& X_scale, const Tensor& Wq,
16
+ const Tensor& W_meta, const Tensor& W_scale,
17
+ const std::optional<Tensor>& bias_opt,
18
+ const std::optional<torch::headeronly::ScalarType> out_dtype_opt) {
19
+ // Validate input datatypes.
20
+ STD_TORCH_CHECK(
21
+ Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn &&
22
+ Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn,
23
+ __func__, " : The input datatypes combination ", Xq.scalar_type(), " for Xq and ",
24
+ Wq.scalar_type(), " for Wq is not supported");
25
+
26
+ #if defined(BUILD_ROWWISE_SCALED_LINEAR_SPARSE_CUTLASS)
27
+ using DtypeXq = cutlass::float_e4m3_t;
28
+ using DtypeWq = cutlass::float_e4m3_t;
29
+ return rowwise_scaled_linear_sparse_cutlass<DtypeXq, DtypeWq>(
30
+ Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt);
31
+ #else
32
+ STD_TORCH_CHECK(false, OPERATOR_NAME, " : Not implemented");
33
+ return Tensor{};
34
+ #endif
35
+ }
36
+
37
+ } // namespace torchao
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e4m3e5m2.cu ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD 3-Clause license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+ #include "rowwise_scaled_linear_sparse_cutlass.cuh"
7
+ #include "rowwise_scaled_linear_sparse_cutlass_e4m3e5m2.h"
8
+
9
+ namespace torchao {
10
+
11
+ using torch::stable::Tensor;
12
+
13
+ Tensor
14
+ rowwise_scaled_linear_sparse_cutlass_e4m3e5m2(
15
+ const Tensor& Xq, const Tensor& X_scale, const Tensor& Wq,
16
+ const Tensor& W_meta, const Tensor& W_scale,
17
+ const std::optional<Tensor>& bias_opt,
18
+ const std::optional<torch::headeronly::ScalarType> out_dtype_opt) {
19
+ // Validate input datatypes.
20
+ STD_TORCH_CHECK(
21
+ Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn &&
22
+ Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2,
23
+ __func__, " : The input datatypes combination ", Xq.scalar_type(), " for Xq and ",
24
+ Wq.scalar_type(), " for Wq is not supported");
25
+
26
+ #if defined(BUILD_ROWWISE_SCALED_LINEAR_SPARSE_CUTLASS)
27
+ using DtypeXq = cutlass::float_e4m3_t;
28
+ using DtypeWq = cutlass::float_e5m2_t;
29
+ return rowwise_scaled_linear_sparse_cutlass<DtypeXq, DtypeWq>(
30
+ Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt);
31
+ #else
32
+ STD_TORCH_CHECK(false, OPERATOR_NAME, " : Not implemented");
33
+ return Tensor{};
34
+ #endif
35
+ }
36
+
37
+ } // namespace torchao
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e5m2e4m3.cu ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD 3-Clause license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+ #include "rowwise_scaled_linear_sparse_cutlass.cuh"
7
+ #include "rowwise_scaled_linear_sparse_cutlass_e5m2e4m3.h"
8
+
9
+ namespace torchao {
10
+
11
+ using torch::stable::Tensor;
12
+
13
+ Tensor
14
+ rowwise_scaled_linear_sparse_cutlass_e5m2e4m3(
15
+ const Tensor& Xq, const Tensor& X_scale, const Tensor& Wq,
16
+ const Tensor& W_meta, const Tensor& W_scale,
17
+ const std::optional<Tensor>& bias_opt,
18
+ const std::optional<torch::headeronly::ScalarType> out_dtype_opt) {
19
+ // Validate input datatypes.
20
+ STD_TORCH_CHECK(
21
+ Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2 &&
22
+ Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn,
23
+ __func__, " : The input datatypes combination ", Xq.scalar_type(), " for Xq and ",
24
+ Wq.scalar_type(), " for Wq is not supported");
25
+
26
+ #if defined(BUILD_ROWWISE_SCALED_LINEAR_SPARSE_CUTLASS)
27
+ using DtypeXq = cutlass::float_e5m2_t;
28
+ using DtypeWq = cutlass::float_e4m3_t;
29
+ return rowwise_scaled_linear_sparse_cutlass<DtypeXq, DtypeWq>(
30
+ Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt);
31
+ #else
32
+ STD_TORCH_CHECK(false, OPERATOR_NAME, " : Not implemented");
33
+ return Tensor{};
34
+ #endif
35
+ }
36
+
37
+ } // namespace torchao
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e5m2e5m2.cu ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD 3-Clause license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+ #include "rowwise_scaled_linear_sparse_cutlass.cuh"
7
+ #include "rowwise_scaled_linear_sparse_cutlass_e5m2e5m2.h"
8
+
9
+ namespace torchao {
10
+
11
+ using torch::stable::Tensor;
12
+
13
+ Tensor
14
+ rowwise_scaled_linear_sparse_cutlass_e5m2e5m2(
15
+ const Tensor& Xq, const Tensor& X_scale, const Tensor& Wq,
16
+ const Tensor& W_meta, const Tensor& W_scale,
17
+ const std::optional<Tensor>& bias_opt,
18
+ const std::optional<torch::headeronly::ScalarType> out_dtype_opt) {
19
+ // Validate input datatypes.
20
+ STD_TORCH_CHECK(
21
+ Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2 &&
22
+ Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2,
23
+ __func__, " : The input datatypes combination ", Xq.scalar_type(), " for Xq and ",
24
+ Wq.scalar_type(), " for Wq is not supported");
25
+
26
+ #if defined(BUILD_ROWWISE_SCALED_LINEAR_SPARSE_CUTLASS)
27
+ using DtypeXq = cutlass::float_e5m2_t;
28
+ using DtypeWq = cutlass::float_e5m2_t;
29
+ return rowwise_scaled_linear_sparse_cutlass<DtypeXq, DtypeWq>(
30
+ Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt);
31
+ #else
32
+ STD_TORCH_CHECK(false, OPERATOR_NAME, " : Not implemented");
33
+ return Tensor{};
34
+ #endif
35
+ }
36
+
37
+ } // namespace torchao
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_f8f8.cu ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD 3-Clause license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+ #include <torch/csrc/stable/library.h>
7
+ #include <torch/csrc/stable/tensor.h>
8
+ #include <torch/headeronly/core/ScalarType.h>
9
+ #include <torch/headeronly/util/Exception.h>
10
+
11
+ #include "rowwise_scaled_linear_sparse_cutlass_e4m3e4m3.h"
12
+ #include "rowwise_scaled_linear_sparse_cutlass_e4m3e5m2.h"
13
+ #include "rowwise_scaled_linear_sparse_cutlass_e5m2e4m3.h"
14
+ #include "rowwise_scaled_linear_sparse_cutlass_e5m2e5m2.h"
15
+
16
+ namespace torchao {
17
+
18
+ using torch::stable::Tensor;
19
+
20
+ Tensor
21
+ rowwise_scaled_linear_sparse_cutlass_f8f8(
22
+ const Tensor& Xq, const Tensor& X_scale, const Tensor& Wq,
23
+ const Tensor& W_meta, const Tensor& W_scale,
24
+ const std::optional<Tensor>& bias_opt = std::nullopt,
25
+ const std::optional<torch::headeronly::ScalarType> out_dtype_opt = std::nullopt) {
26
+ // Validate input datatypes.
27
+ STD_TORCH_CHECK(
28
+ (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn &&
29
+ Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn) ||
30
+ (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn &&
31
+ Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2) ||
32
+ (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2 &&
33
+ Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn) ||
34
+ (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2 &&
35
+ Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2),
36
+ __func__, " : The input datatypes combination ", Xq.scalar_type(),
37
+ " for Xq and ", Wq.scalar_type(), " for Wq is not supported");
38
+
39
+ // Dispatch to appropriate kernel template.
40
+ if (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn &&
41
+ Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn) {
42
+ return rowwise_scaled_linear_sparse_cutlass_e4m3e4m3(
43
+ Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt);
44
+ } else if (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn &&
45
+ Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2) {
46
+ return rowwise_scaled_linear_sparse_cutlass_e4m3e5m2(
47
+ Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt);
48
+ } else if (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2 &&
49
+ Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn) {
50
+ return rowwise_scaled_linear_sparse_cutlass_e5m2e4m3(
51
+ Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt);
52
+ } else if (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2 &&
53
+ Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2) {
54
+ return rowwise_scaled_linear_sparse_cutlass_e5m2e5m2(
55
+ Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt);
56
+ }
57
+ return Tensor{};
58
+ }
59
+
60
+ #ifdef DEF_SPARSE_CUTLASS_OPS
61
+ STABLE_TORCH_LIBRARY(torchao, m) {
62
+ m.def(
63
+ "torchao::rowwise_scaled_linear_sparse_cutlass_f8f8(Tensor input, Tensor input_scale, Tensor weight, Tensor weight_meta, Tensor weight_scale, Tensor? bias=None, ScalarType? out_dtype=None) -> Tensor");
64
+ }
65
+ #endif
66
+
67
+ STABLE_TORCH_LIBRARY_IMPL(torchao, CUDA, m) {
68
+ m.impl("torchao::rowwise_scaled_linear_sparse_cutlass_f8f8",
69
+ TORCH_BOX(&rowwise_scaled_linear_sparse_cutlass_f8f8));
70
+ }
71
+
72
+ } // namespace torchao
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/to_sparse_semi_structured_cutlass_sm9x/to_sparse_semi_structured_cutlass_sm9x_f8.cu ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD 3-Clause license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #include "to_sparse_semi_structured_cutlass_sm9x.cuh"
8
+
9
+ namespace torchao {
10
+
11
+ std::tuple<Tensor, Tensor>
12
+ to_sparse_semi_structured_cutlass_sm9x_f8(const Tensor& W) {
13
+ // Validate input datatypes.
14
+ STD_TORCH_CHECK(W.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2 ||
15
+ W.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn,
16
+ __func__, " : The input datatype ", static_cast<int>(W.scalar_type()),
17
+ " is not supported");
18
+
19
+ #if defined(BUILD_TO_SPARSE_SEMI_STRUCTURED_CUTLASS_SM9X)
20
+ // Dispatch to appropriate kernel template.
21
+ switch (W.scalar_type()) {
22
+ case torch::headeronly::ScalarType::Float8_e5m2: {
23
+ using DtypeW = cutlass::float_e5m2_t;
24
+ return to_sparse_semi_structured_cutlass_sm9x<DtypeW>(W);
25
+ }
26
+ case torch::headeronly::ScalarType::Float8_e4m3fn: {
27
+ using DtypeW = cutlass::float_e4m3_t;
28
+ return to_sparse_semi_structured_cutlass_sm9x<DtypeW>(W);
29
+ }
30
+ default:
31
+ return std::tuple(Tensor{}, Tensor{});
32
+ }
33
+ #else
34
+ STD_TORCH_CHECK(false, OPERATOR_NAME, " : Not implemented");
35
+ return std::tuple(Tensor{}, Tensor{});
36
+ #endif
37
+ }
38
+
39
+ STABLE_TORCH_LIBRARY_IMPL(torchao, CUDA, m) {
40
+ m.impl("torchao::to_sparse_semi_structured_cutlass_sm9x_f8",
41
+ TORCH_BOX(&to_sparse_semi_structured_cutlass_sm9x_f8));
42
+ }
43
+
44
+ } // namespace torchao
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/experimental/ops/mps/__pycache__/utils.cpython-310.pyc ADDED
Binary file (1.79 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (4.59 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (260 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_analytics.cpython-310.pyc ADDED
Binary file (2.38 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_iterutils.cpython-310.pyc ADDED
Binary file (2.92 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_strutils.cpython-310.pyc ADDED
Binary file (1.81 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/data_types.cpython-310.pyc ADDED
Binary file (2.14 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/env.cpython-310.pyc ADDED
Binary file (13.3 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/jupyter.cpython-310.pyc ADDED
Binary file (12.6 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/sklearn.cpython-310.pyc ADDED
Binary file (742 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/trigger.cpython-310.pyc ADDED
Binary file (1.15 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/util.cpython-310.pyc ADDED
Binary file (60 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_agent.cpython-310.pyc ADDED
Binary file (16.2 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_controller.cpython-310.pyc ADDED
Binary file (20.5 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_run.cpython-310.pyc ADDED
Binary file (331 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Internal utilities for working with pydantic."""
2
+
3
+ __all__ = [
4
+ "CompatBaseModel",
5
+ "JsonableModel",
6
+ "GQLBase",
7
+ "GQLInput",
8
+ "GQLResult",
9
+ "Connection",
10
+ "ConnectionWithTotal",
11
+ "Edge",
12
+ "PageInfo",
13
+ "Typename",
14
+ "GQLId",
15
+ "AliasChoices",
16
+ "computed_field",
17
+ "field_validator",
18
+ "model_validator",
19
+ "pydantic_isinstance",
20
+ "to_camel",
21
+ "to_json",
22
+ "from_json",
23
+ "gql_typename",
24
+ "ValidationError",
25
+ ]
26
+
27
+ from pydantic import (
28
+ AliasChoices,
29
+ ValidationError,
30
+ computed_field,
31
+ field_validator,
32
+ model_validator,
33
+ )
34
+ from pydantic.alias_generators import to_camel
35
+
36
+ from .base import CompatBaseModel, GQLBase, GQLInput, GQLResult, JsonableModel
37
+ from .field_types import GQLId, Typename
38
+ from .pagination import Connection, ConnectionWithTotal, Edge, PageInfo
39
+ from .utils import from_json, gql_typename, pydantic_isinstance, to_json
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/base.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base classes and other customizations for generated pydantic types."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC
6
+ from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, Literal, overload
7
+
8
+ from pydantic import BaseModel, ConfigDict
9
+ from pydantic.alias_generators import to_camel
10
+ from typing_extensions import TypedDict, Unpack, override
11
+
12
+ if TYPE_CHECKING:
13
+ from pydantic.main import IncEx
14
+
15
+
16
+ class ModelDumpKwargs(TypedDict, total=False):
17
+ """Shared keyword arguments for `BaseModel.model_{dump,dump_json}`.
18
+
19
+ Newer pydantic versions may accept more arguments than are listed here.
20
+ Last updated for pydantic v2.12.0.
21
+ """
22
+
23
+ include: IncEx | None
24
+ exclude: IncEx | None
25
+ context: Any | None
26
+ by_alias: bool | None
27
+ exclude_unset: bool
28
+ exclude_defaults: bool
29
+ exclude_none: bool
30
+ exclude_computed_fields: bool
31
+ round_trip: bool
32
+ warnings: bool | Literal["none", "warn", "error"]
33
+ fallback: Callable[[Any], Any] | None
34
+ serialize_as_any: bool
35
+
36
+
37
+ # ---------------------------------------------------------------------------
38
+ # Base models and mixin classes.
39
+ #
40
+ # Extra info is provided for devs in inline comments, NOT docstrings. This
41
+ # prevents it from showing up in generated docs for subclasses.
42
+
43
+
44
+ # FOR INTERNAL USE ONLY: W&B's shared base model for generated pydantic types.
45
+ # Deliberately inherits ALL default configuration from `pydantic.BaseModel`.
46
+ class CompatBaseModel(BaseModel):
47
+ __doc__ = None # Prevent subclasses from inheriting the BaseModel docstring
48
+
49
+
50
+ class JsonableModel(CompatBaseModel, ABC):
51
+ # Base class with sensible defaults for converting to and from JSON.
52
+ #
53
+ # Automatically parse or serialize "raw" API data (e.g. convert to and from
54
+ # camelCase keys):
55
+ # - `.model_{dump,dump_json}()` should return JSON-ready dicts or JSON
56
+ # strings.
57
+ # - `.model_{validate,validate_json}()` should accept JSON-ready dicts or
58
+ # JSON strings.
59
+ #
60
+ # Ensure round-trip serialization <-> deserialization between:
61
+ # - `model_dump()` <-> `model_validate()`
62
+ # - `model_dump_json()` <-> `model_validate_json()`
63
+ #
64
+ # These behaviors help models predictably handle GraphQL request or response
65
+ # data.
66
+
67
+ model_config = ConfigDict(
68
+ # ---------------------------------------------------------------------------
69
+ # Discouraged in v2.11+, deprecated in v3. Kept here for compatibility.
70
+ populate_by_name=True,
71
+ # ---------------------------------------------------------------------------
72
+ # Introduced in v2.11, ignored in earlier versions
73
+ validate_by_name=True,
74
+ validate_by_alias=True,
75
+ serialize_by_alias=True,
76
+ # ---------------------------------------------------------------------------
77
+ validate_assignment=True,
78
+ use_attribute_docstrings=True,
79
+ from_attributes=True,
80
+ )
81
+
82
+ # Custom default kwargs for `JsonableModel.model_{dump,dump_json}`:
83
+ # - by_alias: Convert keys to JSON-ready names and objects to JSON-ready
84
+ # dicts.
85
+ # - round_trip: Ensure the result can round-trip.
86
+ __DUMP_DEFAULTS: ClassVar[Dict[str, Any]] = dict(by_alias=True, round_trip=True)
87
+
88
+ @overload # Actual signature
89
+ def model_dump(
90
+ self, *, mode: str, **kwargs: Unpack[ModelDumpKwargs]
91
+ ) -> dict[str, Any]: ...
92
+ @overload # In case pydantic adds more kwargs in future releases
93
+ def model_dump(self, **kwargs: Any) -> dict[str, Any]: ...
94
+
95
+ @override
96
+ def model_dump(self, *, mode: str = "json", **kwargs: Any) -> dict[str, Any]:
97
+ kwargs = {**self.__DUMP_DEFAULTS, **kwargs} # allows overrides, if needed
98
+ return super().model_dump(mode=mode, **kwargs)
99
+
100
+ @overload # Actual signature
101
+ def model_dump_json(
102
+ self, *, indent: int | None, **kwargs: Unpack[ModelDumpKwargs]
103
+ ) -> str: ...
104
+ @overload # In case pydantic adds more kwargs in future releases
105
+ def model_dump_json(self, **kwargs: Any) -> str: ...
106
+
107
+ @override
108
+ def model_dump_json(self, *, indent: int | None = None, **kwargs: Any) -> str:
109
+ kwargs = {**self.__DUMP_DEFAULTS, **kwargs} # allows overrides, if needed
110
+ return super().model_dump_json(indent=indent, **kwargs)
111
+
112
+
113
+ # Base class for all GraphQL-derived types.
114
+ class GQLBase(JsonableModel, ABC):
115
+ model_config = ConfigDict(
116
+ validate_default=True,
117
+ revalidate_instances="always",
118
+ protected_namespaces=(), # Some GraphQL fields may begin with "model_"
119
+ )
120
+
121
+
122
+ # Base class for GraphQL result types, i.e. parsed GraphQL response data.
123
+ class GQLResult(GQLBase, ABC):
124
+ model_config = ConfigDict(
125
+ alias_generator=to_camel, # Assume JSON names are camelCase, by default
126
+ frozen=True, # Keep the actual response data immutable
127
+ )
128
+
129
+
130
+ # Base class for GraphQL input types, i.e. prepared variables or input objects
131
+ # for queries and mutations.
132
+ class GQLInput(GQLBase, ABC):
133
+ # For GraphQL inputs, exclude null values when preparing JSON-able request
134
+ # data.
135
+ __DUMP_DEFAULTS: ClassVar[Dict[str, Any]] = dict(exclude_none=True)
136
+
137
+ @override
138
+ def model_dump(self, *, mode: str = "json", **kwargs: Any) -> dict[str, Any]:
139
+ kwargs = {**self.__DUMP_DEFAULTS, **kwargs}
140
+ return super().model_dump(mode=mode, **kwargs)
141
+
142
+ @override
143
+ def model_dump_json(self, *, indent: int | None = None, **kwargs: Any) -> str:
144
+ kwargs = {**self.__DUMP_DEFAULTS, **kwargs}
145
+ return super().model_dump_json(indent=indent, **kwargs)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/field_types.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reusable field types and annotations for pydantic fields."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Annotated, TypeVar
6
+
7
+ from pydantic import Field, StrictStr
8
+
9
+ T = TypeVar("T")
10
+
11
+ # HACK: Pydantic no longer seems to like it when you define a type alias
12
+ # at the module level with `Annotated[...]`.
13
+ # The commented TypeAliases are a hack to unblock CI for now.
14
+
15
+ # Typename = Annotated[T, Field(repr=False, frozen=True, alias="__typename")]
16
+ Typename = Annotated[T, Field(alias="__typename")]
17
+ """Annotates GraphQL `__typename` fields."""
18
+
19
+
20
+ # GQLId = Annotated[StrictStr, Field(repr=False, frozen=True)]
21
+ GQLId = StrictStr
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/pagination.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities for client-side handling of "relay-style" GraphQL pagination.
2
+
3
+ For formal specs and definitions, see https://relay.dev/graphql/connections.htm.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Iterator
9
+ from typing import Generic, Literal, Optional, TypeVar
10
+
11
+ from pydantic import NonNegativeInt
12
+
13
+ from .base import GQLResult
14
+
15
+ NodeT = TypeVar("NodeT")
16
+ """A generic type variable for a GraphQL relay node."""
17
+
18
+
19
+ class PageInfo(GQLResult):
20
+ """Pagination metadata returned by the server for a single page of results."""
21
+
22
+ typename__: Literal["PageInfo"] = "PageInfo"
23
+
24
+ end_cursor: Optional[str]
25
+ """Opaque token marking the end of this page and the start of the next page."""
26
+
27
+ has_next_page: bool
28
+ """True if more results exist beyond this page."""
29
+
30
+
31
+ class Edge(GQLResult, Generic[NodeT]):
32
+ """A wrapper around a single result item in a paginated response.
33
+
34
+ In relay-style pagination, individual items are wrapped in "edges" which can
35
+ carry additional metadata, e.g., per-item cursors. This base implementation
36
+ only exposes the `node` (the actual result item, like a GraphQL `Run` or `Project`).
37
+ """
38
+
39
+ node: NodeT
40
+ """The actual result item."""
41
+
42
+
43
+ class Connection(GQLResult, Generic[NodeT]):
44
+ """A page of results from the response of a paginated GraphQL query.
45
+
46
+ This follows the "Relay Connection" specification, which is a standard
47
+ way to paginate large result sets in GraphQL. Instead of returning all
48
+ results at once, the server returns one page at a time. Each "page" is
49
+ represented by a `Connection` object that includes:
50
+
51
+ - A list of `edges`, each wrapping a single result item (`node`).
52
+ - A `page_info` object with metadata for fetching subsequent pages.
53
+ - Optionally, a `total_count` of all results (not just this page).
54
+ """
55
+
56
+ edges: list[Edge[NodeT]]
57
+ """The items in this page, each wrapped in an `Edge`."""
58
+
59
+ page_info: PageInfo
60
+ """Pagination metadata, e.g. `end_cursor`, `has_next_page`."""
61
+
62
+ total_count: Optional[NonNegativeInt] = None
63
+ """Total number of results across all pages, if available."""
64
+
65
+ def nodes(self) -> Iterator[NodeT]:
66
+ """Returns an iterator over the nodes in the connection."""
67
+ return (node for edge in self.edges if (node := edge.node))
68
+
69
+ @property
70
+ def has_next(self) -> bool:
71
+ """Returns True if there are more pages to fetch."""
72
+ return self.page_info.has_next_page
73
+
74
+ @property
75
+ def next_cursor(self) -> Optional[str]:
76
+ """The cursor value to pass as the `after` arg in the next page request."""
77
+ return self.page_info.end_cursor
78
+
79
+
80
+ class ConnectionWithTotal(Connection[NodeT], Generic[NodeT]):
81
+ """A `Connection` where the `totalCount` field must be present.
82
+
83
+ Use this INSTEAD of `Connection` when the paginated query is expected
84
+ to return a finite `totalCount` field, i.e. when `totalCount` is:
85
+ - explicitly requested in the GraphQL query
86
+ - non-nullable in the GraphQL schema
87
+ """
88
+
89
+ total_count: NonNegativeInt
90
+ """Total number of results across all pages (required, not optional)."""
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/utils.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Internal utilities for working with Pydantic types and data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from functools import lru_cache
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ import pydantic_core
9
+
10
+ if TYPE_CHECKING:
11
+ from pydantic import BaseModel
12
+
13
+
14
+ @lru_cache
15
+ def gql_typename(cls: type[BaseModel]) -> str:
16
+ """Get the GraphQL typename for a Pydantic model."""
17
+ if (field := cls.model_fields.get("typename__")) and (typename := field.default):
18
+ return typename
19
+ raise TypeError(f"Cannot extract GraphQL typename from: {cls.__qualname__!r}.")
20
+
21
+
22
+ def from_json(s: str | bytes) -> Any:
23
+ """Quickly deserialize a JSON string to a Python object."""
24
+ return pydantic_core.from_json(s)
25
+
26
+
27
+ def to_json(v: Any) -> str:
28
+ """Quickly serialize a (possibly Pydantic) object to a JSON string."""
29
+ return pydantic_core.to_json(v, by_alias=True, round_trip=True).decode("utf-8")
30
+
31
+
32
+ def pydantic_isinstance(
33
+ v: Any, classinfo: type[BaseModel] | tuple[type[BaseModel], ...]
34
+ ) -> bool:
35
+ """Return True if the object could be parsed into the given Pydantic type."""
36
+ if isinstance(classinfo, tuple):
37
+ return any(cls.__pydantic_validator__.isinstance_python(v) for cls in classinfo)
38
+ cls = classinfo
39
+ return cls.__pydantic_validator__.isinstance_python(v)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/agents/__init__.py ADDED
File without changes
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/agents/pyagent.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Agent - Agent object.
2
+
3
+ Manage wandb agent.
4
+
5
+ """
6
+
7
+ import ctypes
8
+ import logging
9
+ import os
10
+ import queue
11
+ import socket
12
+ import sys
13
+ import threading
14
+ import time
15
+ import traceback
16
+
17
+ import wandb
18
+ from wandb.apis import InternalApi
19
+ from wandb.sdk.launch.sweeps import SweepNotFoundError
20
+ from wandb.sdk.launch.sweeps import utils as sweep_utils
21
+ from wandb.sdk.lib import config_util
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ def _terminate_thread(thread):
27
+ if not thread.is_alive():
28
+ return
29
+ if hasattr(thread, "_terminated"):
30
+ return
31
+ thread._terminated = True
32
+ tid = getattr(thread, "_thread_id", None)
33
+ if tid is None:
34
+ for k, v in threading._active.items():
35
+ if v is thread:
36
+ tid = k
37
+ if tid is None:
38
+ # This should never happen
39
+ return
40
+ logger.debug(f"Terminating thread: {tid}")
41
+ res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
42
+ ctypes.c_long(tid), ctypes.py_object(Exception)
43
+ )
44
+ if res == 0:
45
+ # This should never happen
46
+ return
47
+ elif res != 1:
48
+ # Revert
49
+ logger.debug(f"Termination failed for thread {tid}")
50
+ ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)
51
+
52
+
53
+ class Job:
54
+ def __init__(self, command):
55
+ self.command = command
56
+ job_type = command.get("type")
57
+ self.type = job_type
58
+ self.run_id = command.get("run_id")
59
+ self.config = command.get("args")
60
+
61
+ def __repr__(self):
62
+ if self.type == "run":
63
+ return f"Job({self.run_id},{self.config})"
64
+ elif self.type == "stop":
65
+ return f"stop({self.run_id})"
66
+ else:
67
+ return "exit"
68
+
69
+
70
+ class RunStatus:
71
+ QUEUED = "QUEUED"
72
+ RUNNING = "RUNNING"
73
+ STOPPED = "STOPPED"
74
+ ERRORED = "ERRORED"
75
+ DONE = "DONE"
76
+
77
+
78
+ class Agent:
79
+ FLAPPING_MAX_SECONDS = 60
80
+ FLAPPING_MAX_FAILURES = 3
81
+ MAX_INITIAL_FAILURES = 5
82
+
83
+ def __init__(
84
+ self, sweep_id=None, project=None, entity=None, function=None, count=None
85
+ ):
86
+ self._sweep_path = sweep_id
87
+ self._sweep_id = None
88
+ self._project = project
89
+ self._entity = entity
90
+ self._function = function
91
+ self._count = count
92
+ # glob_config = os.path.expanduser('~/.config/wandb/settings')
93
+ # loc_config = 'wandb/settings'
94
+ # files = (glob_config, loc_config)
95
+ self._api = InternalApi()
96
+ self._agent_id = None
97
+ self._max_initial_failures = wandb.env.get_agent_max_initial_failures(
98
+ self.MAX_INITIAL_FAILURES
99
+ )
100
+ # if the directory to log to is not set, set it
101
+ if os.environ.get(wandb.env.DIR) is None:
102
+ os.environ[wandb.env.DIR] = os.path.abspath(os.getcwd())
103
+
104
+ def _init(self):
105
+ # These are not in constructor so that Agent instance can be rerun
106
+ self._run_threads = {}
107
+ self._run_status = {}
108
+ self._queue = queue.Queue()
109
+ self._exit_flag = False
110
+ self._exceptions = {}
111
+ self._start_time = time.time()
112
+
113
+ def _register(self):
114
+ logger.debug("Agent._register()")
115
+ agent = self._api.register_agent(socket.gethostname(), sweep_id=self._sweep_id)
116
+ self._agent_id = agent["id"]
117
+ logger.debug(f"agent_id = {self._agent_id}")
118
+
119
+ def _setup(self):
120
+ logger.debug("Agent._setup()")
121
+ self._init()
122
+ parts = dict(entity=self._entity, project=self._project, name=self._sweep_path)
123
+ err = sweep_utils.parse_sweep_id(parts)
124
+ if err:
125
+ wandb.termerror(err)
126
+ return
127
+ entity = parts.get("entity") or self._entity
128
+ project = parts.get("project") or self._project
129
+ sweep_id = parts.get("name") or self._sweep_id
130
+ if sweep_id:
131
+ os.environ[wandb.env.SWEEP_ID] = sweep_id
132
+ if entity:
133
+ wandb.env.set_entity(entity)
134
+ if project:
135
+ wandb.env.set_project(project)
136
+ if sweep_id:
137
+ self._sweep_id = sweep_id
138
+ self._register()
139
+
140
+ def _stop_run(self, run_id):
141
+ logger.debug(f"Stopping run {run_id}.")
142
+ self._run_status[run_id] = RunStatus.STOPPED
143
+ thread = self._run_threads.get(run_id)
144
+ if thread:
145
+ _terminate_thread(thread)
146
+
147
+ def _stop_all_runs(self):
148
+ logger.debug("Stopping all runs.")
149
+ for run in list(self._run_threads.keys()):
150
+ self._stop_run(run)
151
+
152
+ def _exit(self):
153
+ self._stop_all_runs()
154
+ self._exit_flag = True
155
+ # _terminate_thread(self._main_thread)
156
+
157
+ def _heartbeat(self):
158
+ while True:
159
+ if self._exit_flag:
160
+ return
161
+ # if not self._main_thread.is_alive():
162
+ # return
163
+ run_status = {
164
+ run: True
165
+ for run, status in self._run_status.items()
166
+ if status in (RunStatus.QUEUED, RunStatus.RUNNING)
167
+ }
168
+ try:
169
+ commands = self._api.agent_heartbeat(self._agent_id, {}, run_status)
170
+ except SweepNotFoundError:
171
+ wandb.termerror(
172
+ "Sweep was deleted or agent was not found. Stopping sweep."
173
+ )
174
+ self._exit()
175
+ return
176
+ if commands:
177
+ job = Job(commands[0])
178
+ logger.debug(f"Job received: {job}")
179
+ if job.type in ["run", "resume"]:
180
+ self._queue.put(job)
181
+ self._run_status[job.run_id] = RunStatus.QUEUED
182
+ elif job.type == "stop":
183
+ self._stop_run(job.run_id)
184
+ elif job.type == "exit":
185
+ self._exit()
186
+ return
187
+ time.sleep(5)
188
+
189
+ def _run_jobs_from_queue(self):
190
+ global _INSTANCES
191
+ _INSTANCES += 1
192
+ try:
193
+ waiting = False
194
+ count = 0
195
+ while True:
196
+ if self._exit_flag:
197
+ return
198
+ try:
199
+ try:
200
+ job = self._queue.get(timeout=5)
201
+ if self._exit_flag:
202
+ logger.debug("Exiting main loop due to exit flag.")
203
+ wandb.termlog("Sweep Agent: Exiting.")
204
+ return
205
+ except queue.Empty:
206
+ if not waiting:
207
+ logger.debug("Paused.")
208
+ wandb.termlog("Sweep Agent: Waiting for job.")
209
+ waiting = True
210
+ time.sleep(5)
211
+ if self._exit_flag:
212
+ logger.debug("Exiting main loop due to exit flag.")
213
+ wandb.termlog("Sweep Agent: Exiting.")
214
+ return
215
+ continue
216
+ if waiting:
217
+ logger.debug("Resumed.")
218
+ wandb.termlog("Job received.")
219
+ waiting = False
220
+ count += 1
221
+ run_id = job.run_id
222
+ if self._run_status[run_id] == RunStatus.STOPPED:
223
+ continue
224
+ logger.debug(f"Spawning new thread for run {run_id}.")
225
+ thread = threading.Thread(target=self._run_job, args=(job,))
226
+ self._run_threads[run_id] = thread
227
+ thread.start()
228
+ self._run_status[run_id] = RunStatus.RUNNING
229
+ thread.join()
230
+ logger.debug(f"Thread joined for run {run_id}.")
231
+ if self._run_status[run_id] == RunStatus.RUNNING:
232
+ self._run_status[run_id] = RunStatus.DONE
233
+ elif self._run_status[run_id] == RunStatus.ERRORED:
234
+ exc = self._exceptions[run_id]
235
+ # Extract to reduce a decision point to avoid ruff c901
236
+ log_str, term_str = _get_exception_logger_and_term_strs(exc)
237
+ logger.error(f"Run {run_id} errored:\n{log_str}")
238
+ wandb.termerror(f"Run {run_id} errored:{term_str}")
239
+ if os.getenv(wandb.env.AGENT_DISABLE_FLAPPING) == "true":
240
+ self._exit_flag = True
241
+ return
242
+ elif (
243
+ time.time() - self._start_time < self.FLAPPING_MAX_SECONDS
244
+ ) and (len(self._exceptions) >= self.FLAPPING_MAX_FAILURES):
245
+ msg = f"Detected {self.FLAPPING_MAX_FAILURES} failed runs in the first {self.FLAPPING_MAX_SECONDS} seconds, killing sweep."
246
+ logger.error(msg)
247
+ wandb.termerror(msg)
248
+ wandb.termlog(
249
+ "To disable this check set WANDB_AGENT_DISABLE_FLAPPING=true"
250
+ )
251
+ self._exit_flag = True
252
+ return
253
+ if (
254
+ self._max_initial_failures < len(self._exceptions)
255
+ and len(self._exceptions) >= count
256
+ ):
257
+ msg = f"Detected {self._max_initial_failures} failed runs in a row at start, killing sweep."
258
+ logger.error(msg)
259
+ wandb.termerror(msg)
260
+ wandb.termlog(
261
+ "To change this value set WANDB_AGENT_MAX_INITIAL_FAILURES=val"
262
+ )
263
+ self._exit_flag = True
264
+ return
265
+ if self._count and self._count == count:
266
+ logger.debug("Exiting main loop because max count reached.")
267
+ self._exit_flag = True
268
+ return
269
+ except KeyboardInterrupt:
270
+ logger.debug("Ctrl + C detected. Stopping sweep.")
271
+ wandb.termlog("Ctrl + C detected. Stopping sweep.")
272
+ self._exit()
273
+ return
274
+ except Exception:
275
+ if self._exit_flag:
276
+ logger.debug("Exiting main loop due to exit flag.")
277
+ wandb.termlog("Sweep Agent: Killed.")
278
+ return
279
+ else:
280
+ raise
281
+ finally:
282
+ _INSTANCES -= 1
283
+
284
+ def _run_job(self, job):
285
+ try:
286
+ run_id = job.run_id
287
+
288
+ config_file = os.path.join(
289
+ "wandb", "sweep-" + self._sweep_id, "config-" + run_id + ".yaml"
290
+ )
291
+ os.environ[wandb.env.RUN_ID] = run_id
292
+ base_dir = os.environ.get(wandb.env.DIR, "")
293
+ sweep_param_path = os.path.join(base_dir, config_file)
294
+ os.environ[wandb.env.SWEEP_PARAM_PATH] = sweep_param_path
295
+ config_util.save_config_file_from_dict(sweep_param_path, job.config)
296
+ os.environ[wandb.env.SWEEP_ID] = self._sweep_id
297
+ wandb.teardown()
298
+
299
+ wandb.termlog(f"Agent Starting Run: {run_id} with config:")
300
+ for k, v in job.config.items():
301
+ wandb.termlog("\t{}: {}".format(k, v["value"]))
302
+
303
+ try:
304
+ self._function()
305
+ except KeyboardInterrupt:
306
+ raise
307
+ except Exception as e:
308
+ # Log the run's exceptions directly to stderr to match CLI case, and wrap so we
309
+ # can identify it as coming from the job later later. This will get automatically
310
+ # logged by console_capture.py. Exception handler below will also handle exceptions
311
+ # in setup code.
312
+ exc_repr = _format_exception_traceback(e)
313
+ print(exc_repr, file=sys.stderr) # noqa: T201
314
+ raise _JobError(f"Run threw exception: {str(e)}") from e
315
+ wandb.finish()
316
+ except KeyboardInterrupt:
317
+ raise
318
+ except Exception as e:
319
+ wandb.finish(exit_code=1)
320
+ if self._run_status[run_id] == RunStatus.RUNNING:
321
+ self._run_status[run_id] = RunStatus.ERRORED
322
+ self._exceptions[run_id] = e
323
+ finally:
324
+ # clean up the environment changes made
325
+ os.environ.pop(wandb.env.RUN_ID, None)
326
+ os.environ.pop(wandb.env.SWEEP_ID, None)
327
+ os.environ.pop(wandb.env.SWEEP_PARAM_PATH, None)
328
+
329
+ def run(self):
330
+ logger.info(
331
+ f"Starting sweep agent: entity={self._entity}, project={self._project}, count={self._count}"
332
+ )
333
+ self._setup()
334
+ # self._main_thread = threading.Thread(target=self._run_jobs_from_queue)
335
+ self._heartbeat_thread = threading.Thread(target=self._heartbeat)
336
+ self._heartbeat_thread.daemon = True
337
+ # self._main_thread.start()
338
+ self._heartbeat_thread.start()
339
+ # self._main_thread.join()
340
+ self._run_jobs_from_queue()
341
+
342
+
343
+ def pyagent(sweep_id, function, entity=None, project=None, count=None):
344
+ """Generic agent entrypoint, used for CLI or jupyter.
345
+
346
+ Args:
347
+ sweep_id (dict): Sweep ID generated by CLI or sweep API
348
+ function (func, optional): A function to call instead of the "program"
349
+ entity (str, optional): W&B Entity
350
+ project (str, optional): W&B Project
351
+ count (int, optional): the number of trials to run.
352
+ """
353
+ if not callable(function):
354
+ raise TypeError("function parameter must be callable!")
355
+ agent = Agent(
356
+ sweep_id,
357
+ function=function,
358
+ entity=entity,
359
+ project=project,
360
+ count=count,
361
+ )
362
+ agent.run()
363
+
364
+
365
+ def _format_exception_traceback(exc):
366
+ return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
367
+
368
+
369
+ class _JobError(Exception):
370
+ """Exception raised when a job fails during execution."""
371
+
372
+ pass
373
+
374
+
375
+ def _get_exception_logger_and_term_strs(exc):
376
+ if isinstance(exc, _JobError) and exc.__cause__:
377
+ # If it's a JobException, get the original exception for display
378
+ job_exc = exc.__cause__
379
+ log_str = _format_exception_traceback(job_exc)
380
+ # Don't long full stacktrace to terminal again because we already
381
+ # printed it to stderr.
382
+ term_str = " " + str(job_exc)
383
+ else:
384
+ log_str = _format_exception_traceback(exc)
385
+ term_str = "\n" + log_str
386
+ return log_str, term_str
387
+
388
+
389
+ _INSTANCES = 0
390
+
391
+
392
+ def is_running():
393
+ return bool(_INSTANCES)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/analytics/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __all__ = ("get_sentry",)
2
+
3
+ from .sentry import get_sentry
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/analytics/sentry.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import atexit
4
+ import contextlib
5
+ import functools
6
+ import os
7
+ import pathlib
8
+ import sys
9
+ import threading
10
+ from collections.abc import Callable
11
+ from types import TracebackType
12
+ from typing import Any, Concatenate, Literal, TypeVar
13
+ from urllib.parse import quote
14
+
15
+ from typing_extensions import Never, ParamSpec
16
+
17
+ _P = ParamSpec("_P")
18
+ _T = TypeVar("_T")
19
+
20
+ SENTRY_DEFAULT_DSN = (
21
+ "https://2592b1968ea94cca9b5ef5e348e094a7@o151352.ingest.sentry.io/4504800232407040"
22
+ )
23
+
24
+ SessionStatus = Literal["ok", "exited", "crashed", "abnormal"]
25
+
26
+
27
+ def _guard(
28
+ method: Callable[Concatenate[Sentry, _P], _T],
29
+ ) -> Callable[Concatenate[Sentry, _P], _T | None]:
30
+ """Make a Sentry method safe, lazy, and non-raising.
31
+
32
+ The wrapped method becomes a no-op if Sentry is disabled,
33
+ this instance belongs to a different PID, or lazy boot fails
34
+ """
35
+
36
+ @functools.wraps(method)
37
+ def wrapper(
38
+ self: Sentry,
39
+ *args: _P.args,
40
+ **kwargs: _P.kwargs,
41
+ ) -> _T | None:
42
+ if not self._enabled:
43
+ return None
44
+
45
+ # If this instance belongs to a different process (fork happened),
46
+ # do nothing; get_sentry() will create a fresh instance for the child.
47
+ if self._pid != os.getpid():
48
+ return None
49
+
50
+ if not self._booted and not self._boot():
51
+ return None
52
+
53
+ try:
54
+ return method(self, *args, **kwargs)
55
+ except Exception as e:
56
+ if method.__name__ != "exception":
57
+ # Best-effort logging of wrapper-level failures.
58
+ with contextlib.suppress(Exception):
59
+ self.exception(f"Error in {method.__name__}: {e}")
60
+ return None
61
+
62
+ return wrapper
63
+
64
+
65
+ class Sentry:
66
+ def __init__(self, *, pid: int) -> None:
67
+ from wandb import env as _env
68
+
69
+ self._pid: int = pid
70
+ self._enabled: bool = bool(_env.error_reporting_enabled())
71
+ self._booted: bool = False
72
+ self._boot_lock = threading.Lock()
73
+ self._atexit_registered: bool = False
74
+
75
+ self._sent_messages: set[str] = set()
76
+ self._sdk: Any | None = None # will hold the sentry_sdk module after boot
77
+ self.scope: Any | None = None
78
+
79
+ self.dsn: str | None = os.environ.get(_env.SENTRY_DSN, SENTRY_DEFAULT_DSN)
80
+
81
+ @property
82
+ def environment(self) -> str:
83
+ is_git = pathlib.Path(__file__).parent.parent.parent.joinpath(".git").exists()
84
+ return "development" if is_git else "production"
85
+
86
+ def _boot(self) -> bool:
87
+ """Import sentry_sdk and set up client/scope."""
88
+ from wandb import __version__
89
+
90
+ with self._boot_lock:
91
+ if not self._enabled:
92
+ return False
93
+
94
+ if self._booted:
95
+ return True
96
+
97
+ try:
98
+ import sentry_sdk # type: ignore
99
+ import sentry_sdk.scope # type: ignore
100
+ import sentry_sdk.utils # type: ignore
101
+
102
+ self._sdk = sentry_sdk
103
+
104
+ client = self._sdk.Client(
105
+ dsn=self.dsn,
106
+ default_integrations=False,
107
+ environment=self.environment,
108
+ release=__version__,
109
+ )
110
+ scope = self._sdk.get_global_scope().fork()
111
+ scope.clear()
112
+ scope.set_client(client)
113
+
114
+ self.scope = scope
115
+ self._booted = True
116
+
117
+ if not self._atexit_registered:
118
+ atexit.register(self.end_session)
119
+ self._atexit_registered = True
120
+
121
+ except Exception:
122
+ # Disable on any failure.
123
+ self._enabled = False
124
+ self._booted = False
125
+ self._sdk = None
126
+ self.scope = None
127
+
128
+ return False
129
+
130
+ return True
131
+
132
+ @_guard
133
+ def message(
134
+ self,
135
+ message: str,
136
+ repeat: bool = True,
137
+ level: str = "info",
138
+ ) -> str | None:
139
+ if not repeat and message in self._sent_messages:
140
+ return None
141
+ self._sent_messages.add(message)
142
+ with self._sdk.scope.use_isolation_scope(self.scope): # type: ignore
143
+ return self._sdk.capture_message(message, level=level) # type: ignore
144
+
145
+ @_guard
146
+ def exception(
147
+ self,
148
+ exc: str
149
+ | BaseException
150
+ | tuple[
151
+ type[BaseException] | None,
152
+ BaseException | None,
153
+ TracebackType | None,
154
+ ]
155
+ | None,
156
+ handled: bool = False,
157
+ status: SessionStatus | None = None,
158
+ ) -> str | None:
159
+ if isinstance(exc, str):
160
+ exc_info = self._sdk.utils.exc_info_from_error(Exception(exc)) # type: ignore
161
+ elif isinstance(exc, BaseException):
162
+ exc_info = self._sdk.utils.exc_info_from_error(exc) # type: ignore
163
+ else:
164
+ exc_info = sys.exc_info()
165
+
166
+ event, _ = self._sdk.utils.event_from_exception( # type: ignore
167
+ exc_info,
168
+ client_options=self.scope.get_client().options, # type: ignore
169
+ mechanism={"type": "generic", "handled": handled},
170
+ )
171
+ event_id = None
172
+ with contextlib.suppress(Exception):
173
+ with self._sdk.scope.use_isolation_scope(self.scope): # type: ignore
174
+ event_id = self._sdk.capture_event(event) # type: ignore
175
+
176
+ status = status or ("crashed" if not handled else "errored") # type: ignore
177
+ self.mark_session(status=status)
178
+
179
+ client = self.scope.get_client() # type: ignore
180
+ if client is not None:
181
+ client.flush()
182
+ return event_id
183
+
184
+ def reraise(self, exc: Any) -> Never:
185
+ """Re-raise after logging, preserving traceback. Safe if disabled."""
186
+ try:
187
+ self.exception(exc) # @_guard applies here
188
+ finally:
189
+ _, _, tb = sys.exc_info()
190
+ if tb is not None and hasattr(exc, "with_traceback"):
191
+ raise exc.with_traceback(tb)
192
+ raise exc
193
+
194
+ @_guard
195
+ def start_session(self) -> None:
196
+ if self.scope is None:
197
+ return
198
+ if self.scope._session is None:
199
+ self.scope.start_session()
200
+
201
+ @_guard
202
+ def end_session(self) -> None:
203
+ if self.scope is None:
204
+ return
205
+ client = self.scope.get_client()
206
+ session = self.scope._session
207
+ if session is not None and client is not None:
208
+ self.scope.end_session()
209
+ client.flush()
210
+
211
+ @_guard
212
+ def mark_session(self, status: SessionStatus | None = None) -> None:
213
+ if self.scope is None:
214
+ return
215
+ session = self.scope._session
216
+ if session is not None:
217
+ session.update(status=status)
218
+
219
+ @_guard
220
+ def configure_scope(
221
+ self,
222
+ tags: dict[str, Any] | None = None,
223
+ process_context: str | None = None,
224
+ ) -> None:
225
+ import wandb.util
226
+
227
+ if self.scope is None:
228
+ return
229
+
230
+ settings_tags = (
231
+ "entity",
232
+ "project",
233
+ "run_id",
234
+ "run_url",
235
+ "sweep_url",
236
+ "sweep_id",
237
+ "deployment",
238
+ "launch",
239
+ "_platform",
240
+ )
241
+
242
+ if process_context:
243
+ self.scope.set_tag("process_context", process_context)
244
+
245
+ if tags is None:
246
+ return None
247
+
248
+ for tag in settings_tags:
249
+ val = tags.get(tag, None)
250
+ if val not in (None, ""):
251
+ self.scope.set_tag(tag, val)
252
+
253
+ if tags.get("_colab", None):
254
+ python_runtime = "colab"
255
+ elif tags.get("_jupyter", None):
256
+ python_runtime = "jupyter"
257
+ elif tags.get("_ipython", None):
258
+ python_runtime = "ipython"
259
+ else:
260
+ python_runtime = "python"
261
+ self.scope.set_tag("python_runtime", python_runtime)
262
+
263
+ # Construct run_url and sweep_url given run_id and sweep_id.
264
+ for obj in ("run", "sweep"):
265
+ obj_id, obj_url = f"{obj}_id", f"{obj}_url"
266
+ if tags.get(obj_url, None):
267
+ continue
268
+ try:
269
+ app_url = wandb.util.app_url(tags["base_url"]) # type: ignore[index]
270
+ entity, project = (quote(tags[k]) for k in ("entity", "project")) # type: ignore[index]
271
+ self.scope.set_tag(
272
+ obj_url,
273
+ f"{app_url}/{entity}/{project}/{obj}s/{tags[obj_id]}",
274
+ )
275
+ except Exception:
276
+ pass
277
+
278
+ email = tags.get("email")
279
+ if email:
280
+ self.scope.user = {"email": email}
281
+
282
+ self.start_session()
283
+
284
+
285
+ _singleton: Sentry | None = None
286
+ _singleton_lock = threading.Lock()
287
+
288
+
289
+ def get_sentry() -> Sentry:
290
+ """Return the Sentry singleton for the current process (fork-aware).
291
+
292
+ Creates a new instance in child processes after fork.
293
+ Thread-safe within each process.
294
+ """
295
+ global _singleton
296
+
297
+ pid = os.getpid()
298
+
299
+ with _singleton_lock:
300
+ if _singleton is not None and _singleton._pid == pid:
301
+ return _singleton
302
+
303
+ if _singleton is None or _singleton._pid != pid:
304
+ _singleton = Sentry(pid=pid)
305
+
306
+ return _singleton
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__init__.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """api."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+
7
+ import wandb
8
+ from wandb import env, util
9
+
10
+
11
+ def _disable_ssl() -> Callable[[], None]:
12
+ import requests
13
+ from urllib3.exceptions import InsecureRequestWarning
14
+
15
+ # Because third party libraries may also use requests, we monkey patch it globally
16
+ # and turn off urllib3 warnings instead printing a global warning to the user.
17
+ wandb.termwarn(
18
+ "Disabling SSL verification. Connections to this server are not verified and may be insecure!"
19
+ )
20
+
21
+ requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
22
+ old_merge_environment_settings = requests.Session.merge_environment_settings
23
+
24
+ def merge_environment_settings(self, url, proxies, stream, verify, cert):
25
+ settings = old_merge_environment_settings(
26
+ self, url, proxies, stream, verify, cert
27
+ )
28
+ settings["verify"] = False
29
+ return settings
30
+
31
+ requests.Session.merge_environment_settings = merge_environment_settings
32
+
33
+ def reset():
34
+ requests.Session.merge_environment_settings = old_merge_environment_settings
35
+
36
+ return reset
37
+
38
+
39
+ if env.ssl_disabled():
40
+ _disable_ssl()
41
+
42
+
43
+ reset_path = util.vendor_setup()
44
+
45
+ from .internal import Api as InternalApi # noqa
46
+ from .public import Api as PublicApi # noqa
47
+
48
+ reset_path()
49
+
50
+ __all__ = ["InternalApi", "PublicApi"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.45 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/attrs.cpython-310.pyc ADDED
Binary file (2.07 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/internal.cpython-310.pyc ADDED
Binary file (9.32 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/normalize.cpython-310.pyc ADDED
Binary file (2 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/paginator.cpython-310.pyc ADDED
Binary file (7.38 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__init__.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generated by ariadne-codegen
2
+
3
+ __all__ = [
4
+ "CREATE_INVITE_GQL",
5
+ "CREATE_PROJECT_GQL",
6
+ "CREATE_SERVICE_ACCOUNT_GQL",
7
+ "CREATE_TEAM_GQL",
8
+ "CREATE_USER_FROM_ADMIN_GQL",
9
+ "DELETE_API_KEY_GQL",
10
+ "DELETE_INVITE_GQL",
11
+ "GENERATE_API_KEY_GQL",
12
+ "GET_AGENT_RUNS_GQL",
13
+ "GET_DEFAULT_ENTITY_GQL",
14
+ "GET_PROJECTS_GQL",
15
+ "GET_PROJECT_GQL",
16
+ "GET_SWEEPS_GQL",
17
+ "GET_SWEEP_AGENTS_GQL",
18
+ "GET_SWEEP_AGENT_GQL",
19
+ "GET_SWEEP_GQL",
20
+ "GET_SWEEP_LEGACY_GQL",
21
+ "GET_TEAM_ENTITY_GQL",
22
+ "GET_VIEWER_GQL",
23
+ "SEARCH_USERS_GQL",
24
+ "GetProjects",
25
+ "GetProject",
26
+ "CreateProject",
27
+ "GetSweeps",
28
+ "GetSweep",
29
+ "GetSweepLegacy",
30
+ "GetSweepAgent",
31
+ "GetSweepAgents",
32
+ "GetAgentRuns",
33
+ "GetTeamEntity",
34
+ "CreateTeam",
35
+ "CreateInvite",
36
+ "DeleteInvite",
37
+ "CreateServiceAccount",
38
+ "SearchUsers",
39
+ "GetViewer",
40
+ "GetDefaultEntity",
41
+ "CreateUserFromAdmin",
42
+ "DeleteApiKey",
43
+ "GenerateApiKey",
44
+ "ArtifactTypeInput",
45
+ "ProjectIconInput",
46
+ "RateLimitsInput",
47
+ "UpsertModelInput",
48
+ "AgentFragment",
49
+ "ApiKeyFragment",
50
+ "CreatedProjectFragment",
51
+ "LegacySweepFragment",
52
+ "LightweightRunFragment",
53
+ "PageInfoFragment",
54
+ "ProjectFragment",
55
+ "SweepFragment",
56
+ "UserFragment",
57
+ "UserInfoFragment",
58
+ ]
59
+ from .create_invite import CreateInvite
60
+ from .create_project import CreateProject
61
+ from .create_service_account import CreateServiceAccount
62
+ from .create_team import CreateTeam
63
+ from .create_user_from_admin import CreateUserFromAdmin
64
+ from .delete_api_key import DeleteApiKey
65
+ from .delete_invite import DeleteInvite
66
+ from .fragments import (
67
+ AgentFragment,
68
+ ApiKeyFragment,
69
+ CreatedProjectFragment,
70
+ LegacySweepFragment,
71
+ LightweightRunFragment,
72
+ PageInfoFragment,
73
+ ProjectFragment,
74
+ SweepFragment,
75
+ UserFragment,
76
+ UserInfoFragment,
77
+ )
78
+ from .generate_api_key import GenerateApiKey
79
+ from .get_agent_runs import GetAgentRuns
80
+ from .get_default_entity import GetDefaultEntity
81
+ from .get_project import GetProject
82
+ from .get_projects import GetProjects
83
+ from .get_sweep import GetSweep
84
+ from .get_sweep_agent import GetSweepAgent
85
+ from .get_sweep_agents import GetSweepAgents
86
+ from .get_sweep_legacy import GetSweepLegacy
87
+ from .get_sweeps import GetSweeps
88
+ from .get_team_entity import GetTeamEntity
89
+ from .get_viewer import GetViewer
90
+ from .input_types import (
91
+ ArtifactTypeInput,
92
+ ProjectIconInput,
93
+ RateLimitsInput,
94
+ UpsertModelInput,
95
+ )
96
+ from .operations import (
97
+ CREATE_INVITE_GQL,
98
+ CREATE_PROJECT_GQL,
99
+ CREATE_SERVICE_ACCOUNT_GQL,
100
+ CREATE_TEAM_GQL,
101
+ CREATE_USER_FROM_ADMIN_GQL,
102
+ DELETE_API_KEY_GQL,
103
+ DELETE_INVITE_GQL,
104
+ GENERATE_API_KEY_GQL,
105
+ GET_AGENT_RUNS_GQL,
106
+ GET_DEFAULT_ENTITY_GQL,
107
+ GET_PROJECT_GQL,
108
+ GET_PROJECTS_GQL,
109
+ GET_SWEEP_AGENT_GQL,
110
+ GET_SWEEP_AGENTS_GQL,
111
+ GET_SWEEP_GQL,
112
+ GET_SWEEP_LEGACY_GQL,
113
+ GET_SWEEPS_GQL,
114
+ GET_TEAM_ENTITY_GQL,
115
+ GET_VIEWER_GQL,
116
+ SEARCH_USERS_GQL,
117
+ )
118
+ from .search_users import SearchUsers
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.56 kB). View file