pathwaysutils 0.0.7__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pathwaysutils-0.0.7/LICENSE +201 -0
- pathwaysutils-0.0.7/PKG-INFO +30 -0
- pathwaysutils-0.0.7/README.md +7 -0
- pathwaysutils-0.0.7/pathwaysutils/__init__.py +71 -0
- pathwaysutils-0.0.7/pathwaysutils/cloud_logging.py +21 -0
- pathwaysutils-0.0.7/pathwaysutils/persistence/__init__.py +13 -0
- pathwaysutils-0.0.7/pathwaysutils/persistence/helper.py +192 -0
- pathwaysutils-0.0.7/pathwaysutils/persistence/pathways_orbax_handler.py +192 -0
- pathwaysutils-0.0.7/pathwaysutils/plugin_executable.py +65 -0
- pathwaysutils-0.0.7/pathwaysutils/profiling.py +182 -0
- pathwaysutils-0.0.7/pathwaysutils/proxy_backend.py +29 -0
- pathwaysutils-0.0.7/pyproject.toml +56 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: pathwaysutils
|
|
3
|
+
Version: 0.0.7
|
|
4
|
+
Summary: Package of Pathways-on-Cloud utilities.
|
|
5
|
+
Keywords:
|
|
6
|
+
Author-email: Pathways-on-Cloud Utilities Developers <pathwaysutils-dev@google.com>
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
10
|
+
Requires-Dist: absl-py
|
|
11
|
+
Requires-Dist: fastapi
|
|
12
|
+
Requires-Dist: google-cloud-logging
|
|
13
|
+
Requires-Dist: jax>=0.4.26
|
|
14
|
+
Requires-Dist: orbax-checkpoint
|
|
15
|
+
Requires-Dist: uvicorn
|
|
16
|
+
Requires-Dist: pylint>=2.6.0 ; extra == "dev"
|
|
17
|
+
Requires-Dist: pyink ; extra == "dev"
|
|
18
|
+
Project-URL: changelog, https://github.com/AI-Hypercomputer/pathways-utils/blob/main/CHANGELOG.md
|
|
19
|
+
Project-URL: homepage, https://github.com/AI-Hypercomputer/pathways-utils
|
|
20
|
+
Project-URL: repository, https://github.com/AI-Hypercomputer/pathways-utils
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
|
|
23
|
+
# Package of Pathways-on-Cloud utilities
|
|
24
|
+
|
|
25
|
+
For customers to utilize Pathways-on-Cloud, there are several changes needed by
|
|
26
|
+
the user job. We encapsulate these changes in a single Python package for two
|
|
27
|
+
primary reasons. First, some of the changes are temporary patches that will not
|
|
28
|
+
be needed long-term. Second, several of the changes follow anti-patterns and
|
|
29
|
+
are now confined to a single repository.
|
|
30
|
+
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Package of Pathways-on-Cloud utilities
|
|
2
|
+
|
|
3
|
+
For customers to utilize Pathways-on-Cloud, there are several changes needed by
|
|
4
|
+
the user job. We encapsulate these changes in a single Python package for two
|
|
5
|
+
primary reasons. First, some of the changes are temporary patches that will not
|
|
6
|
+
be needed long-term. Second, several of the changes follow anti-patterns and
|
|
7
|
+
are now confined to a single repository.
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# Copyright 2024 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
"""Package of Pathways-on-Cloud utilities."""
|
|
15
|
+
|
|
16
|
+
import datetime
|
|
17
|
+
import os
|
|
18
|
+
|
|
19
|
+
from absl import logging
|
|
20
|
+
import jax
|
|
21
|
+
from pathwaysutils import cloud_logging
|
|
22
|
+
from pathwaysutils import profiling
|
|
23
|
+
from pathwaysutils import proxy_backend
|
|
24
|
+
from pathwaysutils.persistence import pathways_orbax_handler
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# A new PyPI release will be pushed every time `__version__` is increased.
|
|
28
|
+
# When changing this, also update the CHANGELOG.md.
|
|
29
|
+
__version__ = "v0.0.7"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# This is a brittle implementation since the platforms value is not necessarily
|
|
33
|
+
# which backend is ultimately selected
|
|
34
|
+
def _is_pathways_used():
|
|
35
|
+
return jax.config.jax_platforms and "proxy" in jax.config.jax_platforms
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _is_persistence_enabled():
|
|
39
|
+
if "ENABLE_PATHWAYS_PERSISTENCE" in os.environ:
|
|
40
|
+
if os.environ["ENABLE_PATHWAYS_PERSISTENCE"] == "1":
|
|
41
|
+
return True
|
|
42
|
+
if os.environ["ENABLE_PATHWAYS_PERSISTENCE"] == "0":
|
|
43
|
+
return False
|
|
44
|
+
else:
|
|
45
|
+
raise ValueError(
|
|
46
|
+
"ENABLE_PATHWAYS_PERSISTENCE must be set to 1/0 or unset, got: "
|
|
47
|
+
+ os.environ["ENABLE_PATHWAYS_PERSISTENCE"]
|
|
48
|
+
)
|
|
49
|
+
return False
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
if _is_pathways_used():
|
|
53
|
+
logging.debug(
|
|
54
|
+
"pathwaysutils: Detected Pathways-on-Cloud backend. Applying changes."
|
|
55
|
+
)
|
|
56
|
+
proxy_backend.register_backend_factory()
|
|
57
|
+
profiling.monkey_patch_jax()
|
|
58
|
+
# TODO(b/365549911): Remove when OCDBT-compatible
|
|
59
|
+
if _is_persistence_enabled():
|
|
60
|
+
pathways_orbax_handler.register_pathways_handlers(
|
|
61
|
+
datetime.timedelta(minutes=10)
|
|
62
|
+
)
|
|
63
|
+
try:
|
|
64
|
+
cloud_logging.setup()
|
|
65
|
+
except OSError as e:
|
|
66
|
+
logging.debug("pathwaysutils: Failed to set up cloud logging.")
|
|
67
|
+
else:
|
|
68
|
+
logging.debug(
|
|
69
|
+
"pathwaysutils: Did not detect Pathways-on-Cloud backend. No changes"
|
|
70
|
+
" applied."
|
|
71
|
+
)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Copyright 2024 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
"""Package for setting up Cloud Logging for Python."""
|
|
15
|
+
|
|
16
|
+
import google.cloud.logging
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def setup():
|
|
20
|
+
client = google.cloud.logging.Client()
|
|
21
|
+
client.setup_logging()
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Copyright 2024 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# Copyright 2024 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
"""Helper functions for persistence."""
|
|
15
|
+
|
|
16
|
+
import base64
|
|
17
|
+
import datetime
|
|
18
|
+
import json
|
|
19
|
+
from typing import Sequence, Union
|
|
20
|
+
|
|
21
|
+
import jax
|
|
22
|
+
from jax import core
|
|
23
|
+
from jax.lib import xla_client as xc
|
|
24
|
+
import numpy as np
|
|
25
|
+
from pathwaysutils import plugin_executable
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def base64_utf8_stringify(bs: bytes) -> str:
|
|
29
|
+
"""Converts bytes to a base64-encoded utf-8 string.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
bs: The bytes to convert.
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
The base64-encoded utf-8 string.
|
|
36
|
+
"""
|
|
37
|
+
return base64.b64encode(bs).decode("utf-8")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def string_to_base64(text: str) -> str:
|
|
41
|
+
"""Encodes a string to base64 format.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
text: The string to encode.
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
The base64-encoded string.
|
|
48
|
+
"""
|
|
49
|
+
return base64_utf8_stringify(text.encode("utf-8"))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def get_hlo_sharding_string(
|
|
53
|
+
sharding: jax.sharding.Sharding,
|
|
54
|
+
num_dimensions: int,
|
|
55
|
+
) -> str:
|
|
56
|
+
"""Serializes the sharding to an hlo-sharding, encodes it to base64 and returns the base-64 as an utf-8 string."""
|
|
57
|
+
return base64_utf8_stringify(
|
|
58
|
+
# pylint:disable=protected-access
|
|
59
|
+
sharding._to_xla_hlo_sharding(num_dimensions) # pytype: disable=attribute-error
|
|
60
|
+
# pylint:enable=protected-access
|
|
61
|
+
.to_proto().SerializeToString()
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def get_shape_string(
|
|
66
|
+
dtype: np.dtype,
|
|
67
|
+
shape: Sequence[int],
|
|
68
|
+
) -> str:
|
|
69
|
+
"""Serializes the shape, encodes it to base64 and returns the base-64 as an utf-8 string."""
|
|
70
|
+
return base64_utf8_stringify(
|
|
71
|
+
xc.Shape.array_shape(
|
|
72
|
+
xc.PrimitiveType(xc.dtype_to_etype(dtype)),
|
|
73
|
+
shape,
|
|
74
|
+
)
|
|
75
|
+
.with_major_to_minor_layout_if_absent()
|
|
76
|
+
.to_serialized_proto()
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def get_write_request(
|
|
81
|
+
location_path: str,
|
|
82
|
+
name: str,
|
|
83
|
+
jax_array: jax.Array,
|
|
84
|
+
timeout: datetime.timedelta,
|
|
85
|
+
) -> str:
|
|
86
|
+
"""Returns a string representation of the plugin program which writes the given jax_array to the given location."""
|
|
87
|
+
sharding = jax_array.sharding
|
|
88
|
+
assert isinstance(sharding, jax.sharding.Sharding), sharding
|
|
89
|
+
|
|
90
|
+
timeout_seconds, timeout_fractional_seconds = divmod(
|
|
91
|
+
timeout.total_seconds(), 1
|
|
92
|
+
)
|
|
93
|
+
timeout_nanoseconds = timeout_fractional_seconds * 1e9
|
|
94
|
+
return json.dumps({
|
|
95
|
+
"persistenceWriteRequest": {
|
|
96
|
+
"b64_location": string_to_base64(location_path),
|
|
97
|
+
"b64_name": string_to_base64(name),
|
|
98
|
+
"b64_hlo_sharding_string": get_hlo_sharding_string(
|
|
99
|
+
jax_array.sharding, len(jax_array.shape)
|
|
100
|
+
),
|
|
101
|
+
"shape": jax_array.shape,
|
|
102
|
+
"devices": {
|
|
103
|
+
"device_ids": [
|
|
104
|
+
# pylint:disable=protected-access
|
|
105
|
+
device.id
|
|
106
|
+
for device in sharding._device_assignment
|
|
107
|
+
# pylint:enable=protected-access
|
|
108
|
+
],
|
|
109
|
+
},
|
|
110
|
+
"timeout": {
|
|
111
|
+
"seconds": int(timeout_seconds),
|
|
112
|
+
"nanos": int(timeout_nanoseconds),
|
|
113
|
+
},
|
|
114
|
+
}
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def get_read_request(
|
|
119
|
+
location_path: str,
|
|
120
|
+
name: str,
|
|
121
|
+
dtype: np.dtype,
|
|
122
|
+
shape: Sequence[int],
|
|
123
|
+
sharding: jax.sharding.Sharding,
|
|
124
|
+
devices: Sequence[jax.Device],
|
|
125
|
+
timeout: datetime.timedelta,
|
|
126
|
+
) -> str:
|
|
127
|
+
"""Returns a string representation of the plugin program which reads the given array from the given location into the provided sharding."""
|
|
128
|
+
if not isinstance(devices, np.ndarray):
|
|
129
|
+
devices = np.array(devices)
|
|
130
|
+
|
|
131
|
+
timeout_seconds, timeout_fractional_seconds = divmod(
|
|
132
|
+
timeout.total_seconds(), 1
|
|
133
|
+
)
|
|
134
|
+
timeout_nanoseconds = timeout_fractional_seconds * 1e9
|
|
135
|
+
return json.dumps({
|
|
136
|
+
"persistenceReadRequest": {
|
|
137
|
+
"b64_location": string_to_base64(location_path),
|
|
138
|
+
"b64_shape_proto_string": get_shape_string(dtype, shape),
|
|
139
|
+
"b64_name": string_to_base64(name),
|
|
140
|
+
"b64_hlo_sharding_string": get_hlo_sharding_string(
|
|
141
|
+
sharding, len(shape)
|
|
142
|
+
),
|
|
143
|
+
"devices": {
|
|
144
|
+
"device_ids": [device.id for device in devices.flatten()]
|
|
145
|
+
},
|
|
146
|
+
"timeout": {
|
|
147
|
+
"seconds": int(timeout_seconds),
|
|
148
|
+
"nanos": int(timeout_nanoseconds),
|
|
149
|
+
},
|
|
150
|
+
}
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def write_one_array(
|
|
155
|
+
location: str,
|
|
156
|
+
name: str,
|
|
157
|
+
value: jax.Array,
|
|
158
|
+
timeout: datetime.timedelta,
|
|
159
|
+
):
|
|
160
|
+
"""Creates the write array plugin program string, compiles it to an executable, calls it and returns an awaitable future."""
|
|
161
|
+
write_request = get_write_request(location, name, value, timeout)
|
|
162
|
+
write_executable = plugin_executable.PluginExecutable(write_request)
|
|
163
|
+
_, write_future = write_executable.call([value])
|
|
164
|
+
return write_future
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def read_one_array(
|
|
168
|
+
location: str,
|
|
169
|
+
name: str,
|
|
170
|
+
dtype: np.dtype,
|
|
171
|
+
shape: Sequence[int],
|
|
172
|
+
shardings: jax.sharding.Sharding,
|
|
173
|
+
devices: Union[Sequence[jax.Device], np.ndarray],
|
|
174
|
+
timeout: datetime.timedelta,
|
|
175
|
+
):
|
|
176
|
+
"""Creates the read array plugin program string, compiles it to an executable, calls it and returns the result."""
|
|
177
|
+
read_request = get_read_request(
|
|
178
|
+
location,
|
|
179
|
+
name,
|
|
180
|
+
dtype,
|
|
181
|
+
shape,
|
|
182
|
+
shardings,
|
|
183
|
+
devices,
|
|
184
|
+
timeout,
|
|
185
|
+
)
|
|
186
|
+
read_executable = plugin_executable.PluginExecutable(read_request)
|
|
187
|
+
out_aval = core.ShapedArray(shape, dtype)
|
|
188
|
+
read_array, read_future = read_executable.call(
|
|
189
|
+
out_shardings=[shardings], out_avals=[out_aval]
|
|
190
|
+
)
|
|
191
|
+
read_future.result()
|
|
192
|
+
return read_array[0]
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# Copyright 2024 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
"""TypeHandlers supporting Pathways backend."""
|
|
15
|
+
|
|
16
|
+
import collections
|
|
17
|
+
import datetime
|
|
18
|
+
import functools
|
|
19
|
+
import typing
|
|
20
|
+
from typing import Optional, Sequence
|
|
21
|
+
|
|
22
|
+
from absl import logging
|
|
23
|
+
import jax
|
|
24
|
+
from orbax.checkpoint import future
|
|
25
|
+
from orbax.checkpoint import type_handlers
|
|
26
|
+
from pathwaysutils.persistence import helper
|
|
27
|
+
|
|
28
|
+
ParamInfo = type_handlers.ParamInfo
|
|
29
|
+
SaveArgs = type_handlers.SaveArgs
|
|
30
|
+
RestoreArgs = type_handlers.RestoreArgs
|
|
31
|
+
ArrayRestoreArgs = type_handlers.ArrayRestoreArgs
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def extract_parent_dir_and_name(
|
|
35
|
+
infos: Sequence[ParamInfo],
|
|
36
|
+
) -> tuple[Sequence[str], Sequence[str]]:
|
|
37
|
+
"""Extracts names and locations from ParamInfos."""
|
|
38
|
+
parent_dirs = [str(info.parent_dir) for info in infos]
|
|
39
|
+
names = [str(info.name) for info in infos]
|
|
40
|
+
return parent_dirs, names
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class CloudPathwaysArrayHandler(type_handlers.ArrayHandler):
|
|
44
|
+
"""A TypeHandler for array types when using Pathways."""
|
|
45
|
+
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
read_timeout: Optional[datetime.timedelta] = None,
|
|
49
|
+
use_ocdbt: bool = False,
|
|
50
|
+
):
|
|
51
|
+
"""Constructor.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
read_timeout: Duration indicating the timeout for reading arrays
|
|
55
|
+
use_ocdbt: allows using Tensorstore OCDBT driver.
|
|
56
|
+
"""
|
|
57
|
+
self._read_timeout = read_timeout
|
|
58
|
+
|
|
59
|
+
if use_ocdbt:
|
|
60
|
+
raise ValueError('OCDBT not supported for Pathways.')
|
|
61
|
+
super().__init__()
|
|
62
|
+
|
|
63
|
+
async def serialize(
|
|
64
|
+
self,
|
|
65
|
+
values: Sequence[jax.Array],
|
|
66
|
+
infos: Sequence[ParamInfo],
|
|
67
|
+
args: Optional[Sequence[SaveArgs]] = None,
|
|
68
|
+
) -> Sequence[future.Future]:
|
|
69
|
+
"""Uses Pathways Persistence API to serialize a jax array."""
|
|
70
|
+
type_handlers.check_input_arguments(values, infos, args)
|
|
71
|
+
|
|
72
|
+
if any([arg.dtype is not None for arg in args]):
|
|
73
|
+
raise ValueError('Casting during save not supported for Pathways.')
|
|
74
|
+
|
|
75
|
+
locations, names = extract_parent_dir_and_name(infos)
|
|
76
|
+
f = functools.partial(
|
|
77
|
+
helper.write_one_array, timeout=self._read_timeout
|
|
78
|
+
)
|
|
79
|
+
return list(map(f, locations, names, values))
|
|
80
|
+
|
|
81
|
+
async def deserialize(
|
|
82
|
+
self,
|
|
83
|
+
infos: Sequence[ParamInfo],
|
|
84
|
+
args: Optional[Sequence[RestoreArgs]] = None,
|
|
85
|
+
) -> Sequence[jax.Array]:
|
|
86
|
+
"""Uses Pathways Persistence API to deserialize a jax array."""
|
|
87
|
+
if args is None:
|
|
88
|
+
raise ValueError('Must provide ArrayRestoreArgs to restore as jax.Array.')
|
|
89
|
+
type_handlers.check_input_arguments(infos, args)
|
|
90
|
+
|
|
91
|
+
global_meshes = []
|
|
92
|
+
mesh_axes = []
|
|
93
|
+
global_shapes = []
|
|
94
|
+
dtypes = []
|
|
95
|
+
shardings = []
|
|
96
|
+
|
|
97
|
+
should_open_metadata = False
|
|
98
|
+
for arg in args:
|
|
99
|
+
if not isinstance(arg, ArrayRestoreArgs):
|
|
100
|
+
raise ValueError(
|
|
101
|
+
'To restore jax.Array, provide ArrayRestoreArgs; found'
|
|
102
|
+
f' {type(arg).__name__}'
|
|
103
|
+
)
|
|
104
|
+
arg = typing.cast(ArrayRestoreArgs, arg)
|
|
105
|
+
if arg.sharding is None and (arg.mesh is None or arg.mesh_axes is None):
|
|
106
|
+
raise ValueError(
|
|
107
|
+
'Sharding of jax.Array cannot be None. Provide `mesh`'
|
|
108
|
+
' and `mesh_axes` OR `sharding`.'
|
|
109
|
+
)
|
|
110
|
+
if arg.sharding is None:
|
|
111
|
+
global_meshes.append(arg.mesh)
|
|
112
|
+
mesh_axes.append(arg.mesh_axes)
|
|
113
|
+
shardings.append(
|
|
114
|
+
jax.sharding.NamedSharding(mesh=arg.mesh, spec=arg.mesh_axes)
|
|
115
|
+
)
|
|
116
|
+
else:
|
|
117
|
+
if not isinstance(arg.sharding, jax.sharding.NamedSharding):
|
|
118
|
+
raise ValueError('Pathways only supports jax.sharding.NamedSharding.')
|
|
119
|
+
sharding = typing.cast(jax.sharding.NamedSharding, arg.sharding)
|
|
120
|
+
global_meshes.append(sharding.mesh)
|
|
121
|
+
mesh_axes.append(sharding.spec)
|
|
122
|
+
shardings.append(sharding)
|
|
123
|
+
if arg.global_shape is None or arg.dtype is None:
|
|
124
|
+
logging.warning(
|
|
125
|
+
'Shape or dtype not provided for restoration. Provide these'
|
|
126
|
+
' properties for improved performance.'
|
|
127
|
+
)
|
|
128
|
+
should_open_metadata = True
|
|
129
|
+
global_shapes.append(arg.global_shape)
|
|
130
|
+
dtypes.append(arg.dtype)
|
|
131
|
+
|
|
132
|
+
if should_open_metadata:
|
|
133
|
+
metadatas = await self.metadata(infos)
|
|
134
|
+
global_shapes = [
|
|
135
|
+
m.shape if s is None else s for m, s in zip(metadatas, global_shapes)
|
|
136
|
+
]
|
|
137
|
+
dtypes = [m.dtype if d is None else d for m, d in zip(metadatas, dtypes)]
|
|
138
|
+
|
|
139
|
+
# Group inputs by global_mesh so that we can perform batched Array
|
|
140
|
+
# construction for each global_mesh.
|
|
141
|
+
inputs_by_global_mesh = collections.defaultdict(list)
|
|
142
|
+
for i, global_mesh in enumerate(global_meshes):
|
|
143
|
+
inputs_by_global_mesh[global_mesh].append(i)
|
|
144
|
+
|
|
145
|
+
results = [None] * len(infos)
|
|
146
|
+
|
|
147
|
+
for global_mesh, idxs in inputs_by_global_mesh.items():
|
|
148
|
+
grouped_infos = [infos[idx] for idx in idxs]
|
|
149
|
+
grouped_global_shapes = [global_shapes[idx] for idx in idxs]
|
|
150
|
+
grouped_dtypes = [dtypes[idx] for idx in idxs]
|
|
151
|
+
grouped_shardings = [shardings[idx] for idx in idxs]
|
|
152
|
+
locations, names = extract_parent_dir_and_name(grouped_infos)
|
|
153
|
+
f = functools.partial(
|
|
154
|
+
helper.read_one_array,
|
|
155
|
+
devices=global_mesh.devices,
|
|
156
|
+
timeout=self._read_timeout,
|
|
157
|
+
)
|
|
158
|
+
grouped_arrays = [
|
|
159
|
+
f(
|
|
160
|
+
location=location,
|
|
161
|
+
name=name,
|
|
162
|
+
dtype=dtype,
|
|
163
|
+
shape=shape,
|
|
164
|
+
shardings=sharding,
|
|
165
|
+
)
|
|
166
|
+
for location, name, dtype, shape, sharding in zip(
|
|
167
|
+
locations,
|
|
168
|
+
names,
|
|
169
|
+
grouped_dtypes,
|
|
170
|
+
grouped_global_shapes,
|
|
171
|
+
grouped_shardings,
|
|
172
|
+
)
|
|
173
|
+
]
|
|
174
|
+
for idx, arr in zip(idxs, grouped_arrays):
|
|
175
|
+
results[idx] = arr
|
|
176
|
+
return results # pytype: disable=bad-return-type
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def register_pathways_handlers(
|
|
180
|
+
read_timeout: Optional[datetime.timedelta] = None,
|
|
181
|
+
):
|
|
182
|
+
"""Function that must be called before saving or restoring with Pathways."""
|
|
183
|
+
logging.debug(
|
|
184
|
+
'Registering CloudPathwaysArrayHandler (Pathways Persistence API).'
|
|
185
|
+
)
|
|
186
|
+
type_handlers.register_type_handler(
|
|
187
|
+
jax.Array,
|
|
188
|
+
CloudPathwaysArrayHandler(
|
|
189
|
+
read_timeout=read_timeout,
|
|
190
|
+
),
|
|
191
|
+
override=True,
|
|
192
|
+
)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# Copyright 2024 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
"""PluginExecutable is a class for executing plugin programs."""
|
|
15
|
+
|
|
16
|
+
import concurrent.futures
|
|
17
|
+
import threading
|
|
18
|
+
from typing import List, Sequence, Tuple, Union
|
|
19
|
+
|
|
20
|
+
import jax
|
|
21
|
+
from jax._src.interpreters import pxla
|
|
22
|
+
from jaxlib.xla_extension import ifrt_programs
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class PluginExecutable:
|
|
26
|
+
"""Class for running compiled IFRT program over the IFRT Proxy."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, prog_str: str):
|
|
29
|
+
ifrt_client = jax.local_devices()[0].client
|
|
30
|
+
program = ifrt_programs.make_plugin_program(prog_str)
|
|
31
|
+
options = ifrt_programs.make_plugin_compile_options()
|
|
32
|
+
self.compiled = ifrt_client.compile_ifrt_program(program, options)
|
|
33
|
+
|
|
34
|
+
def call(
|
|
35
|
+
self,
|
|
36
|
+
in_arr: Sequence[Union[jax.Array, List[jax.Array]]] = (),
|
|
37
|
+
out_shardings: Sequence[jax.sharding.Sharding] = (),
|
|
38
|
+
out_avals: Sequence[jax.core.ShapedArray] = (),
|
|
39
|
+
out_committed: bool = True,
|
|
40
|
+
) -> Tuple[Sequence[jax.Array], concurrent.futures.Future[None]]:
|
|
41
|
+
"""Runs the compiled IFRT program and returns the result and a future."""
|
|
42
|
+
results_with_token = self.compiled.execute_sharded(in_arr, with_tokens=True)
|
|
43
|
+
|
|
44
|
+
out_arr = results_with_token.consume_with_handlers(
|
|
45
|
+
pxla.global_avals_to_results_handler(
|
|
46
|
+
out_avals, out_shardings, out_committed
|
|
47
|
+
).handlers
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
out_fut = concurrent.futures.Future()
|
|
51
|
+
|
|
52
|
+
def call_on_done():
|
|
53
|
+
try:
|
|
54
|
+
results_with_token.consume_token().block_until_ready()
|
|
55
|
+
except Exception as e: # pylint: disable=broad-exception-caught
|
|
56
|
+
out_fut.set_exception(e)
|
|
57
|
+
return
|
|
58
|
+
out_fut.set_result(None)
|
|
59
|
+
|
|
60
|
+
t = threading.Thread(
|
|
61
|
+
target=call_on_done, name="plugin_executable_call_on_done"
|
|
62
|
+
)
|
|
63
|
+
t.start()
|
|
64
|
+
|
|
65
|
+
return (out_arr, out_fut)
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# Copyright 2024 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
"""Profiling utilites."""
|
|
15
|
+
|
|
16
|
+
import dataclasses
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
|
|
20
|
+
from absl import logging
|
|
21
|
+
import fastapi
|
|
22
|
+
import jax
|
|
23
|
+
from jax import numpy as jnp
|
|
24
|
+
from pathwaysutils import plugin_executable
|
|
25
|
+
import uvicorn
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class _ProfileState:
|
|
29
|
+
def __init__(self):
|
|
30
|
+
self.executable = None
|
|
31
|
+
self.lock = threading.Lock()
|
|
32
|
+
|
|
33
|
+
def reset(self):
|
|
34
|
+
self.executable = None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
_profile_state = _ProfileState()
|
|
38
|
+
_original_start_trace = jax.profiler.start_trace
|
|
39
|
+
_original_stop_trace = jax.profiler.stop_trace
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def toy_computation():
|
|
43
|
+
"""A toy computation to run before the first profile."""
|
|
44
|
+
x = jax.jit(lambda x: x + 1)(jnp.array(1))
|
|
45
|
+
x.block_until_ready()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def start_trace(gcs_bucket: str):
|
|
49
|
+
"""Starts a profiler trace."""
|
|
50
|
+
with _profile_state.lock:
|
|
51
|
+
if start_trace._first_profile_start: # pylint: disable=protected-access, attribute-error
|
|
52
|
+
start_trace._first_profile_start = False # pylint: disable=protected-access
|
|
53
|
+
toy_computation()
|
|
54
|
+
|
|
55
|
+
if _profile_state.executable is not None:
|
|
56
|
+
raise ValueError(
|
|
57
|
+
"start_trace called while a trace is already being taken!"
|
|
58
|
+
)
|
|
59
|
+
_profile_state.executable = plugin_executable.PluginExecutable(
|
|
60
|
+
f"{{profileRequest: {{traceLocation: '{gcs_bucket}'}}}}"
|
|
61
|
+
)
|
|
62
|
+
try:
|
|
63
|
+
_profile_state.executable.call()[1].result()
|
|
64
|
+
except:
|
|
65
|
+
_profile_state.reset()
|
|
66
|
+
raise
|
|
67
|
+
|
|
68
|
+
_original_start_trace(gcs_bucket)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
start_trace._first_profile_start = True # pylint: disable=protected-access
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def stop_trace():
|
|
75
|
+
"""Stops the currently-running profiler trace."""
|
|
76
|
+
with _profile_state.lock:
|
|
77
|
+
if _profile_state.executable is None:
|
|
78
|
+
raise ValueError("stop_trace called before a trace is being taken!")
|
|
79
|
+
try:
|
|
80
|
+
_profile_state.executable.call()[1].result()
|
|
81
|
+
except:
|
|
82
|
+
_profile_state.reset()
|
|
83
|
+
raise
|
|
84
|
+
_profile_state.reset()
|
|
85
|
+
|
|
86
|
+
_original_stop_trace()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
_profiler_thread = None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def start_server(port: int):
|
|
93
|
+
"""Starts the profiling server on port `port`.
|
|
94
|
+
|
|
95
|
+
The signature is slightly different from `jax.profiler.start_server`
|
|
96
|
+
because no handle to the server is returned because there is no
|
|
97
|
+
`xla_client.profiler.ProfilerServer` to return.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
port : The port to start the server on.
|
|
101
|
+
"""
|
|
102
|
+
def server_loop(port: int):
|
|
103
|
+
logging.debug("Starting JAX profiler server on port %s", port)
|
|
104
|
+
app = fastapi.FastAPI()
|
|
105
|
+
|
|
106
|
+
@dataclasses.dataclass
|
|
107
|
+
class ProfilingConfig:
|
|
108
|
+
duration_ms: int
|
|
109
|
+
repository_path: str
|
|
110
|
+
|
|
111
|
+
@app.post("/profiling")
|
|
112
|
+
async def profiling(pc: ProfilingConfig): # pylint: disable=unused-variable
|
|
113
|
+
logging.debug("Capturing profiling data for %s ms", pc.duration_ms)
|
|
114
|
+
logging.debug("Writing profiling data to %s", pc.repository_path)
|
|
115
|
+
jax.profiler.start_trace(pc.repository_path)
|
|
116
|
+
time.sleep(pc.duration_ms / 1e3)
|
|
117
|
+
jax.profiler.stop_trace()
|
|
118
|
+
return {"response": "profiling completed"}
|
|
119
|
+
|
|
120
|
+
uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")
|
|
121
|
+
|
|
122
|
+
global _profiler_thread
|
|
123
|
+
if _profiler_thread is not None:
|
|
124
|
+
raise ValueError("Only one profiler server can be active at a time.")
|
|
125
|
+
|
|
126
|
+
_profiler_thread = threading.Thread(target=server_loop, args=(port,))
|
|
127
|
+
_profiler_thread.start()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def stop_server():
|
|
131
|
+
"""Raises an error if there is not an active profiler server but otherwise does nothing.
|
|
132
|
+
|
|
133
|
+
Pathways profiling servers are not stoppable at this time.
|
|
134
|
+
"""
|
|
135
|
+
if _profiler_thread is None:
|
|
136
|
+
raise ValueError("No active profiler server.")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def monkey_patch_jax():
|
|
140
|
+
"""Monkey patches JAX with Pathways versions of functions.
|
|
141
|
+
|
|
142
|
+
The signatures in patched functions should match the original.
|
|
143
|
+
|
|
144
|
+
Patched functions are:
|
|
145
|
+
- `jax.profiler.start_trace`
|
|
146
|
+
https://jax.readthedocs.io/en/latest/_autosummary/jax.profiler.start_trace.html
|
|
147
|
+
- `jax.profiler.stop_trace`
|
|
148
|
+
https://jax.readthedocs.io/en/latest/_autosummary/jax.profiler.stop_trace.html
|
|
149
|
+
- `jax.profiler.start_server`
|
|
150
|
+
https://jax.readthedocs.io/en/latest/_autosummary/jax.profiler.start_server.html
|
|
151
|
+
- `jax.profiler.stop_server`
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
def start_trace_patch(
|
|
155
|
+
log_dir,
|
|
156
|
+
create_perfetto_link: bool = False, # pylint: disable=unused-argument
|
|
157
|
+
create_perfetto_trace: bool = False, # pylint: disable=unused-argument
|
|
158
|
+
) -> None:
|
|
159
|
+
logging.debug("jax.profile.start_trace patched with pathways' start_trace")
|
|
160
|
+
return start_trace(log_dir)
|
|
161
|
+
|
|
162
|
+
jax.profiler.start_trace = start_trace_patch
|
|
163
|
+
|
|
164
|
+
def stop_trace_patch() -> None:
|
|
165
|
+
logging.debug("jax.profile.stop_trace patched with pathways' stop_trace")
|
|
166
|
+
return stop_trace()
|
|
167
|
+
|
|
168
|
+
jax.profiler.stop_trace = stop_trace_patch
|
|
169
|
+
|
|
170
|
+
def start_server_patch(port: int):
|
|
171
|
+
logging.debug(
|
|
172
|
+
"jax.profile.start_server patched with pathways' start_server"
|
|
173
|
+
)
|
|
174
|
+
return start_server(port)
|
|
175
|
+
|
|
176
|
+
jax.profiler.start_server = start_server_patch
|
|
177
|
+
|
|
178
|
+
def stop_server_patch():
|
|
179
|
+
logging.debug("jax.profile.stop_server patched with pathways' stop_server")
|
|
180
|
+
return stop_server()
|
|
181
|
+
|
|
182
|
+
jax.profiler.stop_server = stop_server_patch
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Copyright 2024 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
"""Register the IFRT Proxy as a backend for JAX."""
|
|
15
|
+
|
|
16
|
+
import jax
|
|
17
|
+
from jax._src import xla_bridge
|
|
18
|
+
from jaxlib.xla_extension import ifrt_proxy
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def register_backend_factory():
|
|
22
|
+
xla_bridge.register_backend_factory(
|
|
23
|
+
"proxy",
|
|
24
|
+
lambda: ifrt_proxy.get_client(
|
|
25
|
+
jax.config.read("jax_backend_target"),
|
|
26
|
+
ifrt_proxy.ClientConnectionOptions(),
|
|
27
|
+
),
|
|
28
|
+
priority=-1,
|
|
29
|
+
)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
# Project metadata. Available keys are documented at:
|
|
3
|
+
# https://packaging.python.org/en/latest/specifications/declaring-project-metadata
|
|
4
|
+
name = "pathwaysutils"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = {file = "LICENSE"}
|
|
8
|
+
authors = [{name = "Pathways-on-Cloud Utilities Developers", email="pathwaysutils-dev@google.com"}]
|
|
9
|
+
classifiers = [ # List of https://pypi.org/classifiers/
|
|
10
|
+
"License :: OSI Approved :: Apache Software License",
|
|
11
|
+
]
|
|
12
|
+
keywords = []
|
|
13
|
+
|
|
14
|
+
dependencies = [
|
|
15
|
+
"absl-py",
|
|
16
|
+
"fastapi",
|
|
17
|
+
"google-cloud-logging",
|
|
18
|
+
"jax>=0.4.26",
|
|
19
|
+
"orbax-checkpoint",
|
|
20
|
+
"uvicorn",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
# `version` is automatically set by flit to use `my_project.__version__`
|
|
24
|
+
# `description` is automatically set by flit to use `my_project.__doc__`
|
|
25
|
+
dynamic = ["version", "description"]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
homepage = "https://github.com/AI-Hypercomputer/pathways-utils"
|
|
29
|
+
repository = "https://github.com/AI-Hypercomputer/pathways-utils"
|
|
30
|
+
changelog = "https://github.com/AI-Hypercomputer/pathways-utils/blob/main/CHANGELOG.md"
|
|
31
|
+
# documentation = ""
|
|
32
|
+
|
|
33
|
+
[project.optional-dependencies]
|
|
34
|
+
# Development deps (unittest, linting, formating,...)
|
|
35
|
+
# Installed through `pip install -e .[dev]`
|
|
36
|
+
dev = [
|
|
37
|
+
"pylint>=2.6.0",
|
|
38
|
+
"pyink",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[tool.pyink]
|
|
42
|
+
# Formatting configuration to follow Google style-guide
|
|
43
|
+
line-length = 80
|
|
44
|
+
unstable = true
|
|
45
|
+
pyink-indentation = 2
|
|
46
|
+
pyink-use-majority-quotes = true
|
|
47
|
+
|
|
48
|
+
[build-system]
|
|
49
|
+
requires = ["flit_core >=3.8,<4"]
|
|
50
|
+
build-backend = "flit_core.buildapi"
|
|
51
|
+
|
|
52
|
+
[tool.flit.sdist]
|
|
53
|
+
exclude = [
|
|
54
|
+
"**/test",
|
|
55
|
+
]
|
|
56
|
+
|