Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- maxtext-setup/jetstream/AUTHORS +1 -0
- maxtext-setup/jetstream/CONTRIBUTING.md +33 -0
- maxtext-setup/jetstream/LICENSE +202 -0
- maxtext-setup/jetstream/README.md +38 -0
- maxtext-setup/jetstream/benchmarks/README.md +50 -0
- maxtext-setup/jetstream/benchmarks/benchmark_serving.py +602 -0
- maxtext-setup/jetstream/benchmarks/eval_accuracy.py +55 -0
- maxtext-setup/jetstream/benchmarks/requirements.in +3 -0
- maxtext-setup/jetstream/build/lib/jetstream/__init__.py +14 -0
- maxtext-setup/jetstream/build/lib/jetstream/core/__init__.py +14 -0
- maxtext-setup/jetstream/build/lib/jetstream/core/config_lib.py +155 -0
- maxtext-setup/jetstream/build/lib/jetstream/core/implementations/__init__.py +14 -0
- maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/__init__.py +14 -0
- maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/config.py +30 -0
- maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/server.py +49 -0
- maxtext-setup/jetstream/build/lib/jetstream/core/orchestrator.py +651 -0
- maxtext-setup/jetstream/build/lib/jetstream/core/orchestrator_test.py +103 -0
- maxtext-setup/jetstream/build/lib/jetstream/core/proto/__init__.py +14 -0
- maxtext-setup/jetstream/build/lib/jetstream/core/proto/jetstream_pb2.py +44 -0
- maxtext-setup/jetstream/build/lib/jetstream/core/proto/jetstream_pb2_grpc.py +87 -0
- maxtext-setup/jetstream/build/lib/jetstream/core/server_lib.py +105 -0
- maxtext-setup/jetstream/build/lib/jetstream/core/server_test.py +98 -0
- maxtext-setup/jetstream/build/lib/jetstream/engine/__init__.py +14 -0
- maxtext-setup/jetstream/build/lib/jetstream/engine/engine_api.py +225 -0
- maxtext-setup/jetstream/build/lib/jetstream/engine/mock_engine.py +258 -0
- maxtext-setup/jetstream/build/lib/jetstream/engine/mock_engine_test.py +114 -0
- maxtext-setup/jetstream/build/lib/jetstream/engine/mock_utils.py +77 -0
- maxtext-setup/jetstream/build/lib/jetstream/engine/token_utils.py +207 -0
- maxtext-setup/jetstream/build/lib/jetstream/engine/tokenizer_pb2.py +41 -0
- maxtext-setup/jetstream/build/lib/jetstream/engine/tokenizer_pb2_grpc.py +18 -0
- maxtext-setup/jetstream/build/lib/jetstream/engine/utils_test.py +83 -0
- maxtext-setup/jetstream/google_jetstream.egg-info/PKG-INFO +52 -0
- maxtext-setup/jetstream/google_jetstream.egg-info/SOURCES.txt +32 -0
- maxtext-setup/jetstream/google_jetstream.egg-info/dependency_links.txt +1 -0
- maxtext-setup/jetstream/google_jetstream.egg-info/requires.txt +8 -0
- maxtext-setup/jetstream/google_jetstream.egg-info/top_level.txt +1 -0
- maxtext-setup/jetstream/jetstream/__init__.py +14 -0
- maxtext-setup/jetstream/jetstream/core/README.md +3 -0
- maxtext-setup/jetstream/jetstream/core/__init__.py +14 -0
- maxtext-setup/jetstream/jetstream/core/config_lib.py +155 -0
- maxtext-setup/jetstream/jetstream/core/implementations/__init__.py +14 -0
- maxtext-setup/jetstream/jetstream/core/implementations/mock/README.md +3 -0
- maxtext-setup/jetstream/jetstream/core/implementations/mock/__init__.py +14 -0
- maxtext-setup/jetstream/jetstream/core/implementations/mock/config.py +30 -0
- maxtext-setup/jetstream/jetstream/core/implementations/mock/server.py +49 -0
- maxtext-setup/jetstream/jetstream/core/orchestrator.py +651 -0
- maxtext-setup/jetstream/jetstream/core/orchestrator_test.py +103 -0
- maxtext-setup/jetstream/jetstream/core/proto/__init__.py +14 -0
- maxtext-setup/jetstream/jetstream/core/proto/jetstream.proto +38 -0
- maxtext-setup/jetstream/jetstream/core/proto/jetstream_pb2.py +44 -0
maxtext-setup/jetstream/AUTHORS
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Google LLC
|
maxtext-setup/jetstream/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# How to Contribute
|
| 2 |
+
|
| 3 |
+
We'd love to accept your patches and contributions to this project.
|
| 4 |
+
|
| 5 |
+
## Before you begin
|
| 6 |
+
|
| 7 |
+
### Sign our Contributor License Agreement
|
| 8 |
+
|
| 9 |
+
Contributions to this project must be accompanied by a
|
| 10 |
+
[Contributor License Agreement](https://cla.developers.google.com/about) (CLA).
|
| 11 |
+
You (or your employer) retain the copyright to your contribution; this simply
|
| 12 |
+
gives us permission to use and redistribute your contributions as part of the
|
| 13 |
+
project.
|
| 14 |
+
|
| 15 |
+
If you or your current employer have already signed the Google CLA (even if it
|
| 16 |
+
was for a different project), you probably don't need to do it again.
|
| 17 |
+
|
| 18 |
+
Visit <https://cla.developers.google.com/> to see your current agreements or to
|
| 19 |
+
sign a new one.
|
| 20 |
+
|
| 21 |
+
### Review our Community Guidelines
|
| 22 |
+
|
| 23 |
+
This project follows
|
| 24 |
+
[Google's Open Source Community Guidelines](https://opensource.google/conduct/).
|
| 25 |
+
|
| 26 |
+
## Contribution process
|
| 27 |
+
|
| 28 |
+
### Code Reviews
|
| 29 |
+
|
| 30 |
+
All submissions, including submissions by project members, require review. We
|
| 31 |
+
use GitHub pull requests for this purpose. Consult
|
| 32 |
+
[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
|
| 33 |
+
information on using pull requests.
|
maxtext-setup/jetstream/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.
|
maxtext-setup/jetstream/README.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# JetStream - A throughput and memory optimized engine for LLM inference on TPU and GPU
|
| 2 |
+
|
| 3 |
+
## About
|
| 4 |
+
|
| 5 |
+
JetStream is a fast library for LLM inference and serving on TPU and GPU.
|
| 6 |
+
|
| 7 |
+
## Getting Started
|
| 8 |
+
|
| 9 |
+
### Run local server & Testing
|
| 10 |
+
|
| 11 |
+
Use the following commands to run a server locally:
|
| 12 |
+
```
|
| 13 |
+
# Start a server
|
| 14 |
+
python -m jetstream.core.implementations.mock.server
|
| 15 |
+
|
| 16 |
+
# Test local mock server
|
| 17 |
+
python -m jetstream.core.tools.requester
|
| 18 |
+
|
| 19 |
+
# Load test local mock server
|
| 20 |
+
python -m jetstream.core.tools.load_tester
|
| 21 |
+
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
### Test core modules
|
| 25 |
+
```
|
| 26 |
+
# Test JetStream core orchestrator
|
| 27 |
+
python -m jetstream.core.orchestrator_test
|
| 28 |
+
|
| 29 |
+
# Test JetStream core server library
|
| 30 |
+
python -m jetstream.core.server_test
|
| 31 |
+
|
| 32 |
+
# Test mock JetStream engine implementation
|
| 33 |
+
python -m jetstream.engine.mock_engine_test
|
| 34 |
+
|
| 35 |
+
# Test mock JetStream token utils
|
| 36 |
+
python -m jetstream.engine.utils_test
|
| 37 |
+
|
| 38 |
+
```
|
maxtext-setup/jetstream/benchmarks/README.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# JetStream Benchmark And Eval
|
| 2 |
+
|
| 3 |
+
## Install Dependencies
|
| 4 |
+
|
| 5 |
+
```
|
| 6 |
+
cd ~/JetStream/benchmarks
|
| 7 |
+
pip install -r requirements.in
|
| 8 |
+
```
|
| 9 |
+
|
| 10 |
+
## Benchmark
|
| 11 |
+
|
| 12 |
+
### Prepare DataSet
|
| 13 |
+
|
| 14 |
+
```
|
| 15 |
+
cd ~/data
|
| 16 |
+
wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/resolve/main/ShareGPT_V3_unfiltered_cleaned_split.json
|
| 17 |
+
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
### Run Benchmark with maxtext tokenizer
|
| 21 |
+
|
| 22 |
+
```
|
| 23 |
+
python benchmark_serving.py \
|
| 24 |
+
--tokenizer /home/{username}/maxtext/assets/tokenizer \
|
| 25 |
+
--num-prompts 10 \
|
| 26 |
+
--dataset ~/data/ShareGPT_V3_unfiltered_cleaned_split.json
|
| 27 |
+
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
### Save request outputs in Benchmark
|
| 31 |
+
|
| 32 |
+
Please use --save-request-outputs flag to enable this feature.
|
| 33 |
+
|
| 34 |
+
```
|
| 35 |
+
python benchmark_serving.py \
|
| 36 |
+
--tokenizer /home/{username}/maxtext/assets/tokenizer \
|
| 37 |
+
--num-prompts 10 \
|
| 38 |
+
--dataset ~/data/ShareGPT_V3_unfiltered_cleaned_split.json \
|
| 39 |
+
--save-request-outputs
|
| 40 |
+
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
## Eval Accuracy
|
| 44 |
+
|
| 45 |
+
Evaluate inference genereted output accuracy using saved request outputs.
|
| 46 |
+
|
| 47 |
+
```
|
| 48 |
+
python eval_accuracy.py
|
| 49 |
+
|
| 50 |
+
```
|
maxtext-setup/jetstream/benchmarks/benchmark_serving.py
ADDED
|
@@ -0,0 +1,602 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Benchmark JetStream online serving.
|
| 16 |
+
|
| 17 |
+
On the server side, run one of the following commands:
|
| 18 |
+
* For real server, you need to pass correct server config (include the model config that
|
| 19 |
+
being passed into your engine impl) to the command below. Refer to config_lib.py and
|
| 20 |
+
implementations/mock/config.py for config impl detail.
|
| 21 |
+
|
| 22 |
+
(run with real server)
|
| 23 |
+
python -m jetstream.core.implementations.<your_impl>.server \
|
| 24 |
+
--config <your_server_config>
|
| 25 |
+
|
| 26 |
+
(run with mock server)
|
| 27 |
+
python -m jetstream.core.implementations.mock.server
|
| 28 |
+
|
| 29 |
+
On the client side, run:
|
| 30 |
+
* For real server and shareGPT dataset, you need to pass the tokenizer, server config, and
|
| 31 |
+
dataset flags to the command below, and make some changes to the tokenizer logic in the
|
| 32 |
+
benchmark script (get_tokenizer and sample_requests func) to use your tokenizer correctly.
|
| 33 |
+
* Add `--save-result` flag to save the benchmark result to a json file in current folder.
|
| 34 |
+
* Add `--threads` flag to set the maximum number of threads used for request dispatching.
|
| 35 |
+
|
| 36 |
+
(run with real model and engines)
|
| 37 |
+
python -m benchmarks.benchmark_serving \
|
| 38 |
+
--tokenizer <your_tokenizer> --dataset <target_dataset_path> \
|
| 39 |
+
--request-rate <request_rate>
|
| 40 |
+
|
| 41 |
+
(run with mock)
|
| 42 |
+
python -m benchmarks.benchmark_serving \
|
| 43 |
+
--request-rate 1
|
| 44 |
+
|
| 45 |
+
e2e example: python3 benchmark_serving.py --tokenizer /home/rwitten/maxtext/assets/tokenizer --num-prompts 100 --dataset ~/ShareGPT_V3_unfiltered_cleaned_split.json
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
import tensorflow as tf
|
| 50 |
+
import tensorflow_text as tftxt
|
| 51 |
+
|
| 52 |
+
import argparse
|
| 53 |
+
import asyncio
|
| 54 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 55 |
+
from dataclasses import dataclass
|
| 56 |
+
from datetime import datetime
|
| 57 |
+
import json
|
| 58 |
+
import random
|
| 59 |
+
import time
|
| 60 |
+
from typing import Any, AsyncGenerator, List, Tuple
|
| 61 |
+
import grpc
|
| 62 |
+
from jetstream.core.proto import jetstream_pb2
|
| 63 |
+
from jetstream.core.proto import jetstream_pb2_grpc
|
| 64 |
+
import numpy as np
|
| 65 |
+
from tqdm.asyncio import tqdm
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@dataclass
|
| 69 |
+
class BenchmarkMetrics:
|
| 70 |
+
completed: int
|
| 71 |
+
total_input: int
|
| 72 |
+
total_output: int
|
| 73 |
+
request_throughput: float
|
| 74 |
+
input_throughput: float
|
| 75 |
+
output_throughput: float
|
| 76 |
+
mean_ttft_ms: float
|
| 77 |
+
median_ttft_ms: float
|
| 78 |
+
p99_ttft_ms: float
|
| 79 |
+
mean_tpot_ms: float
|
| 80 |
+
median_tpot_ms: float
|
| 81 |
+
p99_tpot_ms: float
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@dataclass
|
| 85 |
+
class InputRequest:
|
| 86 |
+
prompt: str = ""
|
| 87 |
+
prompt_len: int = 0
|
| 88 |
+
output: str = ""
|
| 89 |
+
output_len: int = 0
|
| 90 |
+
|
| 91 |
+
@dataclass
|
| 92 |
+
class RequestFuncOutput:
|
| 93 |
+
input_request: InputRequest = None
|
| 94 |
+
generated_token_list: list[str] = None
|
| 95 |
+
generated_text: str = None
|
| 96 |
+
success: bool = False
|
| 97 |
+
latency: float = 0
|
| 98 |
+
ttft: float = 0
|
| 99 |
+
prompt_len: int = 0
|
| 100 |
+
|
| 101 |
+
# Flatten the structure and return only the necessary results
|
| 102 |
+
def to_dict(self):
|
| 103 |
+
return {
|
| 104 |
+
"prompt": self.input_request.prompt,
|
| 105 |
+
"original_output": self.input_request.output,
|
| 106 |
+
"generated_text": self.generated_text,
|
| 107 |
+
"success": self.success,
|
| 108 |
+
"latency": self.latency,
|
| 109 |
+
"prompt_len": self.prompt_len
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def get_tokenizer(tokenizer_name: str) -> Any:
|
| 114 |
+
"""Return a tokenizer or a tokenizer placholder."""
|
| 115 |
+
if tokenizer_name == "test":
|
| 116 |
+
return "test"
|
| 117 |
+
else:
|
| 118 |
+
with tf.io.gfile.GFile(tokenizer_name, 'rb') as model_fp:
|
| 119 |
+
sp_model = model_fp.read()
|
| 120 |
+
sp_tokenizer = tftxt.SentencepieceTokenizer(
|
| 121 |
+
model=sp_model, add_bos=True, add_eos=False, reverse=False)
|
| 122 |
+
return sp_tokenizer
|
| 123 |
+
|
| 124 |
+
def sample_requests(
|
| 125 |
+
dataset_path: str,
|
| 126 |
+
num_requests: int,
|
| 127 |
+
tokenizer: Any,
|
| 128 |
+
max_output_length: int,
|
| 129 |
+
) -> List[InputRequest]:
|
| 130 |
+
# Load the dataset.
|
| 131 |
+
with open(dataset_path) as f:
|
| 132 |
+
dataset = json.load(f)
|
| 133 |
+
# Filter out the conversations with less than 2 turns.
|
| 134 |
+
dataset = [data for data in dataset if len(data["conversations"]) >= 2]
|
| 135 |
+
# Only keep the first two turns of each conversation.
|
| 136 |
+
dataset = [
|
| 137 |
+
(data["conversations"][0]["value"], data["conversations"][1]["value"])
|
| 138 |
+
for data in dataset
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
# some of these will be filtered out, so sample more than we need
|
| 142 |
+
sampled_indices = random.sample(range(len(dataset)), int(num_requests * 1.2))
|
| 143 |
+
dataset = [dataset[i] for i in sampled_indices]
|
| 144 |
+
|
| 145 |
+
# Tokenize the prompts and completions.
|
| 146 |
+
prompts = [prompt for prompt, _ in dataset]
|
| 147 |
+
prompt_token_ids = tokenizer.tokenize(
|
| 148 |
+
prompts
|
| 149 |
+
) # adjust this code based on tokenizer method
|
| 150 |
+
completions = [completion for _, completion in dataset]
|
| 151 |
+
completion_token_ids = tokenizer.tokenize(
|
| 152 |
+
completions
|
| 153 |
+
) # adjust this code based on tokenizer method
|
| 154 |
+
tokenized_dataset = []
|
| 155 |
+
for i in range(len(dataset)):
|
| 156 |
+
output_len = len(completion_token_ids[i])
|
| 157 |
+
tokenized_dataset.append((prompts[i], prompt_token_ids[i], completions[i], output_len))
|
| 158 |
+
|
| 159 |
+
# Filter out too long sequences.
|
| 160 |
+
filtered_dataset: List[InputRequest] = []
|
| 161 |
+
|
| 162 |
+
for prompt, prompt_token_ids, output, output_len in tokenized_dataset:
|
| 163 |
+
prompt_len = len(prompt_token_ids)
|
| 164 |
+
if prompt_len < 4 or output_len < 4:
|
| 165 |
+
# Prune too short sequences.
|
| 166 |
+
# This is because TGI causes errors when the input or output length
|
| 167 |
+
# is too short.
|
| 168 |
+
continue
|
| 169 |
+
if prompt_len > 1024 or prompt_len + output_len > 2048:
|
| 170 |
+
# Prune too long sequences.
|
| 171 |
+
continue
|
| 172 |
+
reqeust = InputRequest(prompt, prompt_len, output, max_output_length)
|
| 173 |
+
filtered_dataset.append(reqeust)
|
| 174 |
+
|
| 175 |
+
# Sample the requests.
|
| 176 |
+
sampled_requests = random.sample(filtered_dataset, num_requests)
|
| 177 |
+
return sampled_requests
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
async def get_request(
|
| 181 |
+
input_requests: List[InputRequest],
|
| 182 |
+
request_rate: float,
|
| 183 |
+
) -> AsyncGenerator[InputRequest, None]:
|
| 184 |
+
input_requests = iter(input_requests)
|
| 185 |
+
for request in input_requests:
|
| 186 |
+
yield request
|
| 187 |
+
|
| 188 |
+
if request_rate == float("inf"):
|
| 189 |
+
# If the request rate is infinity, then we don't need to wait.
|
| 190 |
+
continue
|
| 191 |
+
# Sample the request interval from the exponential distribution.
|
| 192 |
+
interval = np.random.exponential(1.0 / request_rate)
|
| 193 |
+
# The next request will be sent after the interval.
|
| 194 |
+
await asyncio.sleep(interval)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def calculate_metrics(
|
| 198 |
+
input_requests: List[InputRequest],
|
| 199 |
+
outputs: List[RequestFuncOutput],
|
| 200 |
+
dur_s: float,
|
| 201 |
+
tokenizer: Any,
|
| 202 |
+
) -> BenchmarkMetrics:
|
| 203 |
+
total_output = 0
|
| 204 |
+
total_input = 0
|
| 205 |
+
completed = 0
|
| 206 |
+
per_token_latencies = []
|
| 207 |
+
ttfts = []
|
| 208 |
+
for i in range(len(outputs)):
|
| 209 |
+
if outputs[i].success:
|
| 210 |
+
output_len = len(
|
| 211 |
+
outputs[i].generated_token_list
|
| 212 |
+
if tokenizer != "test"
|
| 213 |
+
else ["Ċ", "Ō", "Ɵ"]
|
| 214 |
+
)
|
| 215 |
+
total_output += output_len
|
| 216 |
+
total_input += input_requests[i].prompt_len
|
| 217 |
+
per_token_latencies.append(outputs[i].latency / output_len)
|
| 218 |
+
ttfts.append(outputs[i].ttft)
|
| 219 |
+
completed += 1
|
| 220 |
+
|
| 221 |
+
metrics = BenchmarkMetrics(
|
| 222 |
+
completed=completed,
|
| 223 |
+
total_input=total_input,
|
| 224 |
+
total_output=total_output,
|
| 225 |
+
request_throughput=completed / dur_s,
|
| 226 |
+
input_throughput=total_input / dur_s,
|
| 227 |
+
output_throughput=total_output / dur_s,
|
| 228 |
+
mean_ttft_ms=np.mean(ttfts) * 1000,
|
| 229 |
+
median_ttft_ms=np.median(ttfts) * 1000,
|
| 230 |
+
p99_ttft_ms=np.percentile(ttfts, 99) * 1000,
|
| 231 |
+
mean_tpot_ms=np.mean(per_token_latencies) * 1000,
|
| 232 |
+
median_tpot_ms=np.median(per_token_latencies) * 1000,
|
| 233 |
+
p99_tpot_ms=np.percentile(per_token_latencies, 99) * 1000,
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
return metrics
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def grpc_sync_request(api_url: str, request: Any) -> tuple[list[str], float, float]:
|
| 240 |
+
"""Send grpc synchronous request since the current grpc server is sync."""
|
| 241 |
+
options = [("grpc.keepalive_timeout_ms", 10000)]
|
| 242 |
+
with grpc.insecure_channel(api_url, options=options) as channel:
|
| 243 |
+
grpc.channel_ready_future(channel).result()
|
| 244 |
+
stub = jetstream_pb2_grpc.OrchestratorStub(channel)
|
| 245 |
+
print("Making request")
|
| 246 |
+
ttft = 0
|
| 247 |
+
token_list = []
|
| 248 |
+
request_start_time = time.perf_counter()
|
| 249 |
+
response = stub.Decode(request)
|
| 250 |
+
for token in response:
|
| 251 |
+
if ttft == 0:
|
| 252 |
+
ttft = time.perf_counter() - request_start_time
|
| 253 |
+
token_list.append(token.response[0])
|
| 254 |
+
latency = time.perf_counter() - request_start_time
|
| 255 |
+
return token_list, ttft, latency
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
async def send_request(
|
| 259 |
+
api_url: str,
|
| 260 |
+
input_request: InputRequest,
|
| 261 |
+
pbar: tqdm,
|
| 262 |
+
session_cache: str,
|
| 263 |
+
priority: int,
|
| 264 |
+
threads: int,
|
| 265 |
+
) -> RequestFuncOutput:
|
| 266 |
+
"""Send the request to JetStream server."""
|
| 267 |
+
loop = asyncio.get_running_loop()
|
| 268 |
+
loop.set_default_executor(ThreadPoolExecutor(max_workers=threads))
|
| 269 |
+
request = jetstream_pb2.DecodeRequest(
|
| 270 |
+
session_cache=session_cache,
|
| 271 |
+
additional_text=input_request.prompt,
|
| 272 |
+
priority=priority,
|
| 273 |
+
max_tokens=input_request.output_len,
|
| 274 |
+
)
|
| 275 |
+
output = RequestFuncOutput()
|
| 276 |
+
output.input_request = input_request
|
| 277 |
+
output.prompt_len = input_request.prompt_len
|
| 278 |
+
generated_token_list, ttft, latency = await loop.run_in_executor(
|
| 279 |
+
None, grpc_sync_request, api_url, request
|
| 280 |
+
)
|
| 281 |
+
output.ttft = ttft
|
| 282 |
+
output.latency = latency
|
| 283 |
+
output.generated_token_list = generated_token_list
|
| 284 |
+
output.generated_text = "".join(generated_token_list)
|
| 285 |
+
output.success = True
|
| 286 |
+
if pbar:
|
| 287 |
+
pbar.update(1)
|
| 288 |
+
return output
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
async def benchmark(
|
| 292 |
+
api_url: str,
|
| 293 |
+
tokenizer: Any,
|
| 294 |
+
input_requests: List[InputRequest],
|
| 295 |
+
request_rate: float,
|
| 296 |
+
disable_tqdm: bool,
|
| 297 |
+
session_cache: str,
|
| 298 |
+
priority: int,
|
| 299 |
+
threads: int,
|
| 300 |
+
):
|
| 301 |
+
"""Benchmark the online serving performance."""
|
| 302 |
+
pbar = None if disable_tqdm else tqdm(total=len(input_requests))
|
| 303 |
+
|
| 304 |
+
print(f"Traffic request rate: {request_rate}")
|
| 305 |
+
|
| 306 |
+
benchmark_start_time = time.perf_counter()
|
| 307 |
+
tasks = []
|
| 308 |
+
async for request in get_request(input_requests, request_rate):
|
| 309 |
+
tasks.append(
|
| 310 |
+
asyncio.create_task(
|
| 311 |
+
send_request(
|
| 312 |
+
api_url=api_url,
|
| 313 |
+
input_request=request,
|
| 314 |
+
pbar=pbar,
|
| 315 |
+
session_cache=session_cache,
|
| 316 |
+
priority=priority,
|
| 317 |
+
threads=threads,
|
| 318 |
+
)
|
| 319 |
+
)
|
| 320 |
+
)
|
| 321 |
+
outputs = await asyncio.gather(*tasks)
|
| 322 |
+
|
| 323 |
+
if not disable_tqdm:
|
| 324 |
+
pbar.close()
|
| 325 |
+
|
| 326 |
+
benchmark_duration = time.perf_counter() - benchmark_start_time
|
| 327 |
+
|
| 328 |
+
metrics = calculate_metrics(
|
| 329 |
+
input_requests=input_requests,
|
| 330 |
+
outputs=outputs,
|
| 331 |
+
dur_s=benchmark_duration,
|
| 332 |
+
tokenizer=tokenizer,
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
print(f"Successful requests: {metrics.completed}")
|
| 336 |
+
print(f"Benchmark duration: {benchmark_duration:2f} s")
|
| 337 |
+
print(f"Total input tokens: {metrics.total_input}")
|
| 338 |
+
print(f"Total generated tokens: {metrics.total_output}")
|
| 339 |
+
print(f"Request throughput: {metrics.request_throughput:.2f} requests/s")
|
| 340 |
+
print(f"Input token throughput: {metrics.input_throughput:.2f} tokens/s")
|
| 341 |
+
print(f"Output token throughput: {metrics.output_throughput:.2f} tokens/s")
|
| 342 |
+
print(f"Mean TTFT: {metrics.mean_ttft_ms:.2f} ms")
|
| 343 |
+
print(f"Median TTFT: {metrics.median_ttft_ms:.2f} ms")
|
| 344 |
+
print(f"P99 TTFT: {metrics.p99_ttft_ms:.2f} ms")
|
| 345 |
+
print(f"Mean TPOT: {metrics.mean_tpot_ms:.2f} ms")
|
| 346 |
+
print(f"Median TPOT: {metrics.median_tpot_ms:.2f} ms")
|
| 347 |
+
print(f"P99 TPOT: {metrics.p99_tpot_ms:.2f} ms")
|
| 348 |
+
|
| 349 |
+
result = {
|
| 350 |
+
"duration": benchmark_duration,
|
| 351 |
+
"completed": metrics.completed,
|
| 352 |
+
"total_input_tokens": metrics.total_input,
|
| 353 |
+
"total_output_tokens": metrics.total_output,
|
| 354 |
+
"request_inthroughput": metrics.request_throughput,
|
| 355 |
+
"input_throughput": metrics.input_throughput,
|
| 356 |
+
"output_throughput": metrics.output_throughput,
|
| 357 |
+
"mean_ttft_ms": metrics.mean_ttft_ms,
|
| 358 |
+
"median_ttft_ms": metrics.median_ttft_ms,
|
| 359 |
+
"p99_ttft_ms": metrics.p99_ttft_ms,
|
| 360 |
+
"mean_tpot_ms": metrics.mean_tpot_ms,
|
| 361 |
+
"median_tpot_ms": metrics.median_tpot_ms,
|
| 362 |
+
"p99_tpot_ms": metrics.p99_tpot_ms,
|
| 363 |
+
}
|
| 364 |
+
return result, outputs
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def mock_requests(total_mock_requests: int):
|
| 368 |
+
"""Generates a list of mock requests containing mock data."""
|
| 369 |
+
data = []
|
| 370 |
+
for _ in range(total_mock_requests):
|
| 371 |
+
reqeust = InputRequest()
|
| 372 |
+
reqeust.prompt = f"Prompt {random.randint(1, 1000)}"
|
| 373 |
+
reqeust.prompt_len = random.randint(10, 100)
|
| 374 |
+
reqeust.out = f"Output {random.randint(1, 1000)}"
|
| 375 |
+
reqeust.output_len = random.randint(1, 10)
|
| 376 |
+
data.append(reqeust)
|
| 377 |
+
return data
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def sample_warmup_requests(requests):
|
| 381 |
+
interesting_buckets = [
|
| 382 |
+
0,
|
| 383 |
+
16,
|
| 384 |
+
32,
|
| 385 |
+
64,
|
| 386 |
+
128,
|
| 387 |
+
256,
|
| 388 |
+
512,
|
| 389 |
+
1024,]
|
| 390 |
+
|
| 391 |
+
for start, end in zip(interesting_buckets[:-1], interesting_buckets[1:]):
|
| 392 |
+
for request in requests:
|
| 393 |
+
if start < request.prompt_len <= end:
|
| 394 |
+
yield request
|
| 395 |
+
break
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def main(args: argparse.Namespace):
|
| 399 |
+
print(args)
|
| 400 |
+
random.seed(args.seed)
|
| 401 |
+
np.random.seed(args.seed)
|
| 402 |
+
|
| 403 |
+
model_id = args.model
|
| 404 |
+
tokenizer_id = args.tokenizer
|
| 405 |
+
|
| 406 |
+
api_url = f"{args.server}:{args.port}"
|
| 407 |
+
|
| 408 |
+
tokenizer = get_tokenizer(tokenizer_id)
|
| 409 |
+
if tokenizer == "test" or args.dataset == "test":
|
| 410 |
+
input_requests = mock_requests(args.total_mock_requests) # e.g. [("AB", 2, "AB", 3)]
|
| 411 |
+
else:
|
| 412 |
+
input_requests = sample_requests(args.dataset, args.num_prompts, tokenizer, args.max_output_length)
|
| 413 |
+
|
| 414 |
+
if args.warmup_first:
|
| 415 |
+
print('Warm up start:' )
|
| 416 |
+
warmup_requests = list(sample_warmup_requests(input_requests)) * 2
|
| 417 |
+
benchmark_result, request_outputs = asyncio.run(
|
| 418 |
+
benchmark(
|
| 419 |
+
api_url=api_url,
|
| 420 |
+
tokenizer=tokenizer,
|
| 421 |
+
input_requests=warmup_requests,
|
| 422 |
+
request_rate=args.request_rate,
|
| 423 |
+
disable_tqdm=args.disable_tqdm,
|
| 424 |
+
session_cache=args.session_cache,
|
| 425 |
+
priority=args.priority,
|
| 426 |
+
threads=args.threads,
|
| 427 |
+
)
|
| 428 |
+
)
|
| 429 |
+
print('Warm up done')
|
| 430 |
+
|
| 431 |
+
benchmark_result, request_outputs = asyncio.run(
|
| 432 |
+
benchmark(
|
| 433 |
+
api_url=api_url,
|
| 434 |
+
tokenizer=tokenizer,
|
| 435 |
+
input_requests=input_requests,
|
| 436 |
+
request_rate=args.request_rate,
|
| 437 |
+
disable_tqdm=args.disable_tqdm,
|
| 438 |
+
session_cache=args.session_cache,
|
| 439 |
+
priority=args.priority,
|
| 440 |
+
threads=args.threads,
|
| 441 |
+
)
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
# Save config and results to json
|
| 445 |
+
if args.save_result:
|
| 446 |
+
result_json = {}
|
| 447 |
+
|
| 448 |
+
# Setup
|
| 449 |
+
current_dt = datetime.now().strftime("%Y%m%d-%H%M%S")
|
| 450 |
+
result_json["date"] = current_dt
|
| 451 |
+
result_json["model_id"] = model_id
|
| 452 |
+
result_json["tokenizer_id"] = tokenizer_id
|
| 453 |
+
result_json["num_prompts"] = args.num_prompts
|
| 454 |
+
|
| 455 |
+
# Traffic
|
| 456 |
+
result_json["request_rate"] = (
|
| 457 |
+
args.request_rate if args.request_rate < float("inf") else "inf"
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
# Merge with benchmark result
|
| 461 |
+
result_json = {**result_json, **benchmark_result}
|
| 462 |
+
|
| 463 |
+
# Save to file
|
| 464 |
+
base_model_id = model_id.split("/")[-1]
|
| 465 |
+
file_name = (
|
| 466 |
+
f"JetStream-{args.request_rate}qps-{base_model_id}-{current_dt}.json"
|
| 467 |
+
)
|
| 468 |
+
with open(file_name, "w") as outfile:
|
| 469 |
+
json.dump(result_json, outfile)
|
| 470 |
+
|
| 471 |
+
if args.save_request_outputs:
|
| 472 |
+
file_path = args.request_outputs_file_path
|
| 473 |
+
with open(file_path, "w") as output_file:
|
| 474 |
+
json.dump([output.to_dict() for output in request_outputs], output_file, indent=4)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
if __name__ == "__main__":
|
| 478 |
+
parser = argparse.ArgumentParser(
|
| 479 |
+
description="Benchmark the online serving throughput."
|
| 480 |
+
)
|
| 481 |
+
parser.add_argument(
|
| 482 |
+
"--server",
|
| 483 |
+
type=str,
|
| 484 |
+
default="dns:///[::1]",
|
| 485 |
+
help="Server address.",
|
| 486 |
+
)
|
| 487 |
+
parser.add_argument("--port", type=str, default=9000)
|
| 488 |
+
parser.add_argument(
|
| 489 |
+
"--dataset", type=str, default="test", help="Path to the dataset."
|
| 490 |
+
)
|
| 491 |
+
parser.add_argument(
|
| 492 |
+
"--model",
|
| 493 |
+
type=str,
|
| 494 |
+
default="no_model",
|
| 495 |
+
help=(
|
| 496 |
+
"Name of the model. (it's just used to label the benchmark, the model"
|
| 497 |
+
" config is defined in config_lib, and passed as the server config"
|
| 498 |
+
" flag when we run the JetStream server)"
|
| 499 |
+
),
|
| 500 |
+
)
|
| 501 |
+
parser.add_argument(
|
| 502 |
+
"--tokenizer",
|
| 503 |
+
type=str,
|
| 504 |
+
default="test",
|
| 505 |
+
help=(
|
| 506 |
+
"Name or path of the tokenizer. (For mock model testing, use the"
|
| 507 |
+
" default value)"
|
| 508 |
+
),
|
| 509 |
+
)
|
| 510 |
+
parser.add_argument(
|
| 511 |
+
"--num-prompts",
|
| 512 |
+
type=int,
|
| 513 |
+
default=1000,
|
| 514 |
+
help=(
|
| 515 |
+
"Number of prompts to process. (number of sample requests we randomly"
|
| 516 |
+
" collect from dataset)"
|
| 517 |
+
),
|
| 518 |
+
)
|
| 519 |
+
parser.add_argument(
|
| 520 |
+
"--request-rate",
|
| 521 |
+
type=float,
|
| 522 |
+
default=float("inf"),
|
| 523 |
+
help=(
|
| 524 |
+
"Number of requests per second. If this is inf, "
|
| 525 |
+
"then all the requests are sent at time 0. "
|
| 526 |
+
"Otherwise, we use Poisson process to synthesize "
|
| 527 |
+
"the request arrival times."
|
| 528 |
+
),
|
| 529 |
+
)
|
| 530 |
+
parser.add_argument(
|
| 531 |
+
"--threads",
|
| 532 |
+
type=int,
|
| 533 |
+
default=110,
|
| 534 |
+
help="The maximum number of threads used for request dispatching.",
|
| 535 |
+
)
|
| 536 |
+
parser.add_argument(
|
| 537 |
+
"--total-mock-requests",
|
| 538 |
+
type=int,
|
| 539 |
+
default=150,
|
| 540 |
+
help="The maximum number of mock requests to send for benchmark testing.",
|
| 541 |
+
)
|
| 542 |
+
|
| 543 |
+
parser.add_argument(
|
| 544 |
+
"--max-output-length",
|
| 545 |
+
type=int,
|
| 546 |
+
default=1024,
|
| 547 |
+
help="The maximum output length for reference request.",
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 551 |
+
parser.add_argument(
|
| 552 |
+
"--disable-tqdm",
|
| 553 |
+
action="store_true",
|
| 554 |
+
help="Specify to disable tqdm progress bar.",
|
| 555 |
+
)
|
| 556 |
+
parser.add_argument(
|
| 557 |
+
"--save-result",
|
| 558 |
+
action="store_true",
|
| 559 |
+
help="Specify to save benchmark results to a json file",
|
| 560 |
+
)
|
| 561 |
+
parser.add_argument(
|
| 562 |
+
"--priority",
|
| 563 |
+
type=int,
|
| 564 |
+
default=0,
|
| 565 |
+
help=(
|
| 566 |
+
"Message priority. (currently no business logic implemented, use"
|
| 567 |
+
" default 0)"
|
| 568 |
+
),
|
| 569 |
+
)
|
| 570 |
+
parser.add_argument(
|
| 571 |
+
"--session-cache",
|
| 572 |
+
type=str,
|
| 573 |
+
default="",
|
| 574 |
+
help=(
|
| 575 |
+
"Location of any pre-cached results. (currently _load_cache_history"
|
| 576 |
+
" not implemented, use default empty str)"
|
| 577 |
+
),
|
| 578 |
+
)
|
| 579 |
+
parser.add_argument(
|
| 580 |
+
"--save-request-outputs",
|
| 581 |
+
action="store_true",
|
| 582 |
+
help="Specify to store request outputs into a json file",
|
| 583 |
+
)
|
| 584 |
+
parser.add_argument(
|
| 585 |
+
"--request-outputs-file-path",
|
| 586 |
+
type=str,
|
| 587 |
+
default="/tmp/request-outputs.json",
|
| 588 |
+
help=(
|
| 589 |
+
"File path to store request outputs"
|
| 590 |
+
),
|
| 591 |
+
)
|
| 592 |
+
parser.add_argument(
|
| 593 |
+
"--warmup-first",
|
| 594 |
+
type=bool,
|
| 595 |
+
default=False,
|
| 596 |
+
help=(
|
| 597 |
+
"Whether to send warmup req first"
|
| 598 |
+
),
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
args = parser.parse_args()
|
| 602 |
+
main(args)
|
maxtext-setup/jetstream/benchmarks/eval_accuracy.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import nltk
|
| 3 |
+
import evaluate
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
def postprocess_text(preds, targets):
|
| 9 |
+
preds = [pred.strip() for pred in preds]
|
| 10 |
+
targets = [target.strip() for target in targets]
|
| 11 |
+
|
| 12 |
+
# rougeLSum expects newline after each sentence
|
| 13 |
+
preds = ["\n".join(nltk.sent_tokenize(pred)) for pred in preds]
|
| 14 |
+
targets = ["\n".join(nltk.sent_tokenize(target)) for target in targets]
|
| 15 |
+
|
| 16 |
+
return preds, targets
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def eval_accuracy(request_outputs_dict):
|
| 20 |
+
metric = evaluate.load("rouge")
|
| 21 |
+
nltk.download('punkt')
|
| 22 |
+
preds = []
|
| 23 |
+
targets = []
|
| 24 |
+
|
| 25 |
+
for output in request_outputs_dict:
|
| 26 |
+
preds.append(output["generated_text"])
|
| 27 |
+
targets.append(output["original_output"])
|
| 28 |
+
preds, targets = postprocess_text(preds, targets)
|
| 29 |
+
result = metric.compute(
|
| 30 |
+
predictions=preds, references=targets, use_stemmer=True, use_aggregator=False)
|
| 31 |
+
result = {k: round(np.mean(v) * 100, 4) for k, v in result.items()}
|
| 32 |
+
prediction_lens = [len(pred) for pred in preds]
|
| 33 |
+
result["gen_len"] = np.sum(prediction_lens)
|
| 34 |
+
result["gen_num"] = len(preds)
|
| 35 |
+
print("\nResults\n")
|
| 36 |
+
print(result)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def main(args):
|
| 40 |
+
with open(args.output_path) as f:
|
| 41 |
+
request_outputs_dict = json.load(f)
|
| 42 |
+
|
| 43 |
+
eval_accuracy(request_outputs_dict)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if __name__ == '__main__':
|
| 47 |
+
parser = argparse.ArgumentParser()
|
| 48 |
+
parser.add_argument(
|
| 49 |
+
"--output_path", type=str,
|
| 50 |
+
default="/tmp/request-outputs.json",
|
| 51 |
+
help="File path which has original_output and inference generated_text.")
|
| 52 |
+
|
| 53 |
+
args = parser.parse_args()
|
| 54 |
+
|
| 55 |
+
main(args)
|
maxtext-setup/jetstream/benchmarks/requirements.in
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
nltk
|
| 2 |
+
evaluate
|
| 3 |
+
rouge-score
|
maxtext-setup/jetstream/build/lib/jetstream/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
maxtext-setup/jetstream/build/lib/jetstream/core/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
maxtext-setup/jetstream/build/lib/jetstream/core/config_lib.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Configs of engines for the orchestrator to load."""
|
| 16 |
+
|
| 17 |
+
import dataclasses
|
| 18 |
+
import functools
|
| 19 |
+
import math
|
| 20 |
+
from typing import Any, Callable, List, Tuple, Type
|
| 21 |
+
|
| 22 |
+
from jetstream.engine import engine_api
|
| 23 |
+
from jetstream.engine import mock_engine
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
Devices = Any
|
| 27 |
+
|
| 28 |
+
CreateEngineFn = Callable[[Devices], engine_api.Engine]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclasses.dataclass
|
| 32 |
+
class ServerConfig:
|
| 33 |
+
"""Configs for slices to put engines on."""
|
| 34 |
+
|
| 35 |
+
prefill_slices: Tuple[str, ...] = ()
|
| 36 |
+
generate_slices: Tuple[str, ...] = ()
|
| 37 |
+
interleaved_slices: Tuple[str, ...] = ()
|
| 38 |
+
prefill_engine_create_fns: Tuple[CreateEngineFn, ...] = ()
|
| 39 |
+
generate_engine_create_fns: Tuple[CreateEngineFn, ...] = ()
|
| 40 |
+
interleaved_engine_create_fns: Tuple[CreateEngineFn, ...] = ()
|
| 41 |
+
|
| 42 |
+
def get_slices_to_launch(self: 'ServerConfig') -> str:
|
| 43 |
+
"""Used when launching this config via xm config."""
|
| 44 |
+
return ','.join(
|
| 45 |
+
self.prefill_slices + self.generate_slices + self.interleaved_slices
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@dataclasses.dataclass
|
| 50 |
+
class InstantiatedEngines:
|
| 51 |
+
prefill_engines: List[engine_api.Engine]
|
| 52 |
+
generate_engines: List[engine_api.Engine]
|
| 53 |
+
interleaved_engines: List[engine_api.Engine]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼#
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def get_test_engine(devices: Devices, weight: int) -> engine_api.Engine:
|
| 60 |
+
del devices
|
| 61 |
+
return mock_engine.TestEngine(
|
| 62 |
+
batch_size=8,
|
| 63 |
+
cache_length=32,
|
| 64 |
+
weight=weight,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@dataclasses.dataclass
|
| 69 |
+
class CPUTestServer(ServerConfig):
|
| 70 |
+
prefill_slices = ('cpu=1',)
|
| 71 |
+
generate_slices = ('cpu=1',)
|
| 72 |
+
prefill_engine_create_fns = (functools.partial(get_test_engine, weight=2),)
|
| 73 |
+
generate_engine_create_fns = (functools.partial(get_test_engine, weight=4),)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@dataclasses.dataclass
|
| 77 |
+
class InterleavedCPUTestServer(ServerConfig):
|
| 78 |
+
interleaved_slices = ('cpu=1',)
|
| 79 |
+
interleaved_engine_create_fns = (
|
| 80 |
+
functools.partial(get_test_engine, weight=2),
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼#
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def slice_to_num_chips(s: str) -> int:
|
| 88 |
+
"""Converts a TPU spec like v5e=4x2 to the number of chips, 8."""
|
| 89 |
+
# Account for the case where it is written 'v5e:4x2'.
|
| 90 |
+
delim = '=' if '=' in s else ':'
|
| 91 |
+
i = math.prod([int(c) for c in s.split(delim)[1].split('x')])
|
| 92 |
+
return i
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _split_devices_by_slices(
|
| 96 |
+
devices: list[Devices], slices: list[int]
|
| 97 |
+
) -> List[List[Devices]]:
|
| 98 |
+
"""Converts an ordered list of devices into slices."""
|
| 99 |
+
assert sum(slices) == len(devices), f'{sum(slices)} != {len(devices)}'
|
| 100 |
+
cumsum = 0
|
| 101 |
+
slice_split_devices = []
|
| 102 |
+
for sl in slices:
|
| 103 |
+
slice_split_devices.append(devices[cumsum : cumsum + sl])
|
| 104 |
+
cumsum += sl
|
| 105 |
+
return slice_split_devices
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def get_engines(
|
| 109 |
+
server_config: Type[ServerConfig], devices: List[Devices]
|
| 110 |
+
) -> InstantiatedEngines:
|
| 111 |
+
"""Processes config to get the appropriate engines.
|
| 112 |
+
|
| 113 |
+
Args:
|
| 114 |
+
server_config: ServerConfig.
|
| 115 |
+
devices: Device objects.
|
| 116 |
+
|
| 117 |
+
Returns:
|
| 118 |
+
Instantiated engines!
|
| 119 |
+
|
| 120 |
+
Devices are popped in order!
|
| 121 |
+
"""
|
| 122 |
+
# Now, we need to split devices by slice due to TPU backend config.
|
| 123 |
+
slices: list[int] = [
|
| 124 |
+
slice_to_num_chips(s)
|
| 125 |
+
for s in list(server_config.prefill_slices)
|
| 126 |
+
+ list(server_config.generate_slices)
|
| 127 |
+
+ list(server_config.interleaved_slices)
|
| 128 |
+
]
|
| 129 |
+
if sum(slices) != len(devices):
|
| 130 |
+
raise ValueError(
|
| 131 |
+
f'The number of available devices ({len(devices)}) do not match the '
|
| 132 |
+
f'expected number of devices on all the slices ({sum(slices)}) '
|
| 133 |
+
'specified in the server_config:\n'
|
| 134 |
+
f'{server_config.prefill_slices=}\n'
|
| 135 |
+
f'{server_config.generate_slices=}\n'
|
| 136 |
+
f'{server_config.interleaved_slices=}\n'
|
| 137 |
+
)
|
| 138 |
+
# e.g. [[tpu_0], [tpu_1]] corresponding to prefill: v5e=1x1
|
| 139 |
+
# generate = v5e=1x1; or [[tpu_0, tpu_1, tpu_2, tpu_3]] corresponding to
|
| 140 |
+
# interleaved: v5e=2x2
|
| 141 |
+
split_devices = _split_devices_by_slices(devices, slices)
|
| 142 |
+
prefill_engines = [
|
| 143 |
+
e(split_devices.pop(0)) for e in server_config.prefill_engine_create_fns
|
| 144 |
+
]
|
| 145 |
+
generate_engines = [
|
| 146 |
+
e(split_devices.pop(0)) for e in server_config.generate_engine_create_fns
|
| 147 |
+
]
|
| 148 |
+
# These share chips and weights for prefill and generation.
|
| 149 |
+
interleaved_engines = [
|
| 150 |
+
e(split_devices.pop(0))
|
| 151 |
+
for e in server_config.interleaved_engine_create_fns
|
| 152 |
+
]
|
| 153 |
+
return InstantiatedEngines(
|
| 154 |
+
prefill_engines, generate_engines, interleaved_engines
|
| 155 |
+
)
|
maxtext-setup/jetstream/build/lib/jetstream/core/implementations/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/config.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Config for mock."""
|
| 16 |
+
|
| 17 |
+
from typing import Type
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
from jetstream.core import config_lib
|
| 21 |
+
|
| 22 |
+
def get_server_config(config_str: str) -> Type[config_lib.ServerConfig]:
|
| 23 |
+
match config_str:
|
| 24 |
+
case 'InterleavedCPUTestServer':
|
| 25 |
+
server_config = config_lib.InterleavedCPUTestServer
|
| 26 |
+
case 'CPUTestServer':
|
| 27 |
+
server_config = config_lib.CPUTestServer
|
| 28 |
+
case _:
|
| 29 |
+
raise NotImplementedError
|
| 30 |
+
return server_config
|
maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/server.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Runs a mock server."""
|
| 16 |
+
|
| 17 |
+
from typing import Sequence
|
| 18 |
+
|
| 19 |
+
from absl import app
|
| 20 |
+
from absl import flags
|
| 21 |
+
|
| 22 |
+
from jetstream.core.implementations.mock import config as mock_config
|
| 23 |
+
from jetstream.core import server_lib
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
_PORT = flags.DEFINE_integer('port', 9000, 'port to listen on')
|
| 27 |
+
_CONFIG = flags.DEFINE_string(
|
| 28 |
+
'config',
|
| 29 |
+
'InterleavedCPUTestServer',
|
| 30 |
+
'available servers',
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
def main(argv: Sequence[str]):
|
| 34 |
+
del argv
|
| 35 |
+
# No devices for local cpu test. A None for prefill and a None for generate.
|
| 36 |
+
devices = server_lib.get_devices()
|
| 37 |
+
server_config = mock_config.get_server_config(_CONFIG.value)
|
| 38 |
+
# We separate credential from run so that we can unit test it with local credentials.
|
| 39 |
+
# TODO: Add grpc credentials for OSS.
|
| 40 |
+
jetstream_server = server_lib.run(
|
| 41 |
+
port=_PORT.value,
|
| 42 |
+
config=server_config,
|
| 43 |
+
devices=devices,
|
| 44 |
+
)
|
| 45 |
+
jetstream_server.wait_for_termination()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if __name__ == '__main__':
|
| 49 |
+
app.run(main)
|
maxtext-setup/jetstream/build/lib/jetstream/core/orchestrator.py
ADDED
|
@@ -0,0 +1,651 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Orchestrates the engines for the inference workflow with performance optimization.
|
| 16 |
+
|
| 17 |
+
1. A client sends a DecodeRequest via gRPC to the server, an 'LLMOrchestrator'.
|
| 18 |
+
2. This gets wrapped as an 'ActiveRequest' inside the orchestrator, with a
|
| 19 |
+
'return_channel' queue as a place that output tokens can be placed.
|
| 20 |
+
- The ActiveRequest is placed on the 'prefill_queue'.
|
| 21 |
+
- A while loop runs continuously, yielding any tokens placed on the return
|
| 22 |
+
channel until an end condition is met (EOS token or max tokens).
|
| 23 |
+
3. There is a prefill_thread per prefill_engine, each of which runs on a
|
| 24 |
+
distinct prefill_slice.
|
| 25 |
+
4. There is a generate_thread per generate_engine, each of which runs on a
|
| 26 |
+
distinct generate_slice.
|
| 27 |
+
5. Within a prefill thread:
|
| 28 |
+
- It attempts to pop ActiveRequests off the prefill_queue.
|
| 29 |
+
- It tokenizes the request.
|
| 30 |
+
- When successful, it performs a prefill operation, transfers the kv cache
|
| 31 |
+
to the generation slice and pops this information (still wrapped in the
|
| 32 |
+
same ActiveRequest) onto the generation queue.
|
| 33 |
+
6. Within a generation thread:
|
| 34 |
+
- There is a queue of integers representing 'available slots'.
|
| 35 |
+
- It checks if there is something on both the slots_queue and generation_
|
| 36 |
+
queue.
|
| 37 |
+
- If so, the kv_cache associated with that request into the decoding state
|
| 38 |
+
of the generation loop at the relevant slot.
|
| 39 |
+
- Regardless, it performs a step.
|
| 40 |
+
- It takes the sampled tokens, and places them on a 'detokenizing_queue'.
|
| 41 |
+
7. Within the detokenizing thread:
|
| 42 |
+
- Tokens are detokenized for every 'slot' in a given set of sampled tokens.
|
| 43 |
+
- When an end condition is met, the 'slot' integer is returned to the
|
| 44 |
+
respective generation queue.
|
| 45 |
+
- This does mean that a single generation step may run after detokenizing
|
| 46 |
+
indicates that row is no longer valid (if the detokenizing is running behind
|
| 47 |
+
generation steps), this is fine as it avoids detokenizing being blocking of
|
| 48 |
+
the generate thread.
|
| 49 |
+
|
| 50 |
+
If you haven't worked with concurrency in python before - queues are thread-safe
|
| 51 |
+
by default, so we can happily use them to transfer pointers to data between
|
| 52 |
+
different processes. The structure of this server is simple as a result - a
|
| 53 |
+
thread for each thing we might want to do (prefill, transfer, generate,
|
| 54 |
+
detokenize), and corresponding queues that an active request is passed between.
|
| 55 |
+
The same goes for the 'return_channel' of the request itself, where we can just
|
| 56 |
+
pop tokens once they are done and try to pop them back to transmit them over
|
| 57 |
+
grpc.
|
| 58 |
+
It is literally queues all the way down! :)
|
| 59 |
+
The primary concern is GIL contention between threads, which is why we block
|
| 60 |
+
on queues that don't have an ongoing activity (i.e. everything but the
|
| 61 |
+
generation queue) because we don't control to go back to those queues until
|
| 62 |
+
necessary. Blocking means that the GIL doesn't switch back to that thread,
|
| 63 |
+
wheras continual queue get operations 'chop' control and mean that we do not
|
| 64 |
+
achieve good throughput. This is okay on the prefill/transfer/detokenisation
|
| 65 |
+
threads because we don't need to do anything other than react to the presence
|
| 66 |
+
of items on these queues, wheras the generation thread needs to also run a
|
| 67 |
+
step - so it cannot block until it has new things to insert.
|
| 68 |
+
|
| 69 |
+
## Testing
|
| 70 |
+
This server is intended to be easy to locally test.
|
| 71 |
+
|
| 72 |
+
Either use :orchestrator test, which tests the multi-threading components,
|
| 73 |
+
:server_test, which extends this to test grpc_components, or run it locally
|
| 74 |
+
to debug hangs due to bugs in threads (it is easier to debug with live logs).
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
import dataclasses
|
| 78 |
+
import functools
|
| 79 |
+
import itertools
|
| 80 |
+
import logging
|
| 81 |
+
import os
|
| 82 |
+
import queue
|
| 83 |
+
import signal
|
| 84 |
+
import sys
|
| 85 |
+
import threading
|
| 86 |
+
import time
|
| 87 |
+
import traceback
|
| 88 |
+
import json
|
| 89 |
+
from typing import Any, Iterable, Optional, Union
|
| 90 |
+
|
| 91 |
+
import grpc
|
| 92 |
+
import jax
|
| 93 |
+
from jetstream.core.proto import jetstream_pb2
|
| 94 |
+
from jetstream.core.proto import jetstream_pb2_grpc
|
| 95 |
+
from jetstream.engine import engine_api
|
| 96 |
+
from jetstream.engine import token_utils
|
| 97 |
+
import numpy as np
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
root = logging.getLogger()
|
| 101 |
+
root.setLevel(logging.DEBUG)
|
| 102 |
+
|
| 103 |
+
handler = logging.StreamHandler(sys.stdout)
|
| 104 |
+
handler.setLevel(logging.DEBUG)
|
| 105 |
+
formatter = logging.Formatter(
|
| 106 |
+
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 107 |
+
)
|
| 108 |
+
handler.setFormatter(formatter)
|
| 109 |
+
root.addHandler(handler)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def delete_pytree(p):
|
| 113 |
+
def delete_leaf(leaf):
|
| 114 |
+
if isinstance(leaf, jax.Array):
|
| 115 |
+
leaf.delete()
|
| 116 |
+
del leaf
|
| 117 |
+
|
| 118 |
+
jax.tree_map(delete_leaf, p)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@dataclasses.dataclass
|
| 122 |
+
class ActiveRequest:
|
| 123 |
+
"""Current state of the driver."""
|
| 124 |
+
|
| 125 |
+
#################### Information relevant for generation #####################
|
| 126 |
+
max_tokens: int
|
| 127 |
+
vocab: str
|
| 128 |
+
# [num_samples,] which corresponds to whether each sample is complete for the
|
| 129 |
+
# requests.
|
| 130 |
+
complete: Optional[np.ndarray] = None
|
| 131 |
+
prefill_result: Any = None
|
| 132 |
+
#################### Information relevant for prefill ########################
|
| 133 |
+
history_path: Optional[str] = None
|
| 134 |
+
prefill_text: Optional[str] = None
|
| 135 |
+
################## Information relevant for detokenisation ###################
|
| 136 |
+
# Which generate step this was added at.
|
| 137 |
+
generate_timestep_added: Optional[int] = None
|
| 138 |
+
# We keep prefill and decode information together in the same object so that
|
| 139 |
+
# there is less indirection about where this return channel is.
|
| 140 |
+
# The return channel returns a list of strings, one per sample for that query.
|
| 141 |
+
return_channel: queue.Queue[list[str]] = dataclasses.field(
|
| 142 |
+
default_factory=queue.Queue
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
def next(self: 'ActiveRequest'):
|
| 146 |
+
"""Blocks until the next token is available, call from RPC threads."""
|
| 147 |
+
return self.return_channel.get()
|
| 148 |
+
|
| 149 |
+
def enqueue_tokens(self, generated_tokens: list[str]):
|
| 150 |
+
"""Records information about the step.
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
generated_tokens: One token to put into the return channel
|
| 154 |
+
|
| 155 |
+
This should be called only from within the Drivers background thread.
|
| 156 |
+
"""
|
| 157 |
+
self.return_channel.put(generated_tokens)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class JetThread(threading.Thread):
|
| 161 |
+
"""Thread that kills the program if it fails.
|
| 162 |
+
|
| 163 |
+
If a driver thread goes down, we can't operate.
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
def run(self):
|
| 167 |
+
try:
|
| 168 |
+
super().run()
|
| 169 |
+
except Exception as e: # pylint: disable=broad-exception-caught
|
| 170 |
+
print(f'Thread {self.name} encountered an error: {e}')
|
| 171 |
+
traceback.print_exc()
|
| 172 |
+
os.kill(os.getpid(), signal.SIGKILL)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _abort_or_raise(
|
| 176 |
+
context: grpc.ServicerContext | None, code: grpc.StatusCode, details: str
|
| 177 |
+
):
|
| 178 |
+
"""Safely aborts a gRPC context if available, or raises an Exception."""
|
| 179 |
+
if context is None:
|
| 180 |
+
raise RuntimeError(details)
|
| 181 |
+
|
| 182 |
+
context.abort(code, details)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
class Driver:
|
| 186 |
+
"""Drives the engines."""
|
| 187 |
+
|
| 188 |
+
_prefill_engines: list[engine_api.Engine]
|
| 189 |
+
_generate_engines: list[engine_api.Engine]
|
| 190 |
+
# Allows us to pre-load the params, primarily so that we can iterate quickly
|
| 191 |
+
# on the driver in colab without reloading weights.
|
| 192 |
+
_prefill_params: Optional[dict[int, Any]] = {}
|
| 193 |
+
_generate_params: Optional[dict[int, Any]] = {}
|
| 194 |
+
# Stage 1
|
| 195 |
+
_prefill_backlog: queue.Queue[ActiveRequest | None]
|
| 196 |
+
# Stage 2
|
| 197 |
+
# We keep this as a dict to avoid a possibly expensive object comparison
|
| 198 |
+
# when logging the index of the generate engine we send a prefill result
|
| 199 |
+
# to, it allows us to natively have the index from the min operation, rather
|
| 200 |
+
# than have to call .index()
|
| 201 |
+
_generate_backlogs: dict[int, queue.Queue[ActiveRequest | None]] = {}
|
| 202 |
+
# Stage 3
|
| 203 |
+
# This can be a list because we can pass it as an arg to generate and
|
| 204 |
+
# detokenize threads. It is a list of tokens to be detokenized.
|
| 205 |
+
_detokenize_backlogs: list[queue.Queue[engine_api.ResultTokens]] = []
|
| 206 |
+
_generate_slots: list[queue.Queue[int]] = []
|
| 207 |
+
_active_requests: list[queue.Queue[tuple[int, ActiveRequest | None]]] = []
|
| 208 |
+
|
| 209 |
+
def __init__(
|
| 210 |
+
self,
|
| 211 |
+
prefill_engines=None,
|
| 212 |
+
generate_engines=None,
|
| 213 |
+
prefill_params=None,
|
| 214 |
+
generate_params=None,
|
| 215 |
+
):
|
| 216 |
+
logging.info(
|
| 217 |
+
'Initialising driver with %d prefill engines and %d generate engines.',
|
| 218 |
+
len(prefill_engines),
|
| 219 |
+
len(generate_engines),
|
| 220 |
+
)
|
| 221 |
+
self._prefill_engines = prefill_engines
|
| 222 |
+
self._generate_engines = generate_engines
|
| 223 |
+
self._prefill_params = prefill_params if prefill_params else {}
|
| 224 |
+
self._generate_params = generate_params if generate_params else {}
|
| 225 |
+
# Stages 1-4 represent the life cycle of a request.
|
| 226 |
+
# Stage 1
|
| 227 |
+
# At first, a request is placed here in order to get prefilled.
|
| 228 |
+
self._prefill_backlog = queue.Queue()
|
| 229 |
+
# Stage 2
|
| 230 |
+
# Each generate engine accesses its own generate backlog.
|
| 231 |
+
self._generate_backlogs = {
|
| 232 |
+
idx: queue.Queue() for idx, _ in enumerate(generate_engines)
|
| 233 |
+
}
|
| 234 |
+
# Stage 3
|
| 235 |
+
# After generation, ActiveRequests are placed on the detokenization backlog
|
| 236 |
+
# for tokens to be sent into each ActiveRequest's return channel.
|
| 237 |
+
# We have one of these per generate engine to simplify the logic keeping
|
| 238 |
+
# track of which generation engine to replace slots on.
|
| 239 |
+
# This is a queue of either - tuple[int, ActiveRequest] which represents our
|
| 240 |
+
# active requests, or tuple[int, sample_tokens]. We combine these into one
|
| 241 |
+
# queue because it allows us to be somewhat clever with how we do
|
| 242 |
+
# detokenization.
|
| 243 |
+
# If the detokenization receives an (int, ActiveRequest) this signifies
|
| 244 |
+
# that slot int should from now be placing tokens in the return channel of
|
| 245 |
+
# the ActiveRequest.
|
| 246 |
+
# If it receives (int, sample_tokens) then it actually
|
| 247 |
+
# does a detokenisation for any slots which have previously been set active
|
| 248 |
+
# via the previous kind of object, and the int is used to log which step
|
| 249 |
+
# the tokens were created at. By having them in one queue we prevent
|
| 250 |
+
# the possibility of race conditions where a slot is made live before the
|
| 251 |
+
# tokens are ready and it receives tokens from a different sequence,
|
| 252 |
+
# or tokens detokenized before the relevant slot is live.
|
| 253 |
+
self._detokenize_backlogs = [queue.Queue() for _ in generate_engines]
|
| 254 |
+
# Finally we have a queue that doesn't represent a stage, but tracks the
|
| 255 |
+
# internal status of a request within the generation loop.
|
| 256 |
+
# a) A queue of integers representing available 'slots' in the decode
|
| 257 |
+
# operation. I.e. potentially available rows in the batch and/or
|
| 258 |
+
# microbatch. When we want to insert a prefill result, we pop an integer
|
| 259 |
+
# to insert at. When this is empty, it means all slots are full.
|
| 260 |
+
|
| 261 |
+
# Construct a)
|
| 262 |
+
self._generate_slots = [queue.Queue() for _ in generate_engines]
|
| 263 |
+
_ = [
|
| 264 |
+
[
|
| 265 |
+
self._generate_slots[idx].put(i)
|
| 266 |
+
for i in range(engine.max_concurrent_decodes)
|
| 267 |
+
]
|
| 268 |
+
for idx, engine in enumerate(generate_engines)
|
| 269 |
+
]
|
| 270 |
+
|
| 271 |
+
# Kick off all our threads
|
| 272 |
+
self._prefill_threads = [
|
| 273 |
+
JetThread(
|
| 274 |
+
target=functools.partial(self._prefill_thread, idx, engine),
|
| 275 |
+
name=f'prefill-{idx}',
|
| 276 |
+
)
|
| 277 |
+
for idx, engine in enumerate(self._prefill_engines)
|
| 278 |
+
]
|
| 279 |
+
self._generate_threads = [
|
| 280 |
+
JetThread(
|
| 281 |
+
target=functools.partial(
|
| 282 |
+
self._generate_thread,
|
| 283 |
+
idx,
|
| 284 |
+
engine,
|
| 285 |
+
self._generate_slots[idx],
|
| 286 |
+
self._detokenize_backlogs[idx],
|
| 287 |
+
),
|
| 288 |
+
name=f'generate-{idx}',
|
| 289 |
+
)
|
| 290 |
+
for idx, engine in enumerate(self._generate_engines)
|
| 291 |
+
]
|
| 292 |
+
# Construct b)
|
| 293 |
+
self.detokenize_threads = [
|
| 294 |
+
JetThread(
|
| 295 |
+
target=functools.partial(
|
| 296 |
+
self._detokenize_thread,
|
| 297 |
+
idx,
|
| 298 |
+
engine,
|
| 299 |
+
self._generate_slots[idx],
|
| 300 |
+
self._detokenize_backlogs[idx],
|
| 301 |
+
),
|
| 302 |
+
name=f'detokenize-{idx}',
|
| 303 |
+
)
|
| 304 |
+
for idx, engine in enumerate(self._generate_engines)
|
| 305 |
+
]
|
| 306 |
+
self._all_threads = list(
|
| 307 |
+
itertools.chain(
|
| 308 |
+
self._prefill_threads,
|
| 309 |
+
self._generate_threads,
|
| 310 |
+
self.detokenize_threads,
|
| 311 |
+
)
|
| 312 |
+
)
|
| 313 |
+
self.live = True
|
| 314 |
+
# Kick off all threads
|
| 315 |
+
for t in self._all_threads:
|
| 316 |
+
t.start()
|
| 317 |
+
|
| 318 |
+
def stop(self):
|
| 319 |
+
"""Stops the driver and all background threads."""
|
| 320 |
+
# Signal to all threads that they should stop.
|
| 321 |
+
self.live = False
|
| 322 |
+
|
| 323 |
+
all_backlogs = list(
|
| 324 |
+
itertools.chain(
|
| 325 |
+
[self._prefill_backlog],
|
| 326 |
+
self._generate_backlogs.values(),
|
| 327 |
+
self._detokenize_backlogs,
|
| 328 |
+
)
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
while any(t.is_alive() for t in self._all_threads):
|
| 332 |
+
# Empty all backlogs and mark any remaining requests as cancelled.
|
| 333 |
+
for q in all_backlogs:
|
| 334 |
+
while True:
|
| 335 |
+
try:
|
| 336 |
+
r = q.get_nowait()
|
| 337 |
+
if r is None:
|
| 338 |
+
continue
|
| 339 |
+
elif isinstance(r, ActiveRequest):
|
| 340 |
+
r.return_channel = None
|
| 341 |
+
else: # detokenize backlog
|
| 342 |
+
_, r = r
|
| 343 |
+
if isinstance(r, ActiveRequest):
|
| 344 |
+
r.return_channel = None
|
| 345 |
+
except queue.Empty:
|
| 346 |
+
break
|
| 347 |
+
|
| 348 |
+
# Put sentinels to unblock threads.
|
| 349 |
+
for q in all_backlogs:
|
| 350 |
+
try:
|
| 351 |
+
q.put_nowait(None)
|
| 352 |
+
except queue.Full:
|
| 353 |
+
pass
|
| 354 |
+
|
| 355 |
+
# Wait for all threads to stop.
|
| 356 |
+
for t in self._all_threads:
|
| 357 |
+
t.join()
|
| 358 |
+
|
| 359 |
+
def get_total_concurrent_requests(self) -> int:
|
| 360 |
+
"""Returns the total number of concurrent requests the driver can service."""
|
| 361 |
+
# We don't support filling all backlogs at once because it can cause GIL
|
| 362 |
+
# contention.
|
| 363 |
+
total_max_concurrent_decodes = sum(
|
| 364 |
+
[e.max_concurrent_decodes for e in self._generate_engines]
|
| 365 |
+
)
|
| 366 |
+
return total_max_concurrent_decodes
|
| 367 |
+
|
| 368 |
+
def place_request_on_prefill_queue(self, request: ActiveRequest):
|
| 369 |
+
"""Used to place new requests for prefilling and generation."""
|
| 370 |
+
self._prefill_backlog.put(request)
|
| 371 |
+
|
| 372 |
+
def _load_cache_history(self, path: str) -> Union[None, Any]:
|
| 373 |
+
"""Loads previous kv cache for a longer conversation."""
|
| 374 |
+
if path:
|
| 375 |
+
raise NotImplementedError
|
| 376 |
+
else:
|
| 377 |
+
return None
|
| 378 |
+
|
| 379 |
+
def _prefill_thread(
|
| 380 |
+
self,
|
| 381 |
+
idx: int,
|
| 382 |
+
prefill_engine: engine_api.Engine,
|
| 383 |
+
generate_backpressure: int = 3,
|
| 384 |
+
):
|
| 385 |
+
"""Thread which runs in the background performing prefills."""
|
| 386 |
+
logging.info('---------Spinning up prefill thread %d.---------', idx)
|
| 387 |
+
prefill_params = self._prefill_params[idx]
|
| 388 |
+
metadata = prefill_engine.get_tokenizer()
|
| 389 |
+
vocab = token_utils.load_vocab(metadata.path, metadata.extra_ids)
|
| 390 |
+
logging.info('---------Prefill params %d loaded.---------', idx)
|
| 391 |
+
|
| 392 |
+
while self.live:
|
| 393 |
+
# We don't want to keep lots of kv caches live in memory on the prefill
|
| 394 |
+
# slice that aren't about to be sent over to a generation slice.
|
| 395 |
+
if self._generate_backlogs[idx].qsize() < generate_backpressure:
|
| 396 |
+
# Check if there is anything on the prefill backlog, pop if so.
|
| 397 |
+
try:
|
| 398 |
+
request = self._prefill_backlog.get(block=True)
|
| 399 |
+
if request is None:
|
| 400 |
+
break
|
| 401 |
+
tempbos_id = request.vocab['bos_id'] if 'bos_id' in request.vocab else vocab.bos_id
|
| 402 |
+
tempeos_id = request.vocab['eos_id'] if 'eos_id' in request.vocab else vocab.eos_id
|
| 403 |
+
temppad_id = request.vocab['pad_id'] if 'pad_id' in request.vocab else vocab.pad_id
|
| 404 |
+
|
| 405 |
+
# TODO: Implement hot/cold cache for history.
|
| 406 |
+
history = self._load_cache_history(request.history_path) # pylint: disable = assignment-from-none
|
| 407 |
+
# Tokenize, and introduce a leading dimension
|
| 408 |
+
is_bos = not bool(request.history_path)
|
| 409 |
+
logging.info(
|
| 410 |
+
'Prefilling on prefill engine %d : prefill queue size, %d,'
|
| 411 |
+
' is_bos: %s, history: %s',
|
| 412 |
+
idx,
|
| 413 |
+
self._prefill_backlog.qsize(),
|
| 414 |
+
is_bos,
|
| 415 |
+
request.history_path,
|
| 416 |
+
) # pylint: disable = line-too-long
|
| 417 |
+
padded_tokens, true_length = token_utils.tokenize_and_pad(
|
| 418 |
+
request.prefill_text,
|
| 419 |
+
vocab,
|
| 420 |
+
is_bos=is_bos,
|
| 421 |
+
eos_id = tempeos_id,
|
| 422 |
+
pad_id = temppad_id,
|
| 423 |
+
bos_id = tempbos_id,
|
| 424 |
+
max_prefill_length=prefill_engine.max_prefill_length,
|
| 425 |
+
)
|
| 426 |
+
# Compute new kv cache for the prefill_text, conditional on
|
| 427 |
+
# history.
|
| 428 |
+
prefill_result = prefill_engine.prefill(
|
| 429 |
+
params=prefill_params,
|
| 430 |
+
existing_prefix=history,
|
| 431 |
+
padded_tokens=padded_tokens,
|
| 432 |
+
true_length=true_length,
|
| 433 |
+
)
|
| 434 |
+
request.prefill_result = prefill_result
|
| 435 |
+
# Once prefill is complete, place it on the generation queue.
|
| 436 |
+
self._generate_backlogs[idx].put(request)
|
| 437 |
+
logging.info(
|
| 438 |
+
'Placed request on the generate queue,'
|
| 439 |
+
f' {self._generate_backlogs[idx].qsize()=}'
|
| 440 |
+
)
|
| 441 |
+
except queue.Empty:
|
| 442 |
+
# Otherwise, don't do anything!
|
| 443 |
+
pass
|
| 444 |
+
|
| 445 |
+
def _generate_thread(
|
| 446 |
+
self,
|
| 447 |
+
idx: int,
|
| 448 |
+
generate_engine: engine_api.Engine,
|
| 449 |
+
my_slots: queue.Queue[int],
|
| 450 |
+
my_detokenize_backlog: queue.Queue[tuple[int, engine_api.ResultTokens]],
|
| 451 |
+
backpressure: int = 3,
|
| 452 |
+
):
|
| 453 |
+
"""Step token generation and insert prefills from backlog.
|
| 454 |
+
|
| 455 |
+
Args:
|
| 456 |
+
idx: Idx corresponding to which generation engine idx this is.
|
| 457 |
+
generate_engine: The generate engine corresponding to this thread.
|
| 458 |
+
my_slots: Integers representing free my_slots.
|
| 459 |
+
my_detokenize_backlog: Detokenize backlog for this generate engine.
|
| 460 |
+
backpressure: How many steps we can queue up before pausing, allows us to
|
| 461 |
+
hide dispatch times because jit calls are dispatched one after another.
|
| 462 |
+
We have this in the first place because we don't want to enqueue
|
| 463 |
+
thousands of steps.
|
| 464 |
+
"""
|
| 465 |
+
logging.info('---------Spinning up generate thread %d.---------', idx)
|
| 466 |
+
# Keep track of what step tokens were generated at.
|
| 467 |
+
generate_timestep = 0
|
| 468 |
+
# State to store things like running kv cache in.
|
| 469 |
+
decode_state = generate_engine.init_decode_state()
|
| 470 |
+
generate_params = self._generate_params[idx]
|
| 471 |
+
logging.info('---------Generate params %d loaded.---------', idx)
|
| 472 |
+
time_of_last_generate = time.time()
|
| 473 |
+
time_of_last_print = time.time()
|
| 474 |
+
while self.live:
|
| 475 |
+
if (time.time() - time_of_last_print) > 1:
|
| 476 |
+
logging.info(
|
| 477 |
+
'Generate thread making a decision with:'
|
| 478 |
+
f' prefill_backlog={self._prefill_backlog.qsize()} generate_free_slots={my_slots.qsize()}'
|
| 479 |
+
)
|
| 480 |
+
time_of_last_print = time.time()
|
| 481 |
+
# Check if there are any free my_slots.
|
| 482 |
+
if not my_slots.empty() and not self._generate_backlogs[idx].empty():
|
| 483 |
+
# Only get requests from the backlog corresponding to this engine.
|
| 484 |
+
new_request = self._generate_backlogs[idx].get()
|
| 485 |
+
if new_request is None:
|
| 486 |
+
break
|
| 487 |
+
slot = my_slots.get()
|
| 488 |
+
logging.info(
|
| 489 |
+
'Generate slice %d slot %d step %d',
|
| 490 |
+
idx,
|
| 491 |
+
slot,
|
| 492 |
+
generate_timestep,
|
| 493 |
+
)
|
| 494 |
+
decode_state = generate_engine.insert(
|
| 495 |
+
new_request.prefill_result, decode_state, slot=slot
|
| 496 |
+
)
|
| 497 |
+
delete_pytree(new_request.prefill_result)
|
| 498 |
+
new_request.generate_timestep_added = generate_timestep
|
| 499 |
+
new_request.complete = np.zeros(
|
| 500 |
+
(generate_engine.samples_per_slot,), dtype=np.bool_
|
| 501 |
+
)
|
| 502 |
+
my_detokenize_backlog.put((slot, new_request))
|
| 503 |
+
|
| 504 |
+
if my_detokenize_backlog.qsize() < backpressure:
|
| 505 |
+
decode_state, sampled_tokens = generate_engine.generate(
|
| 506 |
+
generate_params, decode_state
|
| 507 |
+
)
|
| 508 |
+
sampled_tokens.copy_to_host_async()
|
| 509 |
+
my_detokenize_backlog.put((generate_timestep, sampled_tokens))
|
| 510 |
+
generate_timestep += 1
|
| 511 |
+
logging.info(
|
| 512 |
+
'Generate engine %d step %d - slots free : %d / %d, took %.2fms',
|
| 513 |
+
idx,
|
| 514 |
+
generate_timestep,
|
| 515 |
+
my_slots.qsize(),
|
| 516 |
+
generate_engine.max_concurrent_decodes,
|
| 517 |
+
(time.time() - time_of_last_generate) * 10**3,
|
| 518 |
+
)
|
| 519 |
+
time_of_last_generate = time.time()
|
| 520 |
+
|
| 521 |
+
def _detokenize_thread(
|
| 522 |
+
self,
|
| 523 |
+
idx: int,
|
| 524 |
+
generate_engine: engine_api.Engine,
|
| 525 |
+
my_slots: queue.Queue[int],
|
| 526 |
+
my_detokenize_backlog: queue.Queue[
|
| 527 |
+
Union[tuple[int, engine_api.ResultTokens], tuple[int, ActiveRequest]]
|
| 528 |
+
],
|
| 529 |
+
):
|
| 530 |
+
"""Detokenize sampled tokens and returns them to the user."""
|
| 531 |
+
del idx
|
| 532 |
+
# One of these per generate engine.
|
| 533 |
+
# For all filled my_slots, pop the sampled token onto the relevant
|
| 534 |
+
# requests return channel. If it done, place it back onto free slots.
|
| 535 |
+
metadata = generate_engine.get_tokenizer()
|
| 536 |
+
vocab = token_utils.load_vocab(metadata.path, metadata.extra_ids)
|
| 537 |
+
|
| 538 |
+
my_live_requests = {
|
| 539 |
+
i: None for i in range(generate_engine.max_concurrent_decodes)
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
while self.live:
|
| 543 |
+
try:
|
| 544 |
+
data = my_detokenize_backlog.get(block=True)
|
| 545 |
+
if data is None:
|
| 546 |
+
break
|
| 547 |
+
start_detokenise_time = time.time()
|
| 548 |
+
if isinstance(data[1], engine_api.ResultTokens):
|
| 549 |
+
# We want to detokenise them.
|
| 550 |
+
generate_timestep_added, result_tokens = data
|
| 551 |
+
# Disable attribute error because pytype doesn't know this
|
| 552 |
+
# is a result tokens, and we can't annotate the tuple.
|
| 553 |
+
result_tokens = result_tokens.convert_to_numpy() # pytype: disable=attribute-error
|
| 554 |
+
|
| 555 |
+
for slot, request in my_live_requests.items():
|
| 556 |
+
if request is not None:
|
| 557 |
+
# print(vocab)
|
| 558 |
+
# print(dir(vocab))
|
| 559 |
+
# req_vocab = json.loads(request.vocab)
|
| 560 |
+
tempbos_id = request.vocab['bos_id'] if 'bos_id' in request.vocab else vocab.bos_id
|
| 561 |
+
tempeos_id = request.vocab['eos_id'] if 'eos_id' in request.vocab else vocab.eos_id
|
| 562 |
+
temppad_id = request.vocab['pad_id'] if 'pad_id' in request.vocab else vocab.pad_id
|
| 563 |
+
|
| 564 |
+
results, complete = token_utils.process_result_tokens(
|
| 565 |
+
slot=slot,
|
| 566 |
+
slot_max_length=request.max_tokens,
|
| 567 |
+
result_tokens=result_tokens,
|
| 568 |
+
vocab=vocab,
|
| 569 |
+
eos_id = tempeos_id,
|
| 570 |
+
pad_id = temppad_id,
|
| 571 |
+
bos_id = tempbos_id,
|
| 572 |
+
complete=request.complete,
|
| 573 |
+
)
|
| 574 |
+
request.complete = complete
|
| 575 |
+
# Return some tokens.
|
| 576 |
+
request.enqueue_tokens(results)
|
| 577 |
+
if request.complete.all():
|
| 578 |
+
# Place the slot back on the free queue.
|
| 579 |
+
my_live_requests[slot] = None
|
| 580 |
+
my_slots.put(slot)
|
| 581 |
+
logging.info(
|
| 582 |
+
'Detokenising generate step %d took %.2fms',
|
| 583 |
+
generate_timestep_added,
|
| 584 |
+
(time.time() - start_detokenise_time) * 10**3,
|
| 585 |
+
)
|
| 586 |
+
else:
|
| 587 |
+
# We want to update a slot with the new channel.
|
| 588 |
+
slot, active_request = data
|
| 589 |
+
my_live_requests[slot] = active_request
|
| 590 |
+
|
| 591 |
+
except queue.Empty:
|
| 592 |
+
# Nothing to detokenize!
|
| 593 |
+
pass
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
class LLMOrchestrator(jetstream_pb2_grpc.OrchestratorServicer):
|
| 597 |
+
"""Coordinates a set of prefill and generate slices for LLM decoding."""
|
| 598 |
+
|
| 599 |
+
_driver: Driver
|
| 600 |
+
|
| 601 |
+
def __init__(self, driver: Driver):
|
| 602 |
+
self._driver = driver
|
| 603 |
+
|
| 604 |
+
def Decode(
|
| 605 |
+
self,
|
| 606 |
+
request: jetstream_pb2.DecodeRequest,
|
| 607 |
+
context: Optional[grpc.ServicerContext] = None,
|
| 608 |
+
) -> Iterable[jetstream_pb2.DecodeResponse]:
|
| 609 |
+
"""Decode."""
|
| 610 |
+
if context is None:
|
| 611 |
+
logging.warning(
|
| 612 |
+
'LLM orchestrator is being used in offline test mode, and will not'
|
| 613 |
+
' respond to gRPC queries - only direct function calls.'
|
| 614 |
+
)
|
| 615 |
+
# Wrap request as an ActiveRequest.
|
| 616 |
+
active_request = ActiveRequest(
|
| 617 |
+
max_tokens=request.max_tokens,
|
| 618 |
+
vocab=json.loads(request.vocab),
|
| 619 |
+
history_path=request.session_cache,
|
| 620 |
+
prefill_text=request.additional_text,
|
| 621 |
+
)
|
| 622 |
+
# The first stage is being prefilled, all other stages are handled
|
| 623 |
+
# inside the driver (transfer, generate*N, detokenize).
|
| 624 |
+
try:
|
| 625 |
+
self._driver.place_request_on_prefill_queue(active_request)
|
| 626 |
+
except queue.Full:
|
| 627 |
+
# Safely abort the gRPC server thread with a retriable error.
|
| 628 |
+
_abort_or_raise(
|
| 629 |
+
context=context,
|
| 630 |
+
code=grpc.StatusCode.RESOURCE_EXHAUSTED,
|
| 631 |
+
details=(
|
| 632 |
+
'The driver prefill queue is full and more requests cannot be'
|
| 633 |
+
' handled. You may retry this request.'
|
| 634 |
+
),
|
| 635 |
+
)
|
| 636 |
+
logging.info(
|
| 637 |
+
'Placed request on the prefill queue.',
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
while not (
|
| 641 |
+
active_request.complete and active_request.return_channel.empty()
|
| 642 |
+
):
|
| 643 |
+
# When an active request is created a queue is instantiated. New tokens
|
| 644 |
+
# are placed there during the decoding loop, we pop from that queue by
|
| 645 |
+
# using the .next method on the active request.
|
| 646 |
+
# Yielding allows for the response to be a streaming grpc call - which
|
| 647 |
+
# can be called via iterating over a for loop on the other side.
|
| 648 |
+
# The DecodeResponse stream should consume all generated tokens in
|
| 649 |
+
# return_channel when complete signal is received. It should check if
|
| 650 |
+
# return_channel is empty to decide if it should exit the while loop.
|
| 651 |
+
yield jetstream_pb2.DecodeResponse(response=active_request.next())
|
maxtext-setup/jetstream/build/lib/jetstream/core/orchestrator_test.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Integration test of the orchestrator.
|
| 16 |
+
|
| 17 |
+
This test tests the multi-htreaded orchestrator, where a prefill request is
|
| 18 |
+
popped onto a prefill queue, prefilled, sent to a generation queue and run for
|
| 19 |
+
a number of decoding steps.
|
| 20 |
+
|
| 21 |
+
In operation, it will use gRPC so we can 'yield' from the function to get return
|
| 22 |
+
values in the same way that they would be streamed back.
|
| 23 |
+
|
| 24 |
+
Similar to 'mock_engine_test' we can use known token values and a singleton
|
| 25 |
+
weight to test our operation.
|
| 26 |
+
|
| 27 |
+
Let the prefill engine have a weight of [2] and the generate engine have a
|
| 28 |
+
weight of [3].
|
| 29 |
+
|
| 30 |
+
I.e. if we prefill [2, 65, 66] (i.e. <BOS>, 'A', 'B') using an ACII vocab,
|
| 31 |
+
we should get [4, 130, 132].
|
| 32 |
+
|
| 33 |
+
If we then insert that and run three generation steps, we should see
|
| 34 |
+
266+0 / 2 = 266
|
| 35 |
+
266 + [266] / 4 = 332
|
| 36 |
+
266 + [266, 332] / 4 = 415
|
| 37 |
+
I.e. ['Ċ', 'Ō', 'Ɵ'] when converted back with chr().
|
| 38 |
+
|
| 39 |
+
Therefore we should get back the character sequence '$lǔ' if we request 3 tokens
|
| 40 |
+
decoded (these are the ascii chars at those indices which is what the test
|
| 41 |
+
tokenizer returns).
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
from absl.testing import absltest
|
| 45 |
+
from jetstream.core import orchestrator
|
| 46 |
+
from jetstream.core.proto import jetstream_pb2
|
| 47 |
+
from jetstream.engine import mock_engine
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class OrchestratorTest(absltest.TestCase):
|
| 51 |
+
|
| 52 |
+
def _setup_driver(self):
|
| 53 |
+
prefill_engine = mock_engine.TestEngine(
|
| 54 |
+
batch_size=32, cache_length=256, weight=2.0
|
| 55 |
+
)
|
| 56 |
+
# Create a generate engine with a different set of weights
|
| 57 |
+
# so that we can test that the right one is in use at a given time.
|
| 58 |
+
generate_engine = mock_engine.TestEngine(
|
| 59 |
+
batch_size=4, cache_length=32, weight=4.0
|
| 60 |
+
)
|
| 61 |
+
driver = orchestrator.Driver(
|
| 62 |
+
prefill_engines=[prefill_engine],
|
| 63 |
+
generate_engines=[generate_engine],
|
| 64 |
+
prefill_params=[prefill_engine.load_params()],
|
| 65 |
+
generate_params=[generate_engine.load_params()],
|
| 66 |
+
)
|
| 67 |
+
return driver
|
| 68 |
+
|
| 69 |
+
def test_orchestrator(self):
|
| 70 |
+
"""Test the multithreaded orchestration."""
|
| 71 |
+
driver = self._setup_driver()
|
| 72 |
+
client = orchestrator.LLMOrchestrator(driver=driver)
|
| 73 |
+
|
| 74 |
+
# The string representation of np.array([[65, 66]]), [2] will be prepend
|
| 75 |
+
# as BOS.
|
| 76 |
+
text = 'AB'
|
| 77 |
+
|
| 78 |
+
request = jetstream_pb2.DecodeRequest(
|
| 79 |
+
session_cache='',
|
| 80 |
+
additional_text=text,
|
| 81 |
+
priority=1,
|
| 82 |
+
max_tokens=3,
|
| 83 |
+
)
|
| 84 |
+
iterator = client.Decode(request)
|
| 85 |
+
# chr of [266, 332, 415].
|
| 86 |
+
expected_tokens = ['Ċ', 'Ō', 'Ɵ', '']
|
| 87 |
+
counter = 0
|
| 88 |
+
for token in iterator:
|
| 89 |
+
# Tokens come through as bytes.
|
| 90 |
+
print(
|
| 91 |
+
'actual output: '
|
| 92 |
+
+ bytes(token.response[0], encoding='utf-8').decode()
|
| 93 |
+
)
|
| 94 |
+
assert (
|
| 95 |
+
bytes(token.response[0], encoding='utf-8').decode()
|
| 96 |
+
== expected_tokens[counter]
|
| 97 |
+
)
|
| 98 |
+
counter += 1
|
| 99 |
+
driver.stop()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if __name__ == '__main__':
|
| 103 |
+
absltest.main()
|
maxtext-setup/jetstream/build/lib/jetstream/core/proto/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
maxtext-setup/jetstream/build/lib/jetstream/core/proto/jetstream_pb2.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
# -*- coding: utf-8 -*-
|
| 16 |
+
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
| 17 |
+
# source: jetstream/core/proto/jetstream.proto
|
| 18 |
+
# Protobuf Python Version: 4.25.1
|
| 19 |
+
"""Generated protocol buffer code."""
|
| 20 |
+
from google.protobuf import descriptor as _descriptor
|
| 21 |
+
from google.protobuf import descriptor_pool as _descriptor_pool
|
| 22 |
+
from google.protobuf import symbol_database as _symbol_database
|
| 23 |
+
from google.protobuf.internal import builder as _builder
|
| 24 |
+
# @@protoc_insertion_point(imports)
|
| 25 |
+
|
| 26 |
+
_sym_db = _symbol_database.Default()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n$jetstream/core/proto/jetstream.proto\x12\x0fjetstream.proto\x12\x0fjetstream_proto\"t\n\rDecodeRequest\x12\x15\n\rsession_cache\x18\x01 \x01(\t\x12\x17\n\x0f\x61\x64\x64itional_text\x18\x02 \x01(\t\x12\x10\n\x08priority\x18\x03 \x01(\x05\x12\x12\n\nmax_tokens\x18\x04 \x01(\x05\x12\r\n\x05vocab\x18\x05 \x01(\t\"\"\n\x0e\x44\x65\x63odeResponse\x12\x10\n\x08response\x18\x01 \x03(\t2]\n\x0cOrchestrator\x12M\n\x06\x44\x65\x63ode\x12\x1e.jetstream_proto.DecodeRequest\x1a\x1f.jetstream_proto.DecodeResponse\"\x00\x30\x01\x62\x06proto3')
|
| 32 |
+
|
| 33 |
+
_globals = globals()
|
| 34 |
+
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
|
| 35 |
+
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'jetstream.core.proto.jetstream_pb2', _globals)
|
| 36 |
+
# if _descriptor._USE_C_DESCRIPTORS == False:
|
| 37 |
+
# DESCRIPTOR._options = None
|
| 38 |
+
# _globals['_DECODEREQUEST']._serialized_start=57
|
| 39 |
+
# _globals['_DECODEREQUEST']._serialized_end=173 #158
|
| 40 |
+
# _globals['_DECODERESPONSE']._serialized_start=175 #160
|
| 41 |
+
# _globals['_DECODERESPONSE']._serialized_end=209 #194
|
| 42 |
+
# _globals['_ORCHESTRATOR']._serialized_start=196
|
| 43 |
+
# _globals['_ORCHESTRATOR']._serialized_end=289
|
| 44 |
+
# @@protoc_insertion_point(module_scope)
|
maxtext-setup/jetstream/build/lib/jetstream/core/proto/jetstream_pb2_grpc.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
|
| 16 |
+
"""Client and server classes corresponding to protobuf-defined services."""
|
| 17 |
+
import grpc
|
| 18 |
+
|
| 19 |
+
from jetstream.core.proto import jetstream_pb2 as jetstream_dot_core_dot_proto_dot_jetstream__pb2
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class OrchestratorStub(object):
|
| 23 |
+
"""TODO: Merge this with main JetStream core once we settle on an API.
|
| 24 |
+
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self, channel):
|
| 28 |
+
"""Constructor.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
channel: A grpc.Channel.
|
| 32 |
+
"""
|
| 33 |
+
self.Decode = channel.unary_stream(
|
| 34 |
+
'/jetstream_proto.Orchestrator/Decode',
|
| 35 |
+
request_serializer=jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeRequest.SerializeToString,
|
| 36 |
+
response_deserializer=jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeResponse.FromString,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class OrchestratorServicer(object):
|
| 41 |
+
"""TODO: Merge this with main JetStream core once we settle on an API.
|
| 42 |
+
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def Decode(self, request, context):
|
| 46 |
+
"""Generate the next model tokens.
|
| 47 |
+
"""
|
| 48 |
+
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
|
| 49 |
+
context.set_details('Method not implemented!')
|
| 50 |
+
raise NotImplementedError('Method not implemented!')
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def add_OrchestratorServicer_to_server(servicer, server):
|
| 54 |
+
rpc_method_handlers = {
|
| 55 |
+
'Decode': grpc.unary_stream_rpc_method_handler(
|
| 56 |
+
servicer.Decode,
|
| 57 |
+
request_deserializer=jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeRequest.FromString,
|
| 58 |
+
response_serializer=jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeResponse.SerializeToString,
|
| 59 |
+
),
|
| 60 |
+
}
|
| 61 |
+
generic_handler = grpc.method_handlers_generic_handler(
|
| 62 |
+
'jetstream_proto.Orchestrator', rpc_method_handlers)
|
| 63 |
+
server.add_generic_rpc_handlers((generic_handler,))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# This class is part of an EXPERIMENTAL API.
|
| 67 |
+
class Orchestrator(object):
|
| 68 |
+
"""TODO: Merge this with main JetStream core once we settle on an API.
|
| 69 |
+
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
@staticmethod
|
| 73 |
+
def Decode(request,
|
| 74 |
+
target,
|
| 75 |
+
options=(),
|
| 76 |
+
channel_credentials=None,
|
| 77 |
+
call_credentials=None,
|
| 78 |
+
insecure=False,
|
| 79 |
+
compression=None,
|
| 80 |
+
wait_for_ready=None,
|
| 81 |
+
timeout=None,
|
| 82 |
+
metadata=None):
|
| 83 |
+
return grpc.experimental.unary_stream(request, target, '/jetstream_proto.Orchestrator/Decode',
|
| 84 |
+
jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeRequest.SerializeToString,
|
| 85 |
+
jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeResponse.FromString,
|
| 86 |
+
options, channel_credentials,
|
| 87 |
+
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
|
maxtext-setup/jetstream/build/lib/jetstream/core/server_lib.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Contains common functions for a JetStream core server.
|
| 16 |
+
|
| 17 |
+
See implementations/*/sever.py for examples.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from concurrent import futures
|
| 21 |
+
import logging
|
| 22 |
+
from typing import Any, Type
|
| 23 |
+
|
| 24 |
+
import grpc
|
| 25 |
+
import jax
|
| 26 |
+
from jetstream.core import config_lib
|
| 27 |
+
from jetstream.core import orchestrator
|
| 28 |
+
from jetstream.core.proto import jetstream_pb2_grpc
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
_HOST = '[::]'
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class JetStreamServer:
|
| 35 |
+
"""JetStream grpc server."""
|
| 36 |
+
|
| 37 |
+
def __init__(self, driver: orchestrator.Driver, server: grpc.Server):
|
| 38 |
+
self._driver = driver
|
| 39 |
+
self._server = server
|
| 40 |
+
|
| 41 |
+
def start(self, port, credentials) -> None:
|
| 42 |
+
self._server.add_secure_port(f'{_HOST}:{port}', credentials)
|
| 43 |
+
self._server.start()
|
| 44 |
+
|
| 45 |
+
def stop(self) -> None:
|
| 46 |
+
# Gracefully clean up threads in the orchestrator.
|
| 47 |
+
self._driver.stop()
|
| 48 |
+
self._server.stop(0)
|
| 49 |
+
|
| 50 |
+
def wait_for_termination(self) -> None:
|
| 51 |
+
self._server.wait_for_termination()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def run(
|
| 55 |
+
port: int,
|
| 56 |
+
config: Type[config_lib.ServerConfig],
|
| 57 |
+
devices: Any,
|
| 58 |
+
credentials: Any = grpc.insecure_server_credentials(),
|
| 59 |
+
threads: int | None = None,
|
| 60 |
+
) -> JetStreamServer:
|
| 61 |
+
"""Runs a server with a specified config.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
port: Port on which the server will be made available.
|
| 65 |
+
config: A ServerConfig to config engine, model, device slices, etc.
|
| 66 |
+
devices: Device objects, will be used to get engine with proper slicing.
|
| 67 |
+
credentials: Should use grpc credentials by default.
|
| 68 |
+
threads: Number of RPC handlers worker threads. This should be at least
|
| 69 |
+
equal to the decoding batch size to fully saturate the decoding queue.
|
| 70 |
+
|
| 71 |
+
Returns:
|
| 72 |
+
JetStreamServer that wraps the grpc server and orchestrator driver.
|
| 73 |
+
"""
|
| 74 |
+
logging.info('Kicking off gRPC server.')
|
| 75 |
+
engines = config_lib.get_engines(config, devices=devices)
|
| 76 |
+
prefill_params = [pe.load_params() for pe in engines.prefill_engines]
|
| 77 |
+
generate_params = [ge.load_params() for ge in engines.generate_engines]
|
| 78 |
+
shared_params = [ie.load_params() for ie in engines.interleaved_engines]
|
| 79 |
+
logging.info('Loaded all weights.')
|
| 80 |
+
driver = orchestrator.Driver(
|
| 81 |
+
prefill_engines=engines.prefill_engines + engines.interleaved_engines,
|
| 82 |
+
generate_engines=engines.generate_engines + engines.interleaved_engines,
|
| 83 |
+
prefill_params=prefill_params + shared_params,
|
| 84 |
+
generate_params=generate_params + shared_params,
|
| 85 |
+
)
|
| 86 |
+
# We default threads to the total number of concurrent allowed decodes,
|
| 87 |
+
# to make sure we can fully saturate the model. Set default minimum to 64.
|
| 88 |
+
threads = threads or max(driver.get_total_concurrent_requests(), 64)
|
| 89 |
+
server = grpc.server(futures.ThreadPoolExecutor(max_workers=threads)) # pytype: disable=wrong-keyword-args
|
| 90 |
+
jetstream_pb2_grpc.add_OrchestratorServicer_to_server(
|
| 91 |
+
orchestrator.LLMOrchestrator(driver=driver), server
|
| 92 |
+
)
|
| 93 |
+
logging.info('Starting server on port %d with %d threads', port, threads)
|
| 94 |
+
|
| 95 |
+
jetstream_server = JetStreamServer(driver, server)
|
| 96 |
+
jetstream_server.start(port, credentials)
|
| 97 |
+
return jetstream_server
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def get_devices() -> Any:
|
| 101 |
+
"""Gets devices locally."""
|
| 102 |
+
# Run interleaved engine on local device.
|
| 103 |
+
devices = jax.devices()
|
| 104 |
+
logging.info('Using local devices for interleaved serving: %d', len(devices))
|
| 105 |
+
return devices
|
maxtext-setup/jetstream/build/lib/jetstream/core/server_test.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Tests gRPC server end-to-end.
|
| 16 |
+
|
| 17 |
+
See orchestrator test for why these characters specifically will be the
|
| 18 |
+
response.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from typing import Any, Type
|
| 22 |
+
|
| 23 |
+
from absl.testing import absltest, parameterized
|
| 24 |
+
import grpc
|
| 25 |
+
from jetstream.core import config_lib
|
| 26 |
+
from jetstream.core import server_lib
|
| 27 |
+
from jetstream.core.proto import jetstream_pb2
|
| 28 |
+
from jetstream.core.proto import jetstream_pb2_grpc
|
| 29 |
+
import portpicker
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ServerTest(parameterized.TestCase):
|
| 33 |
+
|
| 34 |
+
@parameterized.parameters(
|
| 35 |
+
# Uses weight 2 for prefill, 4 for decode.
|
| 36 |
+
(
|
| 37 |
+
config_lib.CPUTestServer,
|
| 38 |
+
['Ċ', 'Ō', 'Ɵ', ''],
|
| 39 |
+
[None, None],
|
| 40 |
+
),
|
| 41 |
+
# Uses the same prefill / generate weights (2).
|
| 42 |
+
(
|
| 43 |
+
config_lib.InterleavedCPUTestServer,
|
| 44 |
+
['Ċ', 'Ə', 'ɖ', ''],
|
| 45 |
+
[None],
|
| 46 |
+
),
|
| 47 |
+
)
|
| 48 |
+
def test_server(
|
| 49 |
+
self,
|
| 50 |
+
config: Type[config_lib.ServerConfig],
|
| 51 |
+
expected_tokens: list[str],
|
| 52 |
+
devices: list[Any],
|
| 53 |
+
):
|
| 54 |
+
"""Sets up a server and requests token responses."""
|
| 55 |
+
######################### Server side ######################################
|
| 56 |
+
port = portpicker.pick_unused_port()
|
| 57 |
+
print('port: ' + str(port))
|
| 58 |
+
credentials = grpc.local_server_credentials()
|
| 59 |
+
|
| 60 |
+
server = server_lib.run(
|
| 61 |
+
port=port,
|
| 62 |
+
config=config,
|
| 63 |
+
devices=devices,
|
| 64 |
+
credentials=credentials,
|
| 65 |
+
)
|
| 66 |
+
###################### Requester side ######################################
|
| 67 |
+
channel = grpc.secure_channel(
|
| 68 |
+
f'localhost:{port}', grpc.local_channel_credentials()
|
| 69 |
+
)
|
| 70 |
+
stub = jetstream_pb2_grpc.OrchestratorStub(channel)
|
| 71 |
+
|
| 72 |
+
# The string representation of np.array([[65, 66]]), [2] will be prependd
|
| 73 |
+
# as BOS
|
| 74 |
+
text = 'AB'
|
| 75 |
+
request = jetstream_pb2.DecodeRequest(
|
| 76 |
+
session_cache='',
|
| 77 |
+
additional_text=text,
|
| 78 |
+
priority=1,
|
| 79 |
+
max_tokens=3,
|
| 80 |
+
)
|
| 81 |
+
iterator = stub.Decode(request)
|
| 82 |
+
counter = 0
|
| 83 |
+
for token in iterator:
|
| 84 |
+
# Tokens come through as bytes
|
| 85 |
+
print(
|
| 86 |
+
'actual output: '
|
| 87 |
+
+ bytes(token.response[0], encoding='utf-8').decode()
|
| 88 |
+
)
|
| 89 |
+
assert (
|
| 90 |
+
bytes(token.response[0], encoding='utf-8').decode()
|
| 91 |
+
== expected_tokens[counter]
|
| 92 |
+
)
|
| 93 |
+
counter += 1
|
| 94 |
+
server.stop()
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if __name__ == '__main__':
|
| 98 |
+
absltest.main()
|
maxtext-setup/jetstream/build/lib/jetstream/engine/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
maxtext-setup/jetstream/build/lib/jetstream/engine/engine_api.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Defines the JetStream API.
|
| 16 |
+
|
| 17 |
+
These functions are the accelerator functions which an outer sampling loop
|
| 18 |
+
could want to call, enabling interleaved (continuous batching) inference.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import abc
|
| 22 |
+
from typing import Any, Optional, Tuple, Union
|
| 23 |
+
|
| 24 |
+
from flax import struct
|
| 25 |
+
import jax
|
| 26 |
+
import numpy as np
|
| 27 |
+
|
| 28 |
+
from jetstream.engine import tokenizer_pb2
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# The model parameters - their partitioning will be unique for different prefill
|
| 32 |
+
# and decode topoologies.
|
| 33 |
+
Params = Any
|
| 34 |
+
# The result of a prefill operation, often a batch size 1 KVCache.
|
| 35 |
+
Prefix = Any
|
| 36 |
+
# The inputs into a generation step, often a prefill and generate cache tuple.
|
| 37 |
+
DecodeState = Any
|
| 38 |
+
# Accelerator representation of tokens.
|
| 39 |
+
DeviceTokens = Any
|
| 40 |
+
# Cpus asscociated with the mesh.
|
| 41 |
+
CpuDevices = Any
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@struct.dataclass
|
| 45 |
+
class SlotData:
|
| 46 |
+
"""Class to store slot data."""
|
| 47 |
+
tokens: Union[jax.Array, np.ndarray]
|
| 48 |
+
valid: Union[jax.Array, np.ndarray]
|
| 49 |
+
lengths: Union[jax.Array, np.ndarray]
|
| 50 |
+
|
| 51 |
+
# pylint: disable=g-doc-args
|
| 52 |
+
@struct.dataclass
|
| 53 |
+
class ResultTokens(abc.ABC):
|
| 54 |
+
"""Class to store returned tokens in.
|
| 55 |
+
|
| 56 |
+
We store everything in one array, and keep indexes - because copying
|
| 57 |
+
a single array to host is much faster.
|
| 58 |
+
Each tuple represents the indices of the relevant data.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
# Shape: [batch, tokens.shape[1] + validity.shape[1] + lengths.shape[1]]
|
| 62 |
+
data: Union[jax.Array, np.ndarray]
|
| 63 |
+
# The range of indices which contain tokens.
|
| 64 |
+
tokens_idx: tuple[int, int] = struct.field(
|
| 65 |
+
pytree_node=False,
|
| 66 |
+
)
|
| 67 |
+
# The range of indices which contain the validity of
|
| 68 |
+
# the tokens.
|
| 69 |
+
valid_idx: tuple[int, int] = struct.field(
|
| 70 |
+
pytree_node=False,
|
| 71 |
+
)
|
| 72 |
+
# The range of indices which contain the lengths up till now of the lengths
|
| 73 |
+
# of each generated sequence.
|
| 74 |
+
length_idx: tuple[int, int] = struct.field(
|
| 75 |
+
pytree_node=False,
|
| 76 |
+
)
|
| 77 |
+
samples_per_slot: int = struct.field(
|
| 78 |
+
pytree_node=False,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
def copy_to_host_async(self: 'ResultTokens') -> None:
|
| 82 |
+
"""Copy to host asynchronously."""
|
| 83 |
+
self.data.copy_to_host_async()
|
| 84 |
+
|
| 85 |
+
def convert_to_numpy(self: 'ResultTokens') -> 'ResultTokens':
|
| 86 |
+
"""Converts to numpy."""
|
| 87 |
+
return ResultTokens(
|
| 88 |
+
np.array(self.data),
|
| 89 |
+
self.tokens_idx,
|
| 90 |
+
self.valid_idx,
|
| 91 |
+
self.length_idx,
|
| 92 |
+
self.samples_per_slot,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
def get_result_at_slot(
|
| 96 |
+
self, slot: int
|
| 97 |
+
) -> SlotData:
|
| 98 |
+
"""Returns the token at a given slot.
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
slot: An integer from [0, n) representing an index into the batch.
|
| 102 |
+
|
| 103 |
+
Note: implementations of this method must correctly handle
|
| 104 |
+
microbatches, if microbatches are used.
|
| 105 |
+
"""
|
| 106 |
+
# Potentially get multiple beams for given slot.
|
| 107 |
+
start_idx = slot * self.samples_per_slot
|
| 108 |
+
end_idx = (slot + 1) * self.samples_per_slot
|
| 109 |
+
# Mask out any non valid tokens.
|
| 110 |
+
return SlotData(
|
| 111 |
+
tokens=self.data[start_idx:end_idx, self.tokens_idx[0]:self.tokens_idx[1]],
|
| 112 |
+
valid=self.data[start_idx:end_idx, self.valid_idx[0]:self.valid_idx[1]],
|
| 113 |
+
# Only get a 1D representation here
|
| 114 |
+
lengths=self.data[start_idx:end_idx, self.length_idx[0]:self.length_idx[1]][:, 0]
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class Engine(abc.ABC):
|
| 119 |
+
"""The computational core of the generative model server.
|
| 120 |
+
|
| 121 |
+
Engine defines an API that models must adhere to as they plug into the
|
| 122 |
+
JetStream efficient serving infrastructure.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
@abc.abstractmethod
|
| 126 |
+
def prefill(
|
| 127 |
+
self,
|
| 128 |
+
*,
|
| 129 |
+
params: Params,
|
| 130 |
+
existing_prefix: Optional[Prefix] = None,
|
| 131 |
+
padded_tokens: jax.Array,
|
| 132 |
+
true_length: int,
|
| 133 |
+
) -> Prefix:
|
| 134 |
+
"""Computes a kv-cache for a set of tokens conditional on existing cache.
|
| 135 |
+
|
| 136 |
+
existing_prefix (if provided) represents a prefix that has already been
|
| 137 |
+
processed by the underlying model. tokens is logically appended
|
| 138 |
+
to the text represented by `existing_prefix`. This method returns a new
|
| 139 |
+
kv_cache (typically) for the resulting text.
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
@abc.abstractmethod
|
| 143 |
+
def generate(
|
| 144 |
+
self,
|
| 145 |
+
params: Params,
|
| 146 |
+
decode_state: DecodeState
|
| 147 |
+
) -> Tuple[DecodeState, ResultTokens]:
|
| 148 |
+
"""Generates tokens for each sequence being decoded in parallel.
|
| 149 |
+
|
| 150 |
+
Generate takes a batch of pre-computed kv-caches, and computes:
|
| 151 |
+
- the predicted next token for each of the sequences
|
| 152 |
+
- an updated set of kv-caches
|
| 153 |
+
|
| 154 |
+
In the case of pipelining, this will handle N cycles (where each cycle
|
| 155 |
+
consists of each microbatch progressing through every stage), in
|
| 156 |
+
non-pipelined code this is a full forward pass. In both cases, this accounts
|
| 157 |
+
for a full embed-layerstack-unembed-sample operation.
|
| 158 |
+
"""
|
| 159 |
+
|
| 160 |
+
@abc.abstractmethod
|
| 161 |
+
def insert(
|
| 162 |
+
self,
|
| 163 |
+
prefix: Prefix,
|
| 164 |
+
decode_state: DecodeState,
|
| 165 |
+
slot: int,
|
| 166 |
+
) -> DecodeState:
|
| 167 |
+
"""Adds `new_request` into `caches` at 'slot'.
|
| 168 |
+
|
| 169 |
+
When decoding multiple requests in parallel, when one request finishes, a
|
| 170 |
+
new request must be slotted into the recently vacated spot: `insert`!
|
| 171 |
+
|
| 172 |
+
This can occur in between and async to generate calls, and takes a lock over
|
| 173 |
+
that row of the cache.
|
| 174 |
+
|
| 175 |
+
The slot may represent a tuple of positions (e.g. microbatch, pipeline stage
|
| 176 |
+
and batch), but at the engine interface level all of these are exposed as
|
| 177 |
+
a [0, n) range of slots and converted internally.
|
| 178 |
+
"""
|
| 179 |
+
|
| 180 |
+
@abc.abstractmethod
|
| 181 |
+
def load_params(self, *args, **kwargs) -> Params:
|
| 182 |
+
"""Loads parameters.
|
| 183 |
+
|
| 184 |
+
May not be used in full production form, where weights are part of the saved
|
| 185 |
+
model.
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
@abc.abstractmethod
|
| 189 |
+
def get_prefix_destination_sharding(self) -> Any:
|
| 190 |
+
"""Returns the shardings necessary to transfer data between engines."""
|
| 191 |
+
|
| 192 |
+
@abc.abstractmethod
|
| 193 |
+
def get_tokenizer(
|
| 194 |
+
self,
|
| 195 |
+
) -> tokenizer_pb2.TokenizerParameters:
|
| 196 |
+
"""Returns the info to construct a sentencepiece tokenizer in py/c++."""
|
| 197 |
+
|
| 198 |
+
@abc.abstractmethod
|
| 199 |
+
def init_decode_state(self, *args, **kwargs) -> DecodeState:
|
| 200 |
+
"""Initialises any state which a generation step transforms."""
|
| 201 |
+
|
| 202 |
+
@property
|
| 203 |
+
@abc.abstractmethod
|
| 204 |
+
def max_concurrent_decodes(self) -> int:
|
| 205 |
+
"""Total capacity."""
|
| 206 |
+
|
| 207 |
+
@property
|
| 208 |
+
@abc.abstractmethod
|
| 209 |
+
def samples_per_slot(self) -> int:
|
| 210 |
+
"""Total samples per slot."""
|
| 211 |
+
|
| 212 |
+
@property
|
| 213 |
+
@abc.abstractmethod
|
| 214 |
+
def max_prefill_length(self) -> int:
|
| 215 |
+
"""Maximum prefill length."""
|
| 216 |
+
|
| 217 |
+
@property
|
| 218 |
+
@abc.abstractmethod
|
| 219 |
+
def mesh(self) -> jax.sharding.Mesh:
|
| 220 |
+
"""Mesh which the engine is running on."""
|
| 221 |
+
|
| 222 |
+
@property
|
| 223 |
+
@abc.abstractmethod
|
| 224 |
+
def colocated_cpus(self) -> Union[list[CpuDevices], None]:
|
| 225 |
+
"""CPU devices colocated with the engine's accelerators."""
|
maxtext-setup/jetstream/build/lib/jetstream/engine/mock_engine.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Simple test engine for the JetStream API described.
|
| 16 |
+
|
| 17 |
+
Contains simple functions that we can hand calculate the desired outcome of.
|
| 18 |
+
|
| 19 |
+
Prefill: Doubles the sequence by multiplying it with an integer weight.
|
| 20 |
+
Insert: Writes this sequence into a cache row.
|
| 21 |
+
Generate step: Return sum(prefill_cache) + sum(generate_cache)/weight.
|
| 22 |
+
|
| 23 |
+
I.e. if we prefill [2, 65, 66] (i.e. <BOS>, 'A', 'B') using an ACII vocab,
|
| 24 |
+
we should get [4, 130, 132].
|
| 25 |
+
|
| 26 |
+
If we then insert that and run three generation steps, we should see
|
| 27 |
+
266+0 / 2 = 266
|
| 28 |
+
266 + [266] /2 = 399
|
| 29 |
+
266 + [266, 399] /2 = 598
|
| 30 |
+
I.e. ['Ċ', 'Ə', 'ɖ'] when converted back with chr()
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
import functools
|
| 34 |
+
from typing import Any, Optional, Tuple
|
| 35 |
+
|
| 36 |
+
from flax import struct
|
| 37 |
+
import jax
|
| 38 |
+
from jax.experimental import mesh_utils
|
| 39 |
+
import jax.numpy as jnp
|
| 40 |
+
|
| 41 |
+
from jetstream.engine import engine_api
|
| 42 |
+
from jetstream.engine import tokenizer_pb2
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
Params = jax.Array # [1,].
|
| 46 |
+
Prefix = jax.Array # [batch,] of strings with different lengths.
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@struct.dataclass
|
| 50 |
+
class DecodeState:
|
| 51 |
+
"""The inputs into a generation step."""
|
| 52 |
+
prefill_cache: jax.Array
|
| 53 |
+
generate_cache: jax.Array
|
| 54 |
+
generate_cache_index: int
|
| 55 |
+
generate_lengths: jax.Array
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class TestEngine(engine_api.Engine):
|
| 59 |
+
"""The computational core of the generative model server.
|
| 60 |
+
|
| 61 |
+
Engine defines an API that models must adhere to as they plug into the
|
| 62 |
+
JetStream efficient serving infrastructure.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(self, batch_size: int, cache_length: int, weight: float):
|
| 66 |
+
self.prefill_cache_batch = batch_size
|
| 67 |
+
self.generate_cache_batch = batch_size
|
| 68 |
+
self.cache_length = cache_length
|
| 69 |
+
self.weight = weight
|
| 70 |
+
self._mesh = jax.sharding.Mesh(
|
| 71 |
+
mesh_utils.create_device_mesh((1, 1, 1), jax.devices()), ('x', 'y', 'z')
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def load_params(self) -> Params:
|
| 75 |
+
"""Loads model weights."""
|
| 76 |
+
# An integer, used to multiply inputs.
|
| 77 |
+
return jnp.array([self.weight], dtype=jnp.float32)
|
| 78 |
+
|
| 79 |
+
@functools.partial(jax.jit, static_argnums=(0,))
|
| 80 |
+
def prefill(
|
| 81 |
+
self,
|
| 82 |
+
*,
|
| 83 |
+
params: Params,
|
| 84 |
+
existing_prefix: Optional[jax.Array] = None,
|
| 85 |
+
padded_tokens: jax.Array,
|
| 86 |
+
true_length: int,
|
| 87 |
+
) -> Prefix:
|
| 88 |
+
"""Computes a kv-cache for a new generate request.
|
| 89 |
+
|
| 90 |
+
Args:
|
| 91 |
+
params: Scalar multiplier.
|
| 92 |
+
existing_prefix: If provided, represents a prefix that has already been
|
| 93 |
+
processed by the underlying model.
|
| 94 |
+
padded_tokens: Logically appended tokens to any existing prefix, this is
|
| 95 |
+
what we compute prefill on.
|
| 96 |
+
true_length: The real length of the tokens, pre-pad.
|
| 97 |
+
Returns:
|
| 98 |
+
kv_cache: For the resulting text.
|
| 99 |
+
"""
|
| 100 |
+
if existing_prefix is not None:
|
| 101 |
+
raise NotImplementedError
|
| 102 |
+
del true_length
|
| 103 |
+
assert padded_tokens.ndim == 1
|
| 104 |
+
# Wait to simulate model step time.
|
| 105 |
+
fake_size = 4096
|
| 106 |
+
fake_work = jnp.ones((fake_size, fake_size)) @ jnp.ones(
|
| 107 |
+
(fake_size, fake_size)
|
| 108 |
+
)
|
| 109 |
+
# Do some fake work that isn't eliminated by dead code elimination (DCE).
|
| 110 |
+
params = params + fake_work.mean() - fake_work.mean()
|
| 111 |
+
return padded_tokens[None, :] * params
|
| 112 |
+
|
| 113 |
+
@functools.partial(jax.jit, static_argnums=(0,))
|
| 114 |
+
def generate(
|
| 115 |
+
self, params: Params, decode_state: DecodeState
|
| 116 |
+
) -> Tuple[DecodeState, engine_api.ResultTokens]:
|
| 117 |
+
"""Generates tokens for each sequence being decoded in parallel."""
|
| 118 |
+
prefill_cache, generate_cache, generate_cache_index, generate_lengths = (
|
| 119 |
+
decode_state.prefill_cache,
|
| 120 |
+
decode_state.generate_cache,
|
| 121 |
+
decode_state.generate_cache_index,
|
| 122 |
+
decode_state.generate_lengths,
|
| 123 |
+
)
|
| 124 |
+
# Sum each row of prefill cache and generate cache to produce new timestep,
|
| 125 |
+
# multiply by params.
|
| 126 |
+
l_iota = jax.lax.broadcasted_iota(
|
| 127 |
+
jnp.int32,
|
| 128 |
+
(self.generate_cache_batch, self.cache_length),
|
| 129 |
+
dimension=1,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# The generate cache should be circular and right aligned.
|
| 133 |
+
# TODO: Do we need a left aligned one to test spec sampling?
|
| 134 |
+
# Don't need the + 1 you normally would, because we don't provide a
|
| 135 |
+
# token from prefill in the dummy.
|
| 136 |
+
# This iota and masking is to allow for a cicular cache.
|
| 137 |
+
length_mask = (
|
| 138 |
+
-(l_iota - generate_cache_index + 1) % self.cache_length
|
| 139 |
+
) <= generate_lengths[:, None]
|
| 140 |
+
length_masked_gen_cache = generate_cache * length_mask
|
| 141 |
+
new_timestep = (
|
| 142 |
+
prefill_cache.sum(axis=-1)
|
| 143 |
+
+ (length_masked_gen_cache.sum(axis=-1) / params)
|
| 144 |
+
)[:, jnp.newaxis]
|
| 145 |
+
generate_cache = jax.lax.dynamic_update_slice_in_dim(
|
| 146 |
+
generate_cache, new_timestep, start_index=generate_cache_index, axis=1
|
| 147 |
+
)
|
| 148 |
+
generate_cache_index = (generate_cache_index + 1) % self.cache_length
|
| 149 |
+
# Wait to simulate model step time.
|
| 150 |
+
fake_size = 4096
|
| 151 |
+
fake_work = jnp.ones((fake_size, fake_size)) @ jnp.ones(
|
| 152 |
+
(fake_size, fake_size)
|
| 153 |
+
)
|
| 154 |
+
# Do some fake work that isn't eliminated by dead code elimination (DCE).
|
| 155 |
+
generate_cache = generate_cache + fake_work.mean() - fake_work.mean()
|
| 156 |
+
new_lengths = generate_lengths + 1
|
| 157 |
+
speculations = new_timestep.shape[1]
|
| 158 |
+
# Concatenates the tokens, their validity and the lengths of each sequence
|
| 159 |
+
# into one tensor so that copy operations are faster on Cloud TPU infrastructure.
|
| 160 |
+
token_data = jnp.concatenate(
|
| 161 |
+
[new_timestep, jnp.ones_like(new_timestep), new_lengths[:, None]],
|
| 162 |
+
axis=-1,
|
| 163 |
+
)
|
| 164 |
+
return DecodeState(
|
| 165 |
+
prefill_cache=prefill_cache,
|
| 166 |
+
generate_cache=generate_cache,
|
| 167 |
+
generate_cache_index=generate_cache_index,
|
| 168 |
+
generate_lengths=new_lengths,
|
| 169 |
+
), engine_api.ResultTokens(
|
| 170 |
+
data=token_data.astype(jnp.int32),
|
| 171 |
+
# Tokens are shape [batch, speculations], so when we concatenate
|
| 172 |
+
# tokens, validity and length along their index 1 dimension then they
|
| 173 |
+
# occupy 0:speculations.
|
| 174 |
+
tokens_idx=(0, speculations),
|
| 175 |
+
# Validity occupies the same amount of space, but next in line.
|
| 176 |
+
valid_idx=(speculations, 2 * speculations),
|
| 177 |
+
# And lengths is rank 1.
|
| 178 |
+
length_idx=(2 * speculations, 2 * speculations + 1),
|
| 179 |
+
samples_per_slot=self.generate_cache_batch // self.prefill_cache_batch,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
@functools.partial(jax.jit, static_argnums=(0,), donate_argnums=(2,))
|
| 183 |
+
def insert(
|
| 184 |
+
self,
|
| 185 |
+
prefix: Prefix,
|
| 186 |
+
decode_state: DecodeState,
|
| 187 |
+
slot: int,
|
| 188 |
+
) -> DecodeState:
|
| 189 |
+
"""Adds `prefix` into `decode_state` at `slot`."""
|
| 190 |
+
# [B, T], [T,] -> [B, T]
|
| 191 |
+
prefill_cache = jax.lax.dynamic_update_slice_in_dim(
|
| 192 |
+
decode_state.prefill_cache, prefix, slot, axis=0
|
| 193 |
+
)
|
| 194 |
+
generate_cache = jax.lax.dynamic_update_slice_in_dim(
|
| 195 |
+
decode_state.generate_cache, jnp.zeros((1, self.cache_length)),
|
| 196 |
+
slot, axis=0
|
| 197 |
+
)
|
| 198 |
+
samples_per_slot = self.generate_cache_batch // self.prefill_cache_batch
|
| 199 |
+
generate_lengths = jax.lax.dynamic_update_slice_in_dim(
|
| 200 |
+
decode_state.generate_lengths,
|
| 201 |
+
jnp.zeros((samples_per_slot), dtype=jnp.int32),
|
| 202 |
+
slot * samples_per_slot,
|
| 203 |
+
axis=0,
|
| 204 |
+
)
|
| 205 |
+
return decode_state.replace(
|
| 206 |
+
prefill_cache=prefill_cache,
|
| 207 |
+
generate_cache=generate_cache,
|
| 208 |
+
generate_lengths=generate_lengths,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
def get_prefix_destination_sharding(self) -> Any:
|
| 212 |
+
return jax.sharding.NamedSharding(
|
| 213 |
+
mesh=self.mesh, spec=jax.sharding.PartitionSpec()
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
def get_tokenizer(self) -> tokenizer_pb2.TokenizerParameters:
|
| 217 |
+
"""Return a protobuf of tokenizer info, callable from Py or C++."""
|
| 218 |
+
return tokenizer_pb2.TokenizerParameters(path='test', extra_ids=0)
|
| 219 |
+
|
| 220 |
+
def init_decode_state(self) -> DecodeState:
|
| 221 |
+
"""Initialises any state which a generation step transforms."""
|
| 222 |
+
return DecodeState(
|
| 223 |
+
prefill_cache=jnp.zeros(
|
| 224 |
+
(self.prefill_cache_batch, self.cache_length), dtype=jnp.float32
|
| 225 |
+
),
|
| 226 |
+
generate_cache=jnp.zeros(
|
| 227 |
+
(self.generate_cache_batch, self.cache_length), dtype=jnp.float32
|
| 228 |
+
),
|
| 229 |
+
generate_cache_index=0,
|
| 230 |
+
generate_lengths=jnp.zeros(
|
| 231 |
+
(self.generate_cache_batch), dtype=jnp.int32
|
| 232 |
+
),
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
@property
|
| 236 |
+
def max_concurrent_decodes(self) -> int:
|
| 237 |
+
"""Free slots."""
|
| 238 |
+
return self.prefill_cache_batch
|
| 239 |
+
|
| 240 |
+
@property
|
| 241 |
+
def max_prefill_length(self) -> int:
|
| 242 |
+
"""Maximum prefill length."""
|
| 243 |
+
return self.cache_length
|
| 244 |
+
|
| 245 |
+
@property
|
| 246 |
+
def samples_per_slot(self) -> int:
|
| 247 |
+
"""Number of samples per slot."""
|
| 248 |
+
return self.generate_cache_batch // self.max_concurrent_decodes
|
| 249 |
+
|
| 250 |
+
@property
|
| 251 |
+
def mesh(self) -> jax.sharding.Mesh:
|
| 252 |
+
"""Mesh which the engine is running on."""
|
| 253 |
+
return self._mesh
|
| 254 |
+
|
| 255 |
+
@property
|
| 256 |
+
def colocated_cpus(self) -> None:
|
| 257 |
+
"""CPU devices colocated with the engine's accelerators."""
|
| 258 |
+
raise NotImplementedError
|
maxtext-setup/jetstream/build/lib/jetstream/engine/mock_engine_test.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Tests for a mock version of the engine API.
|
| 16 |
+
|
| 17 |
+
What should we expect?
|
| 18 |
+
|
| 19 |
+
Prefill: Doubles the sequence by multiplying it with a weight [2].
|
| 20 |
+
Insert: Writes this sequence into a cache row
|
| 21 |
+
Generate step: Return sum(prefill_cache) + sum(generate_cache)/weight
|
| 22 |
+
|
| 23 |
+
I.e. if we prefill [2, 65, 66] (i.e. <BOS>, 'A', 'B') using an ACII vocab,
|
| 24 |
+
we should get [4, 130, 132].
|
| 25 |
+
|
| 26 |
+
If we then insert that and run three generation steps, we should see
|
| 27 |
+
266+0 / 2 = 266
|
| 28 |
+
266 + [266] /2 = 399
|
| 29 |
+
266 + [266, 399] /2 = 598
|
| 30 |
+
I.e. ['Ċ', 'Ə', 'ɖ'] when converted back with chr()
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
import jax.numpy as jnp
|
| 34 |
+
import numpy as np
|
| 35 |
+
|
| 36 |
+
from jetstream.engine import mock_engine
|
| 37 |
+
from jetstream.engine import token_utils
|
| 38 |
+
from absl.testing import absltest
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class EngineTest(absltest.TestCase):
|
| 42 |
+
|
| 43 |
+
def _setup(self):
|
| 44 |
+
"""Initialises a test engine."""
|
| 45 |
+
engine = mock_engine.TestEngine(batch_size=32, cache_length=256, weight=2.0)
|
| 46 |
+
params = engine.load_params()
|
| 47 |
+
return engine, params
|
| 48 |
+
|
| 49 |
+
def _prefill(self):
|
| 50 |
+
"""Performs prefill and returns a kv cache."""
|
| 51 |
+
engine, params = self._setup()
|
| 52 |
+
# A 2 will be pre-pended as 'bos' token from the vocab.
|
| 53 |
+
text = 'AB'
|
| 54 |
+
metadata = engine.get_tokenizer()
|
| 55 |
+
vocab = token_utils.load_vocab(metadata.path, metadata.extra_ids)
|
| 56 |
+
tokens, true_length = token_utils.tokenize_and_pad(text, vocab, is_bos=True)
|
| 57 |
+
prefill_result = engine.prefill(
|
| 58 |
+
params=params, padded_tokens=tokens, true_length=3
|
| 59 |
+
)
|
| 60 |
+
return engine, params, prefill_result, true_length
|
| 61 |
+
|
| 62 |
+
def _generate(self, slot=1):
|
| 63 |
+
"""Performs a single generation step."""
|
| 64 |
+
engine, params, prefill_result, _ = self._prefill()
|
| 65 |
+
decode_state = engine.init_decode_state()
|
| 66 |
+
decode_state = engine.insert(
|
| 67 |
+
prefix=prefill_result, decode_state=decode_state, slot=slot
|
| 68 |
+
)
|
| 69 |
+
decode_state, sampled_tokens = engine.generate(
|
| 70 |
+
params=params, decode_state=decode_state
|
| 71 |
+
)
|
| 72 |
+
return engine, params, decode_state, sampled_tokens
|
| 73 |
+
|
| 74 |
+
def test_load_params(self):
|
| 75 |
+
"""Just loads params."""
|
| 76 |
+
_, params = self._setup()
|
| 77 |
+
assert params == jnp.array([2.0])
|
| 78 |
+
|
| 79 |
+
def test_prefill(self):
|
| 80 |
+
"""Tests prefill with weight = 2."""
|
| 81 |
+
_, _, prefill_result, true_length = self._prefill()
|
| 82 |
+
np.testing.assert_array_equal(
|
| 83 |
+
prefill_result[:, :true_length], np.array([[4.0, 130.0, 132.0]])
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
def test_generate(self, slot=1):
|
| 87 |
+
"""Tests multiple generation steps."""
|
| 88 |
+
engine, params, decode_state, sampled_tokens = self._generate(slot=slot)
|
| 89 |
+
metadata = engine.get_tokenizer()
|
| 90 |
+
tokenizer = token_utils.load_vocab(
|
| 91 |
+
metadata.path, metadata.extra_ids
|
| 92 |
+
).tokenizer
|
| 93 |
+
# Char for 266
|
| 94 |
+
token_data = sampled_tokens.get_result_at_slot(slot)
|
| 95 |
+
tok = token_data.tokens
|
| 96 |
+
assert tokenizer.IdToPiece(int(tok.item())) == 'Ċ'
|
| 97 |
+
decode_state, sampled_tokens = engine.generate(
|
| 98 |
+
params=params, decode_state=decode_state
|
| 99 |
+
)
|
| 100 |
+
# Char for 399
|
| 101 |
+
token_data = sampled_tokens.get_result_at_slot(slot)
|
| 102 |
+
tok = token_data.tokens
|
| 103 |
+
assert tokenizer.IdToPiece(int(tok.item())) == 'Ə'
|
| 104 |
+
_, sampled_tokens = engine.generate(
|
| 105 |
+
params=params, decode_state=decode_state
|
| 106 |
+
)
|
| 107 |
+
# Char for 598
|
| 108 |
+
token_data = sampled_tokens.get_result_at_slot(slot)
|
| 109 |
+
tok = token_data.tokens
|
| 110 |
+
assert tokenizer.IdToPiece(int(tok.item())) == 'ɖ'
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
if __name__ == '__main__':
|
| 114 |
+
absltest.main()
|
maxtext-setup/jetstream/build/lib/jetstream/engine/mock_utils.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Utils for engine operation."""
|
| 16 |
+
|
| 17 |
+
from typing import List, Sequence
|
| 18 |
+
from flax import struct
|
| 19 |
+
import numpy as np
|
| 20 |
+
from seqio.vocabularies import Vocabulary
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@struct.dataclass
|
| 24 |
+
class TestTokenizer:
|
| 25 |
+
"""Tokenizer used for testing purposes."""
|
| 26 |
+
|
| 27 |
+
def IdToPiece(self, integer: int) -> str: # pylint: disable=invalid-name
|
| 28 |
+
"""In the real version, unlike encode_tf/decode_tf, doesn't strip trailing whitespace."""
|
| 29 |
+
return chr(integer)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@struct.dataclass
|
| 33 |
+
class TestVocab(Vocabulary):
|
| 34 |
+
"""Mock vocabulary used for tests.
|
| 35 |
+
|
| 36 |
+
These methods are duplicative on the test vocab, but required to fit
|
| 37 |
+
the seqio.Vocabulary interface.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
pad_id = 0
|
| 41 |
+
eos_id = 1
|
| 42 |
+
bos_id = 2
|
| 43 |
+
unk_id = 3
|
| 44 |
+
_base_vocab_size = 2**16
|
| 45 |
+
tokenizer: TestTokenizer = TestTokenizer()
|
| 46 |
+
|
| 47 |
+
def _encode(self, s: str) -> Sequence[int]:
|
| 48 |
+
"""Converts a string into a integer sequenc."""
|
| 49 |
+
# 'We use array methods, not python iterables so we don't
|
| 50 |
+
# implement this method in the mock vocab.
|
| 51 |
+
raise NotImplementedError
|
| 52 |
+
|
| 53 |
+
def _decode(self, tokens: np.ndarray):
|
| 54 |
+
"""Converts a numpy array into a string."""
|
| 55 |
+
# 'We use array methods, not python iterables so we don't
|
| 56 |
+
# implement this method in the mock vocab.
|
| 57 |
+
raise NotImplementedError
|
| 58 |
+
|
| 59 |
+
def _encode_tf(self, text: str) -> np.ndarray:
|
| 60 |
+
"""Converts a string into a numpy array."""
|
| 61 |
+
# We mock using numpy to avoid propagating tf dependencies.
|
| 62 |
+
chars = np.array([ord(c) for c in text]).astype(np.int32)
|
| 63 |
+
return chars
|
| 64 |
+
|
| 65 |
+
def _decode_tf(self, tokens: np.ndarray) -> List[str]:
|
| 66 |
+
"""Converts a numpy array into a string."""
|
| 67 |
+
# We mock using numpy to avoid propagating tf dependencies.
|
| 68 |
+
results = np.split(tokens, tokens.shape[0])
|
| 69 |
+
return [''.join([chr(r) for r in list(line[0])]) for line in results]
|
| 70 |
+
|
| 71 |
+
def encode_tf(self, text: str) -> np.ndarray:
|
| 72 |
+
"""Converts a string into a numpy array."""
|
| 73 |
+
return self._encode_tf(text)
|
| 74 |
+
|
| 75 |
+
def decode_tf(self, tokens: np.ndarray) -> List[str]:
|
| 76 |
+
"""Converts a numpy array into a string."""
|
| 77 |
+
return self._decode_tf(tokens)
|
maxtext-setup/jetstream/build/lib/jetstream/engine/token_utils.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Token manipulation utilities."""
|
| 16 |
+
|
| 17 |
+
from bisect import bisect_left
|
| 18 |
+
import logging
|
| 19 |
+
from typing import List, Optional, Tuple
|
| 20 |
+
|
| 21 |
+
import jax
|
| 22 |
+
import jax.numpy as jnp
|
| 23 |
+
import numpy as np
|
| 24 |
+
from seqio.vocabularies import SentencePieceVocabulary
|
| 25 |
+
from seqio.vocabularies import Vocabulary
|
| 26 |
+
|
| 27 |
+
from jetstream.engine import engine_api
|
| 28 |
+
from jetstream.engine import mock_utils
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def take_nearest_length(lengths: list[int], length: int) -> int:
|
| 32 |
+
"""Gets the nearest length to the right in a set of lengths."""
|
| 33 |
+
pos = bisect_left(lengths, length)
|
| 34 |
+
if pos == len(lengths):
|
| 35 |
+
return lengths[-1]
|
| 36 |
+
return lengths[pos]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def tokenize_and_pad(
|
| 40 |
+
s: str,
|
| 41 |
+
vocab: Vocabulary,
|
| 42 |
+
eos_id: int,
|
| 43 |
+
pad_id: int,
|
| 44 |
+
bos_id: int,
|
| 45 |
+
is_bos: bool = True,
|
| 46 |
+
prefill_lengths: Optional[List[int]] = None,
|
| 47 |
+
max_prefill_length: Optional[int] = None,
|
| 48 |
+
) -> Tuple[jax.Array, int]:
|
| 49 |
+
"""Tokenize and pads a string.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
s: String to tokenize.
|
| 53 |
+
vocab: Vocabulary to tokenize with.
|
| 54 |
+
is_bos: Whether or not this is the beginning of a sequence. Default to yes
|
| 55 |
+
as prefill is typically used when beginning sequences.
|
| 56 |
+
prefill_lengths: Buckets to pad the sequence to for static compilation.
|
| 57 |
+
max_prefill_length: Maximum bucket to use.
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
tokens: Tokenized into integers.
|
| 61 |
+
true_length: Actual length of the non-padded sequence.
|
| 62 |
+
"""
|
| 63 |
+
if prefill_lengths is None:
|
| 64 |
+
prefill_lengths = [
|
| 65 |
+
16,
|
| 66 |
+
32,
|
| 67 |
+
64,
|
| 68 |
+
128,
|
| 69 |
+
256,
|
| 70 |
+
512,
|
| 71 |
+
1024,
|
| 72 |
+
2048,
|
| 73 |
+
4096,
|
| 74 |
+
8192,
|
| 75 |
+
16384,
|
| 76 |
+
32768,
|
| 77 |
+
]
|
| 78 |
+
if max_prefill_length is not None:
|
| 79 |
+
prefill_lengths = prefill_lengths[
|
| 80 |
+
: prefill_lengths.index(max_prefill_length)
|
| 81 |
+
] + [
|
| 82 |
+
max_prefill_length,
|
| 83 |
+
]
|
| 84 |
+
tokens = np.array(vocab.encode_tf(s)) # [Length]
|
| 85 |
+
# Add a beginning of sequence token if this is the beginning.
|
| 86 |
+
if is_bos:
|
| 87 |
+
tokens = np.concatenate(
|
| 88 |
+
[
|
| 89 |
+
np.array([
|
| 90 |
+
bos_id,
|
| 91 |
+
]),
|
| 92 |
+
tokens,
|
| 93 |
+
],
|
| 94 |
+
axis=-1,
|
| 95 |
+
)
|
| 96 |
+
true_length = tokens.shape[-1]
|
| 97 |
+
padded_length = take_nearest_length(prefill_lengths, true_length)
|
| 98 |
+
padding = padded_length - true_length
|
| 99 |
+
assert pad_id == 0, 'Further logic required if pad_id not 0.'
|
| 100 |
+
if padding < 0:
|
| 101 |
+
logging.warning('Provided sequence longer than available.')
|
| 102 |
+
# Take the last N tokens if we have too many.
|
| 103 |
+
padded_tokens = tokens[-padded_length:]
|
| 104 |
+
else:
|
| 105 |
+
padded_tokens = np.pad(tokens, (0, padding))
|
| 106 |
+
return jnp.array(padded_tokens), true_length
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def process_result_tokens(
|
| 110 |
+
slot: int,
|
| 111 |
+
slot_max_length: int,
|
| 112 |
+
result_tokens: engine_api.ResultTokens,
|
| 113 |
+
vocab: Vocabulary,
|
| 114 |
+
eos_id: int,
|
| 115 |
+
pad_id: int,
|
| 116 |
+
bos_id: int,
|
| 117 |
+
complete: np.ndarray,
|
| 118 |
+
debug: bool = False,
|
| 119 |
+
) -> Tuple[List[str], np.ndarray]:
|
| 120 |
+
"""Processes a result tokens into a list of strings, handling multiple samples.
|
| 121 |
+
|
| 122 |
+
Args:
|
| 123 |
+
slot: The slot at which to draw tokens from.
|
| 124 |
+
slot_max_length: Max length for a sample in the slot.
|
| 125 |
+
result_tokens: The tokens to access by slot.
|
| 126 |
+
vocab: For the detokenizer.
|
| 127 |
+
complete: Array representing the completion status of each sample in the
|
| 128 |
+
slot.
|
| 129 |
+
debug: Whether to log step by step detokenisation.
|
| 130 |
+
|
| 131 |
+
Returns:
|
| 132 |
+
sample_return: List of strings, one per sample.
|
| 133 |
+
complete: Updated complete.
|
| 134 |
+
"""
|
| 135 |
+
# tokens: [samples, speculations]
|
| 136 |
+
slot_data = result_tokens.get_result_at_slot(slot)
|
| 137 |
+
slot_tokens = slot_data.tokens
|
| 138 |
+
slot_valid = slot_data.valid
|
| 139 |
+
slot_lengths = slot_data.lengths
|
| 140 |
+
samples, speculations = slot_tokens.shape
|
| 141 |
+
stop_tokens = [eos_id, pad_id]
|
| 142 |
+
# Stop anything which has reached it's max length.
|
| 143 |
+
complete = complete | (slot_lengths > slot_max_length)
|
| 144 |
+
if debug:
|
| 145 |
+
logging.info(
|
| 146 |
+
'Complete %s, slot_tokens: %s, slot_lengths: %s',
|
| 147 |
+
complete.__str__(),
|
| 148 |
+
slot_tokens.__str__(),
|
| 149 |
+
slot_lengths.__str__(),
|
| 150 |
+
)
|
| 151 |
+
sample_return = []
|
| 152 |
+
for idx in range(samples):
|
| 153 |
+
string_so_far = ''
|
| 154 |
+
if not complete[idx].item():
|
| 155 |
+
for spec_idx in range(speculations):
|
| 156 |
+
tok_id = slot_tokens[idx, spec_idx].item()
|
| 157 |
+
valid = slot_valid[idx, spec_idx].item()
|
| 158 |
+
if debug:
|
| 159 |
+
logging.info(
|
| 160 |
+
'Sample idx: %d Speculation idx: %d Token: %d',
|
| 161 |
+
idx,
|
| 162 |
+
spec_idx,
|
| 163 |
+
tok_id,
|
| 164 |
+
)
|
| 165 |
+
if tok_id in stop_tokens or not valid:
|
| 166 |
+
complete[idx] = True
|
| 167 |
+
break
|
| 168 |
+
else:
|
| 169 |
+
try:
|
| 170 |
+
token = vocab.tokenizer.IdToPiece(tok_id) # pytype: disable=attribute-error
|
| 171 |
+
# ▁ or _ encodes a blank space.
|
| 172 |
+
token = token.replace('▁', ' ').replace('_', ' ')
|
| 173 |
+
except ValueError:
|
| 174 |
+
# This error only occurs when using tests where the vocab range is
|
| 175 |
+
# computed via addition and int->char is computed using chr(). Real
|
| 176 |
+
# models have vocab logits which are at max the size of the vocab.
|
| 177 |
+
logging.warning('%d exceeded vocab range', tok_id)
|
| 178 |
+
token = '<sampled_outside_vocab>'
|
| 179 |
+
string_so_far += token
|
| 180 |
+
sample_return.append(string_so_far)
|
| 181 |
+
if debug:
|
| 182 |
+
logging.info('Sampled return %s', sample_return.__str__())
|
| 183 |
+
return sample_return, complete
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def load_vocab(path: str, extra_ids: int = 0) -> Vocabulary:
|
| 187 |
+
"""Eagerly loads a vocabulary.
|
| 188 |
+
|
| 189 |
+
Args:
|
| 190 |
+
path: Vocabulary file path.
|
| 191 |
+
extra_ids: Number of extra IDs.
|
| 192 |
+
|
| 193 |
+
Returns:
|
| 194 |
+
A seqio Vocabulary.
|
| 195 |
+
"""
|
| 196 |
+
if path == 'test':
|
| 197 |
+
return mock_utils.TestVocab()
|
| 198 |
+
else:
|
| 199 |
+
vocab = SentencePieceVocabulary(
|
| 200 |
+
path,
|
| 201 |
+
extra_ids=extra_ids,
|
| 202 |
+
)
|
| 203 |
+
# SentencePieceVocabulary uses lazy loading. Request access to a property,
|
| 204 |
+
# forcing the lazy loading to happen now.
|
| 205 |
+
sp_model = vocab.sp_model
|
| 206 |
+
del sp_model
|
| 207 |
+
return vocab
|
maxtext-setup/jetstream/build/lib/jetstream/engine/tokenizer_pb2.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
# -*- coding: utf-8 -*-
|
| 16 |
+
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
| 17 |
+
# source: jetstream/engine/tokenizer.proto
|
| 18 |
+
# Protobuf Python Version: 4.25.1
|
| 19 |
+
"""Generated protocol buffer code."""
|
| 20 |
+
from google.protobuf import descriptor as _descriptor
|
| 21 |
+
from google.protobuf import descriptor_pool as _descriptor_pool
|
| 22 |
+
from google.protobuf import symbol_database as _symbol_database
|
| 23 |
+
from google.protobuf.internal import builder as _builder
|
| 24 |
+
# @@protoc_insertion_point(imports)
|
| 25 |
+
|
| 26 |
+
_sym_db = _symbol_database.Default()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n jetstream/engine/tokenizer.proto\x12\x06\x65ngine\"6\n\x13TokenizerParameters\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x11\n\textra_ids\x18\x02 \x01(\x05\x42\x02P\x01\x62\x06proto3')
|
| 32 |
+
|
| 33 |
+
_globals = globals()
|
| 34 |
+
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
|
| 35 |
+
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'jetstream.engine.tokenizer_pb2', _globals)
|
| 36 |
+
if _descriptor._USE_C_DESCRIPTORS == False:
|
| 37 |
+
_globals['DESCRIPTOR']._options = None
|
| 38 |
+
_globals['DESCRIPTOR']._serialized_options = b'P\001'
|
| 39 |
+
_globals['_TOKENIZERPARAMETERS']._serialized_start=44
|
| 40 |
+
_globals['_TOKENIZERPARAMETERS']._serialized_end=98
|
| 41 |
+
# @@protoc_insertion_point(module_scope)
|
maxtext-setup/jetstream/build/lib/jetstream/engine/tokenizer_pb2_grpc.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
|
| 16 |
+
"""Client and server classes corresponding to protobuf-defined services."""
|
| 17 |
+
import grpc
|
| 18 |
+
|
maxtext-setup/jetstream/build/lib/jetstream/engine/utils_test.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Tests functionality of the token processing utils using mock engine vocab."""
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
from jetstream.engine import engine_api
|
| 19 |
+
from jetstream.engine import mock_utils
|
| 20 |
+
from jetstream.engine import token_utils
|
| 21 |
+
from absl.testing import absltest
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class UtilsTest(absltest.TestCase):
|
| 25 |
+
|
| 26 |
+
def test_speculations_with_multi_sample_slots(self, samples_per_slot=2):
|
| 27 |
+
# [4, 1]
|
| 28 |
+
mock_tokens = np.array([
|
| 29 |
+
[0, ord('A')],
|
| 30 |
+
[ord('A'), ord('D')],
|
| 31 |
+
[ord('T'), ord('3')],
|
| 32 |
+
[ord('A'), 1],
|
| 33 |
+
]).astype(np.int32)
|
| 34 |
+
mock_valid_tokens = np.ones_like(mock_tokens, dtype=np.int32)
|
| 35 |
+
mock_lengths = np.ones(mock_tokens.shape[0], dtype=np.int32)*2
|
| 36 |
+
# completion is 'per slot' because we track it for a given request.
|
| 37 |
+
mock_complete = np.zeros(
|
| 38 |
+
(mock_tokens.shape[0] // samples_per_slot), dtype=np.int32
|
| 39 |
+
)
|
| 40 |
+
data = np.concatenate(
|
| 41 |
+
[
|
| 42 |
+
mock_tokens,
|
| 43 |
+
mock_valid_tokens,
|
| 44 |
+
mock_lengths[:, None],
|
| 45 |
+
],
|
| 46 |
+
axis=-1,
|
| 47 |
+
)
|
| 48 |
+
speculations = mock_tokens.shape[1]
|
| 49 |
+
result_tokens = engine_api.ResultTokens(
|
| 50 |
+
data=data.astype(np.int32),
|
| 51 |
+
tokens_idx=(0, speculations),
|
| 52 |
+
valid_idx=(speculations, 2 * speculations),
|
| 53 |
+
length_idx=(2 * speculations, 2 * speculations + 1),
|
| 54 |
+
samples_per_slot=2,
|
| 55 |
+
)
|
| 56 |
+
per_channel, complete = token_utils.process_result_tokens(
|
| 57 |
+
slot=0,
|
| 58 |
+
slot_max_length=4,
|
| 59 |
+
result_tokens=result_tokens,
|
| 60 |
+
vocab=mock_utils.TestVocab(),
|
| 61 |
+
complete=mock_complete,
|
| 62 |
+
)
|
| 63 |
+
np.testing.assert_equal(complete, np.array([1, 0]))
|
| 64 |
+
|
| 65 |
+
assert not per_channel[0] # i.e. == '', because of the pad.
|
| 66 |
+
assert per_channel[1] == 'AD'
|
| 67 |
+
mock_complete = np.zeros(
|
| 68 |
+
(mock_tokens.shape[0] // samples_per_slot), dtype=np.int32
|
| 69 |
+
)
|
| 70 |
+
per_channel, complete = token_utils.process_result_tokens(
|
| 71 |
+
slot=1,
|
| 72 |
+
slot_max_length=4,
|
| 73 |
+
result_tokens=result_tokens,
|
| 74 |
+
vocab=mock_utils.TestVocab(),
|
| 75 |
+
complete=mock_complete,
|
| 76 |
+
)
|
| 77 |
+
assert per_channel[0] == 'T3'
|
| 78 |
+
assert per_channel[1] == 'A' # second token is padded.
|
| 79 |
+
np.testing.assert_equal(complete, np.array([0, 1]))
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
if __name__ == '__main__':
|
| 83 |
+
absltest.main()
|
maxtext-setup/jetstream/google_jetstream.egg-info/PKG-INFO
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: google-jetstream
|
| 3 |
+
Version: 0.1.1
|
| 4 |
+
Summary: A throughput and memory optimized engine for LLM inference on TPU and GPU.
|
| 5 |
+
Home-page: https://github.com/google/JetStream
|
| 6 |
+
Author: Google LLC
|
| 7 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 8 |
+
Classifier: License :: OSI Approved :: Apache Software License
|
| 9 |
+
Classifier: Operating System :: OS Independent
|
| 10 |
+
Requires-Python: >=3.10
|
| 11 |
+
Description-Content-Type: text/markdown
|
| 12 |
+
License-File: LICENSE
|
| 13 |
+
License-File: AUTHORS
|
| 14 |
+
|
| 15 |
+
# JetStream - A throughput and memory optimized engine for LLM inference on TPU and GPU
|
| 16 |
+
|
| 17 |
+
## About
|
| 18 |
+
|
| 19 |
+
JetStream is a fast library for LLM inference and serving on TPU and GPU.
|
| 20 |
+
|
| 21 |
+
## Getting Started
|
| 22 |
+
|
| 23 |
+
### Run local server & Testing
|
| 24 |
+
|
| 25 |
+
Use the following commands to run a server locally:
|
| 26 |
+
```
|
| 27 |
+
# Start a server
|
| 28 |
+
python -m jetstream.core.implementations.mock.server
|
| 29 |
+
|
| 30 |
+
# Test local mock server
|
| 31 |
+
python -m jetstream.core.tools.requester
|
| 32 |
+
|
| 33 |
+
# Load test local mock server
|
| 34 |
+
python -m jetstream.core.tools.load_tester
|
| 35 |
+
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
### Test core modules
|
| 39 |
+
```
|
| 40 |
+
# Test JetStream core orchestrator
|
| 41 |
+
python -m jetstream.core.orchestrator_test
|
| 42 |
+
|
| 43 |
+
# Test JetStream core server library
|
| 44 |
+
python -m jetstream.core.server_test
|
| 45 |
+
|
| 46 |
+
# Test mock JetStream engine implementation
|
| 47 |
+
python -m jetstream.engine.mock_engine_test
|
| 48 |
+
|
| 49 |
+
# Test mock JetStream token utils
|
| 50 |
+
python -m jetstream.engine.utils_test
|
| 51 |
+
|
| 52 |
+
```
|
maxtext-setup/jetstream/google_jetstream.egg-info/SOURCES.txt
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
AUTHORS
|
| 2 |
+
LICENSE
|
| 3 |
+
README.md
|
| 4 |
+
setup.py
|
| 5 |
+
google_jetstream.egg-info/PKG-INFO
|
| 6 |
+
google_jetstream.egg-info/SOURCES.txt
|
| 7 |
+
google_jetstream.egg-info/dependency_links.txt
|
| 8 |
+
google_jetstream.egg-info/requires.txt
|
| 9 |
+
google_jetstream.egg-info/top_level.txt
|
| 10 |
+
jetstream/__init__.py
|
| 11 |
+
jetstream/core/__init__.py
|
| 12 |
+
jetstream/core/config_lib.py
|
| 13 |
+
jetstream/core/orchestrator.py
|
| 14 |
+
jetstream/core/orchestrator_test.py
|
| 15 |
+
jetstream/core/server_lib.py
|
| 16 |
+
jetstream/core/server_test.py
|
| 17 |
+
jetstream/core/implementations/__init__.py
|
| 18 |
+
jetstream/core/implementations/mock/__init__.py
|
| 19 |
+
jetstream/core/implementations/mock/config.py
|
| 20 |
+
jetstream/core/implementations/mock/server.py
|
| 21 |
+
jetstream/core/proto/__init__.py
|
| 22 |
+
jetstream/core/proto/jetstream_pb2.py
|
| 23 |
+
jetstream/core/proto/jetstream_pb2_grpc.py
|
| 24 |
+
jetstream/engine/__init__.py
|
| 25 |
+
jetstream/engine/engine_api.py
|
| 26 |
+
jetstream/engine/mock_engine.py
|
| 27 |
+
jetstream/engine/mock_engine_test.py
|
| 28 |
+
jetstream/engine/mock_utils.py
|
| 29 |
+
jetstream/engine/token_utils.py
|
| 30 |
+
jetstream/engine/tokenizer_pb2.py
|
| 31 |
+
jetstream/engine/tokenizer_pb2_grpc.py
|
| 32 |
+
jetstream/engine/utils_test.py
|
maxtext-setup/jetstream/google_jetstream.egg-info/dependency_links.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
maxtext-setup/jetstream/google_jetstream.egg-info/requires.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
absl-py
|
| 2 |
+
flax
|
| 3 |
+
grpcio
|
| 4 |
+
jax
|
| 5 |
+
jaxlib
|
| 6 |
+
portpicker
|
| 7 |
+
numpy
|
| 8 |
+
seqio
|
maxtext-setup/jetstream/google_jetstream.egg-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
jetstream
|
maxtext-setup/jetstream/jetstream/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
maxtext-setup/jetstream/jetstream/core/README.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# JetStream core Subpackage - Server and Library that support continuous batching serving.
|
| 2 |
+
|
| 3 |
+
Interleaved mode: Provide continuous batching to optimize inference. Uses JAX directy on single-host TPU.
|
maxtext-setup/jetstream/jetstream/core/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
maxtext-setup/jetstream/jetstream/core/config_lib.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Configs of engines for the orchestrator to load."""
|
| 16 |
+
|
| 17 |
+
import dataclasses
|
| 18 |
+
import functools
|
| 19 |
+
import math
|
| 20 |
+
from typing import Any, Callable, List, Tuple, Type
|
| 21 |
+
|
| 22 |
+
from jetstream.engine import engine_api
|
| 23 |
+
from jetstream.engine import mock_engine
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
Devices = Any
|
| 27 |
+
|
| 28 |
+
CreateEngineFn = Callable[[Devices], engine_api.Engine]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclasses.dataclass
|
| 32 |
+
class ServerConfig:
|
| 33 |
+
"""Configs for slices to put engines on."""
|
| 34 |
+
|
| 35 |
+
prefill_slices: Tuple[str, ...] = ()
|
| 36 |
+
generate_slices: Tuple[str, ...] = ()
|
| 37 |
+
interleaved_slices: Tuple[str, ...] = ()
|
| 38 |
+
prefill_engine_create_fns: Tuple[CreateEngineFn, ...] = ()
|
| 39 |
+
generate_engine_create_fns: Tuple[CreateEngineFn, ...] = ()
|
| 40 |
+
interleaved_engine_create_fns: Tuple[CreateEngineFn, ...] = ()
|
| 41 |
+
|
| 42 |
+
def get_slices_to_launch(self: 'ServerConfig') -> str:
|
| 43 |
+
"""Used when launching this config via xm config."""
|
| 44 |
+
return ','.join(
|
| 45 |
+
self.prefill_slices + self.generate_slices + self.interleaved_slices
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@dataclasses.dataclass
|
| 50 |
+
class InstantiatedEngines:
|
| 51 |
+
prefill_engines: List[engine_api.Engine]
|
| 52 |
+
generate_engines: List[engine_api.Engine]
|
| 53 |
+
interleaved_engines: List[engine_api.Engine]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼#
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def get_test_engine(devices: Devices, weight: int) -> engine_api.Engine:
|
| 60 |
+
del devices
|
| 61 |
+
return mock_engine.TestEngine(
|
| 62 |
+
batch_size=8,
|
| 63 |
+
cache_length=32,
|
| 64 |
+
weight=weight,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@dataclasses.dataclass
|
| 69 |
+
class CPUTestServer(ServerConfig):
|
| 70 |
+
prefill_slices = ('cpu=1',)
|
| 71 |
+
generate_slices = ('cpu=1',)
|
| 72 |
+
prefill_engine_create_fns = (functools.partial(get_test_engine, weight=2),)
|
| 73 |
+
generate_engine_create_fns = (functools.partial(get_test_engine, weight=4),)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@dataclasses.dataclass
|
| 77 |
+
class InterleavedCPUTestServer(ServerConfig):
|
| 78 |
+
interleaved_slices = ('cpu=1',)
|
| 79 |
+
interleaved_engine_create_fns = (
|
| 80 |
+
functools.partial(get_test_engine, weight=2),
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼#
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def slice_to_num_chips(s: str) -> int:
|
| 88 |
+
"""Converts a TPU spec like v5e=4x2 to the number of chips, 8."""
|
| 89 |
+
# Account for the case where it is written 'v5e:4x2'.
|
| 90 |
+
delim = '=' if '=' in s else ':'
|
| 91 |
+
i = math.prod([int(c) for c in s.split(delim)[1].split('x')])
|
| 92 |
+
return i
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _split_devices_by_slices(
|
| 96 |
+
devices: list[Devices], slices: list[int]
|
| 97 |
+
) -> List[List[Devices]]:
|
| 98 |
+
"""Converts an ordered list of devices into slices."""
|
| 99 |
+
assert sum(slices) == len(devices), f'{sum(slices)} != {len(devices)}'
|
| 100 |
+
cumsum = 0
|
| 101 |
+
slice_split_devices = []
|
| 102 |
+
for sl in slices:
|
| 103 |
+
slice_split_devices.append(devices[cumsum : cumsum + sl])
|
| 104 |
+
cumsum += sl
|
| 105 |
+
return slice_split_devices
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def get_engines(
|
| 109 |
+
server_config: Type[ServerConfig], devices: List[Devices]
|
| 110 |
+
) -> InstantiatedEngines:
|
| 111 |
+
"""Processes config to get the appropriate engines.
|
| 112 |
+
|
| 113 |
+
Args:
|
| 114 |
+
server_config: ServerConfig.
|
| 115 |
+
devices: Device objects.
|
| 116 |
+
|
| 117 |
+
Returns:
|
| 118 |
+
Instantiated engines!
|
| 119 |
+
|
| 120 |
+
Devices are popped in order!
|
| 121 |
+
"""
|
| 122 |
+
# Now, we need to split devices by slice due to TPU backend config.
|
| 123 |
+
slices: list[int] = [
|
| 124 |
+
slice_to_num_chips(s)
|
| 125 |
+
for s in list(server_config.prefill_slices)
|
| 126 |
+
+ list(server_config.generate_slices)
|
| 127 |
+
+ list(server_config.interleaved_slices)
|
| 128 |
+
]
|
| 129 |
+
if sum(slices) != len(devices):
|
| 130 |
+
raise ValueError(
|
| 131 |
+
f'The number of available devices ({len(devices)}) do not match the '
|
| 132 |
+
f'expected number of devices on all the slices ({sum(slices)}) '
|
| 133 |
+
'specified in the server_config:\n'
|
| 134 |
+
f'{server_config.prefill_slices=}\n'
|
| 135 |
+
f'{server_config.generate_slices=}\n'
|
| 136 |
+
f'{server_config.interleaved_slices=}\n'
|
| 137 |
+
)
|
| 138 |
+
# e.g. [[tpu_0], [tpu_1]] corresponding to prefill: v5e=1x1
|
| 139 |
+
# generate = v5e=1x1; or [[tpu_0, tpu_1, tpu_2, tpu_3]] corresponding to
|
| 140 |
+
# interleaved: v5e=2x2
|
| 141 |
+
split_devices = _split_devices_by_slices(devices, slices)
|
| 142 |
+
prefill_engines = [
|
| 143 |
+
e(split_devices.pop(0)) for e in server_config.prefill_engine_create_fns
|
| 144 |
+
]
|
| 145 |
+
generate_engines = [
|
| 146 |
+
e(split_devices.pop(0)) for e in server_config.generate_engine_create_fns
|
| 147 |
+
]
|
| 148 |
+
# These share chips and weights for prefill and generation.
|
| 149 |
+
interleaved_engines = [
|
| 150 |
+
e(split_devices.pop(0))
|
| 151 |
+
for e in server_config.interleaved_engine_create_fns
|
| 152 |
+
]
|
| 153 |
+
return InstantiatedEngines(
|
| 154 |
+
prefill_engines, generate_engines, interleaved_engines
|
| 155 |
+
)
|
maxtext-setup/jetstream/jetstream/core/implementations/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
maxtext-setup/jetstream/jetstream/core/implementations/mock/README.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Mock server
|
| 2 |
+
|
| 3 |
+
Implements Mock JetStream core with mock model config.
|
maxtext-setup/jetstream/jetstream/core/implementations/mock/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
maxtext-setup/jetstream/jetstream/core/implementations/mock/config.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Config for mock."""
|
| 16 |
+
|
| 17 |
+
from typing import Type
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
from jetstream.core import config_lib
|
| 21 |
+
|
| 22 |
+
def get_server_config(config_str: str) -> Type[config_lib.ServerConfig]:
|
| 23 |
+
match config_str:
|
| 24 |
+
case 'InterleavedCPUTestServer':
|
| 25 |
+
server_config = config_lib.InterleavedCPUTestServer
|
| 26 |
+
case 'CPUTestServer':
|
| 27 |
+
server_config = config_lib.CPUTestServer
|
| 28 |
+
case _:
|
| 29 |
+
raise NotImplementedError
|
| 30 |
+
return server_config
|
maxtext-setup/jetstream/jetstream/core/implementations/mock/server.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Runs a mock server."""
|
| 16 |
+
|
| 17 |
+
from typing import Sequence
|
| 18 |
+
|
| 19 |
+
from absl import app
|
| 20 |
+
from absl import flags
|
| 21 |
+
|
| 22 |
+
from jetstream.core.implementations.mock import config as mock_config
|
| 23 |
+
from jetstream.core import server_lib
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
_PORT = flags.DEFINE_integer('port', 9000, 'port to listen on')
|
| 27 |
+
_CONFIG = flags.DEFINE_string(
|
| 28 |
+
'config',
|
| 29 |
+
'InterleavedCPUTestServer',
|
| 30 |
+
'available servers',
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
def main(argv: Sequence[str]):
|
| 34 |
+
del argv
|
| 35 |
+
# No devices for local cpu test. A None for prefill and a None for generate.
|
| 36 |
+
devices = server_lib.get_devices()
|
| 37 |
+
server_config = mock_config.get_server_config(_CONFIG.value)
|
| 38 |
+
# We separate credential from run so that we can unit test it with local credentials.
|
| 39 |
+
# TODO: Add grpc credentials for OSS.
|
| 40 |
+
jetstream_server = server_lib.run(
|
| 41 |
+
port=_PORT.value,
|
| 42 |
+
config=server_config,
|
| 43 |
+
devices=devices,
|
| 44 |
+
)
|
| 45 |
+
jetstream_server.wait_for_termination()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if __name__ == '__main__':
|
| 49 |
+
app.run(main)
|
maxtext-setup/jetstream/jetstream/core/orchestrator.py
ADDED
|
@@ -0,0 +1,651 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Orchestrates the engines for the inference workflow with performance optimization.
|
| 16 |
+
|
| 17 |
+
1. A client sends a DecodeRequest via gRPC to the server, an 'LLMOrchestrator'.
|
| 18 |
+
2. This gets wrapped as an 'ActiveRequest' inside the orchestrator, with a
|
| 19 |
+
'return_channel' queue as a place that output tokens can be placed.
|
| 20 |
+
- The ActiveRequest is placed on the 'prefill_queue'.
|
| 21 |
+
- A while loop runs continuously, yielding any tokens placed on the return
|
| 22 |
+
channel until an end condition is met (EOS token or max tokens).
|
| 23 |
+
3. There is a prefill_thread per prefill_engine, each of which runs on a
|
| 24 |
+
distinct prefill_slice.
|
| 25 |
+
4. There is a generate_thread per generate_engine, each of which runs on a
|
| 26 |
+
distinct generate_slice.
|
| 27 |
+
5. Within a prefill thread:
|
| 28 |
+
- It attempts to pop ActiveRequests off the prefill_queue.
|
| 29 |
+
- It tokenizes the request.
|
| 30 |
+
- When successful, it performs a prefill operation, transfers the kv cache
|
| 31 |
+
to the generation slice and pops this information (still wrapped in the
|
| 32 |
+
same ActiveRequest) onto the generation queue.
|
| 33 |
+
6. Within a generation thread:
|
| 34 |
+
- There is a queue of integers representing 'available slots'.
|
| 35 |
+
- It checks if there is something on both the slots_queue and generation_
|
| 36 |
+
queue.
|
| 37 |
+
- If so, the kv_cache associated with that request into the decoding state
|
| 38 |
+
of the generation loop at the relevant slot.
|
| 39 |
+
- Regardless, it performs a step.
|
| 40 |
+
- It takes the sampled tokens, and places them on a 'detokenizing_queue'.
|
| 41 |
+
7. Within the detokenizing thread:
|
| 42 |
+
- Tokens are detokenized for every 'slot' in a given set of sampled tokens.
|
| 43 |
+
- When an end condition is met, the 'slot' integer is returned to the
|
| 44 |
+
respective generation queue.
|
| 45 |
+
- This does mean that a single generation step may run after detokenizing
|
| 46 |
+
indicates that row is no longer valid (if the detokenizing is running behind
|
| 47 |
+
generation steps), this is fine as it avoids detokenizing being blocking of
|
| 48 |
+
the generate thread.
|
| 49 |
+
|
| 50 |
+
If you haven't worked with concurrency in python before - queues are thread-safe
|
| 51 |
+
by default, so we can happily use them to transfer pointers to data between
|
| 52 |
+
different processes. The structure of this server is simple as a result - a
|
| 53 |
+
thread for each thing we might want to do (prefill, transfer, generate,
|
| 54 |
+
detokenize), and corresponding queues that an active request is passed between.
|
| 55 |
+
The same goes for the 'return_channel' of the request itself, where we can just
|
| 56 |
+
pop tokens once they are done and try to pop them back to transmit them over
|
| 57 |
+
grpc.
|
| 58 |
+
It is literally queues all the way down! :)
|
| 59 |
+
The primary concern is GIL contention between threads, which is why we block
|
| 60 |
+
on queues that don't have an ongoing activity (i.e. everything but the
|
| 61 |
+
generation queue) because we don't control to go back to those queues until
|
| 62 |
+
necessary. Blocking means that the GIL doesn't switch back to that thread,
|
| 63 |
+
wheras continual queue get operations 'chop' control and mean that we do not
|
| 64 |
+
achieve good throughput. This is okay on the prefill/transfer/detokenisation
|
| 65 |
+
threads because we don't need to do anything other than react to the presence
|
| 66 |
+
of items on these queues, wheras the generation thread needs to also run a
|
| 67 |
+
step - so it cannot block until it has new things to insert.
|
| 68 |
+
|
| 69 |
+
## Testing
|
| 70 |
+
This server is intended to be easy to locally test.
|
| 71 |
+
|
| 72 |
+
Either use :orchestrator test, which tests the multi-threading components,
|
| 73 |
+
:server_test, which extends this to test grpc_components, or run it locally
|
| 74 |
+
to debug hangs due to bugs in threads (it is easier to debug with live logs).
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
import dataclasses
|
| 78 |
+
import functools
|
| 79 |
+
import itertools
|
| 80 |
+
import logging
|
| 81 |
+
import os
|
| 82 |
+
import queue
|
| 83 |
+
import signal
|
| 84 |
+
import sys
|
| 85 |
+
import threading
|
| 86 |
+
import time
|
| 87 |
+
import traceback
|
| 88 |
+
import json
|
| 89 |
+
from typing import Any, Iterable, Optional, Union
|
| 90 |
+
|
| 91 |
+
import grpc
|
| 92 |
+
import jax
|
| 93 |
+
from jetstream.core.proto import jetstream_pb2
|
| 94 |
+
from jetstream.core.proto import jetstream_pb2_grpc
|
| 95 |
+
from jetstream.engine import engine_api
|
| 96 |
+
from jetstream.engine import token_utils
|
| 97 |
+
import numpy as np
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
root = logging.getLogger()
|
| 101 |
+
root.setLevel(logging.DEBUG)
|
| 102 |
+
|
| 103 |
+
handler = logging.StreamHandler(sys.stdout)
|
| 104 |
+
handler.setLevel(logging.DEBUG)
|
| 105 |
+
formatter = logging.Formatter(
|
| 106 |
+
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 107 |
+
)
|
| 108 |
+
handler.setFormatter(formatter)
|
| 109 |
+
root.addHandler(handler)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def delete_pytree(p):
|
| 113 |
+
def delete_leaf(leaf):
|
| 114 |
+
if isinstance(leaf, jax.Array):
|
| 115 |
+
leaf.delete()
|
| 116 |
+
del leaf
|
| 117 |
+
|
| 118 |
+
jax.tree_map(delete_leaf, p)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@dataclasses.dataclass
|
| 122 |
+
class ActiveRequest:
|
| 123 |
+
"""Current state of the driver."""
|
| 124 |
+
|
| 125 |
+
#################### Information relevant for generation #####################
|
| 126 |
+
max_tokens: int
|
| 127 |
+
vocab: str
|
| 128 |
+
# [num_samples,] which corresponds to whether each sample is complete for the
|
| 129 |
+
# requests.
|
| 130 |
+
complete: Optional[np.ndarray] = None
|
| 131 |
+
prefill_result: Any = None
|
| 132 |
+
#################### Information relevant for prefill ########################
|
| 133 |
+
history_path: Optional[str] = None
|
| 134 |
+
prefill_text: Optional[str] = None
|
| 135 |
+
################## Information relevant for detokenisation ###################
|
| 136 |
+
# Which generate step this was added at.
|
| 137 |
+
generate_timestep_added: Optional[int] = None
|
| 138 |
+
# We keep prefill and decode information together in the same object so that
|
| 139 |
+
# there is less indirection about where this return channel is.
|
| 140 |
+
# The return channel returns a list of strings, one per sample for that query.
|
| 141 |
+
return_channel: queue.Queue[list[str]] = dataclasses.field(
|
| 142 |
+
default_factory=queue.Queue
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
def next(self: 'ActiveRequest'):
|
| 146 |
+
"""Blocks until the next token is available, call from RPC threads."""
|
| 147 |
+
return self.return_channel.get()
|
| 148 |
+
|
| 149 |
+
def enqueue_tokens(self, generated_tokens: list[str]):
|
| 150 |
+
"""Records information about the step.
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
generated_tokens: One token to put into the return channel
|
| 154 |
+
|
| 155 |
+
This should be called only from within the Drivers background thread.
|
| 156 |
+
"""
|
| 157 |
+
self.return_channel.put(generated_tokens)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class JetThread(threading.Thread):
|
| 161 |
+
"""Thread that kills the program if it fails.
|
| 162 |
+
|
| 163 |
+
If a driver thread goes down, we can't operate.
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
def run(self):
|
| 167 |
+
try:
|
| 168 |
+
super().run()
|
| 169 |
+
except Exception as e: # pylint: disable=broad-exception-caught
|
| 170 |
+
print(f'Thread {self.name} encountered an error: {e}')
|
| 171 |
+
traceback.print_exc()
|
| 172 |
+
os.kill(os.getpid(), signal.SIGKILL)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _abort_or_raise(
|
| 176 |
+
context: grpc.ServicerContext | None, code: grpc.StatusCode, details: str
|
| 177 |
+
):
|
| 178 |
+
"""Safely aborts a gRPC context if available, or raises an Exception."""
|
| 179 |
+
if context is None:
|
| 180 |
+
raise RuntimeError(details)
|
| 181 |
+
|
| 182 |
+
context.abort(code, details)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
class Driver:
|
| 186 |
+
"""Drives the engines."""
|
| 187 |
+
|
| 188 |
+
_prefill_engines: list[engine_api.Engine]
|
| 189 |
+
_generate_engines: list[engine_api.Engine]
|
| 190 |
+
# Allows us to pre-load the params, primarily so that we can iterate quickly
|
| 191 |
+
# on the driver in colab without reloading weights.
|
| 192 |
+
_prefill_params: Optional[dict[int, Any]] = {}
|
| 193 |
+
_generate_params: Optional[dict[int, Any]] = {}
|
| 194 |
+
# Stage 1
|
| 195 |
+
_prefill_backlog: queue.Queue[ActiveRequest | None]
|
| 196 |
+
# Stage 2
|
| 197 |
+
# We keep this as a dict to avoid a possibly expensive object comparison
|
| 198 |
+
# when logging the index of the generate engine we send a prefill result
|
| 199 |
+
# to, it allows us to natively have the index from the min operation, rather
|
| 200 |
+
# than have to call .index()
|
| 201 |
+
_generate_backlogs: dict[int, queue.Queue[ActiveRequest | None]] = {}
|
| 202 |
+
# Stage 3
|
| 203 |
+
# This can be a list because we can pass it as an arg to generate and
|
| 204 |
+
# detokenize threads. It is a list of tokens to be detokenized.
|
| 205 |
+
_detokenize_backlogs: list[queue.Queue[engine_api.ResultTokens]] = []
|
| 206 |
+
_generate_slots: list[queue.Queue[int]] = []
|
| 207 |
+
_active_requests: list[queue.Queue[tuple[int, ActiveRequest | None]]] = []
|
| 208 |
+
|
| 209 |
+
def __init__(
|
| 210 |
+
self,
|
| 211 |
+
prefill_engines=None,
|
| 212 |
+
generate_engines=None,
|
| 213 |
+
prefill_params=None,
|
| 214 |
+
generate_params=None,
|
| 215 |
+
):
|
| 216 |
+
logging.info(
|
| 217 |
+
'Initialising driver with %d prefill engines and %d generate engines.',
|
| 218 |
+
len(prefill_engines),
|
| 219 |
+
len(generate_engines),
|
| 220 |
+
)
|
| 221 |
+
self._prefill_engines = prefill_engines
|
| 222 |
+
self._generate_engines = generate_engines
|
| 223 |
+
self._prefill_params = prefill_params if prefill_params else {}
|
| 224 |
+
self._generate_params = generate_params if generate_params else {}
|
| 225 |
+
# Stages 1-4 represent the life cycle of a request.
|
| 226 |
+
# Stage 1
|
| 227 |
+
# At first, a request is placed here in order to get prefilled.
|
| 228 |
+
self._prefill_backlog = queue.Queue()
|
| 229 |
+
# Stage 2
|
| 230 |
+
# Each generate engine accesses its own generate backlog.
|
| 231 |
+
self._generate_backlogs = {
|
| 232 |
+
idx: queue.Queue() for idx, _ in enumerate(generate_engines)
|
| 233 |
+
}
|
| 234 |
+
# Stage 3
|
| 235 |
+
# After generation, ActiveRequests are placed on the detokenization backlog
|
| 236 |
+
# for tokens to be sent into each ActiveRequest's return channel.
|
| 237 |
+
# We have one of these per generate engine to simplify the logic keeping
|
| 238 |
+
# track of which generation engine to replace slots on.
|
| 239 |
+
# This is a queue of either - tuple[int, ActiveRequest] which represents our
|
| 240 |
+
# active requests, or tuple[int, sample_tokens]. We combine these into one
|
| 241 |
+
# queue because it allows us to be somewhat clever with how we do
|
| 242 |
+
# detokenization.
|
| 243 |
+
# If the detokenization receives an (int, ActiveRequest) this signifies
|
| 244 |
+
# that slot int should from now be placing tokens in the return channel of
|
| 245 |
+
# the ActiveRequest.
|
| 246 |
+
# If it receives (int, sample_tokens) then it actually
|
| 247 |
+
# does a detokenisation for any slots which have previously been set active
|
| 248 |
+
# via the previous kind of object, and the int is used to log which step
|
| 249 |
+
# the tokens were created at. By having them in one queue we prevent
|
| 250 |
+
# the possibility of race conditions where a slot is made live before the
|
| 251 |
+
# tokens are ready and it receives tokens from a different sequence,
|
| 252 |
+
# or tokens detokenized before the relevant slot is live.
|
| 253 |
+
self._detokenize_backlogs = [queue.Queue() for _ in generate_engines]
|
| 254 |
+
# Finally we have a queue that doesn't represent a stage, but tracks the
|
| 255 |
+
# internal status of a request within the generation loop.
|
| 256 |
+
# a) A queue of integers representing available 'slots' in the decode
|
| 257 |
+
# operation. I.e. potentially available rows in the batch and/or
|
| 258 |
+
# microbatch. When we want to insert a prefill result, we pop an integer
|
| 259 |
+
# to insert at. When this is empty, it means all slots are full.
|
| 260 |
+
|
| 261 |
+
# Construct a)
|
| 262 |
+
self._generate_slots = [queue.Queue() for _ in generate_engines]
|
| 263 |
+
_ = [
|
| 264 |
+
[
|
| 265 |
+
self._generate_slots[idx].put(i)
|
| 266 |
+
for i in range(engine.max_concurrent_decodes)
|
| 267 |
+
]
|
| 268 |
+
for idx, engine in enumerate(generate_engines)
|
| 269 |
+
]
|
| 270 |
+
|
| 271 |
+
# Kick off all our threads
|
| 272 |
+
self._prefill_threads = [
|
| 273 |
+
JetThread(
|
| 274 |
+
target=functools.partial(self._prefill_thread, idx, engine),
|
| 275 |
+
name=f'prefill-{idx}',
|
| 276 |
+
)
|
| 277 |
+
for idx, engine in enumerate(self._prefill_engines)
|
| 278 |
+
]
|
| 279 |
+
self._generate_threads = [
|
| 280 |
+
JetThread(
|
| 281 |
+
target=functools.partial(
|
| 282 |
+
self._generate_thread,
|
| 283 |
+
idx,
|
| 284 |
+
engine,
|
| 285 |
+
self._generate_slots[idx],
|
| 286 |
+
self._detokenize_backlogs[idx],
|
| 287 |
+
),
|
| 288 |
+
name=f'generate-{idx}',
|
| 289 |
+
)
|
| 290 |
+
for idx, engine in enumerate(self._generate_engines)
|
| 291 |
+
]
|
| 292 |
+
# Construct b)
|
| 293 |
+
self.detokenize_threads = [
|
| 294 |
+
JetThread(
|
| 295 |
+
target=functools.partial(
|
| 296 |
+
self._detokenize_thread,
|
| 297 |
+
idx,
|
| 298 |
+
engine,
|
| 299 |
+
self._generate_slots[idx],
|
| 300 |
+
self._detokenize_backlogs[idx],
|
| 301 |
+
),
|
| 302 |
+
name=f'detokenize-{idx}',
|
| 303 |
+
)
|
| 304 |
+
for idx, engine in enumerate(self._generate_engines)
|
| 305 |
+
]
|
| 306 |
+
self._all_threads = list(
|
| 307 |
+
itertools.chain(
|
| 308 |
+
self._prefill_threads,
|
| 309 |
+
self._generate_threads,
|
| 310 |
+
self.detokenize_threads,
|
| 311 |
+
)
|
| 312 |
+
)
|
| 313 |
+
self.live = True
|
| 314 |
+
# Kick off all threads
|
| 315 |
+
for t in self._all_threads:
|
| 316 |
+
t.start()
|
| 317 |
+
|
| 318 |
+
def stop(self):
|
| 319 |
+
"""Stops the driver and all background threads."""
|
| 320 |
+
# Signal to all threads that they should stop.
|
| 321 |
+
self.live = False
|
| 322 |
+
|
| 323 |
+
all_backlogs = list(
|
| 324 |
+
itertools.chain(
|
| 325 |
+
[self._prefill_backlog],
|
| 326 |
+
self._generate_backlogs.values(),
|
| 327 |
+
self._detokenize_backlogs,
|
| 328 |
+
)
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
while any(t.is_alive() for t in self._all_threads):
|
| 332 |
+
# Empty all backlogs and mark any remaining requests as cancelled.
|
| 333 |
+
for q in all_backlogs:
|
| 334 |
+
while True:
|
| 335 |
+
try:
|
| 336 |
+
r = q.get_nowait()
|
| 337 |
+
if r is None:
|
| 338 |
+
continue
|
| 339 |
+
elif isinstance(r, ActiveRequest):
|
| 340 |
+
r.return_channel = None
|
| 341 |
+
else: # detokenize backlog
|
| 342 |
+
_, r = r
|
| 343 |
+
if isinstance(r, ActiveRequest):
|
| 344 |
+
r.return_channel = None
|
| 345 |
+
except queue.Empty:
|
| 346 |
+
break
|
| 347 |
+
|
| 348 |
+
# Put sentinels to unblock threads.
|
| 349 |
+
for q in all_backlogs:
|
| 350 |
+
try:
|
| 351 |
+
q.put_nowait(None)
|
| 352 |
+
except queue.Full:
|
| 353 |
+
pass
|
| 354 |
+
|
| 355 |
+
# Wait for all threads to stop.
|
| 356 |
+
for t in self._all_threads:
|
| 357 |
+
t.join()
|
| 358 |
+
|
| 359 |
+
def get_total_concurrent_requests(self) -> int:
|
| 360 |
+
"""Returns the total number of concurrent requests the driver can service."""
|
| 361 |
+
# We don't support filling all backlogs at once because it can cause GIL
|
| 362 |
+
# contention.
|
| 363 |
+
total_max_concurrent_decodes = sum(
|
| 364 |
+
[e.max_concurrent_decodes for e in self._generate_engines]
|
| 365 |
+
)
|
| 366 |
+
return total_max_concurrent_decodes
|
| 367 |
+
|
| 368 |
+
def place_request_on_prefill_queue(self, request: ActiveRequest):
|
| 369 |
+
"""Used to place new requests for prefilling and generation."""
|
| 370 |
+
self._prefill_backlog.put(request)
|
| 371 |
+
|
| 372 |
+
def _load_cache_history(self, path: str) -> Union[None, Any]:
|
| 373 |
+
"""Loads previous kv cache for a longer conversation."""
|
| 374 |
+
if path:
|
| 375 |
+
raise NotImplementedError
|
| 376 |
+
else:
|
| 377 |
+
return None
|
| 378 |
+
|
| 379 |
+
def _prefill_thread(
|
| 380 |
+
self,
|
| 381 |
+
idx: int,
|
| 382 |
+
prefill_engine: engine_api.Engine,
|
| 383 |
+
generate_backpressure: int = 3,
|
| 384 |
+
):
|
| 385 |
+
"""Thread which runs in the background performing prefills."""
|
| 386 |
+
logging.info('---------Spinning up prefill thread %d.---------', idx)
|
| 387 |
+
prefill_params = self._prefill_params[idx]
|
| 388 |
+
metadata = prefill_engine.get_tokenizer()
|
| 389 |
+
vocab = token_utils.load_vocab(metadata.path, metadata.extra_ids)
|
| 390 |
+
logging.info('---------Prefill params %d loaded.---------', idx)
|
| 391 |
+
|
| 392 |
+
while self.live:
|
| 393 |
+
# We don't want to keep lots of kv caches live in memory on the prefill
|
| 394 |
+
# slice that aren't about to be sent over to a generation slice.
|
| 395 |
+
if self._generate_backlogs[idx].qsize() < generate_backpressure:
|
| 396 |
+
# Check if there is anything on the prefill backlog, pop if so.
|
| 397 |
+
try:
|
| 398 |
+
request = self._prefill_backlog.get(block=True)
|
| 399 |
+
if request is None:
|
| 400 |
+
break
|
| 401 |
+
tempbos_id = request.vocab['bos_id'] if 'bos_id' in request.vocab else vocab.bos_id
|
| 402 |
+
tempeos_id = request.vocab['eos_id'] if 'eos_id' in request.vocab else vocab.eos_id
|
| 403 |
+
temppad_id = request.vocab['pad_id'] if 'pad_id' in request.vocab else vocab.pad_id
|
| 404 |
+
|
| 405 |
+
# TODO: Implement hot/cold cache for history.
|
| 406 |
+
history = self._load_cache_history(request.history_path) # pylint: disable = assignment-from-none
|
| 407 |
+
# Tokenize, and introduce a leading dimension
|
| 408 |
+
is_bos = not bool(request.history_path)
|
| 409 |
+
logging.info(
|
| 410 |
+
'Prefilling on prefill engine %d : prefill queue size, %d,'
|
| 411 |
+
' is_bos: %s, history: %s',
|
| 412 |
+
idx,
|
| 413 |
+
self._prefill_backlog.qsize(),
|
| 414 |
+
is_bos,
|
| 415 |
+
request.history_path,
|
| 416 |
+
) # pylint: disable = line-too-long
|
| 417 |
+
padded_tokens, true_length = token_utils.tokenize_and_pad(
|
| 418 |
+
request.prefill_text,
|
| 419 |
+
vocab,
|
| 420 |
+
is_bos=is_bos,
|
| 421 |
+
eos_id = tempeos_id,
|
| 422 |
+
pad_id = temppad_id,
|
| 423 |
+
bos_id = tempbos_id,
|
| 424 |
+
max_prefill_length=prefill_engine.max_prefill_length,
|
| 425 |
+
)
|
| 426 |
+
# Compute new kv cache for the prefill_text, conditional on
|
| 427 |
+
# history.
|
| 428 |
+
prefill_result = prefill_engine.prefill(
|
| 429 |
+
params=prefill_params,
|
| 430 |
+
existing_prefix=history,
|
| 431 |
+
padded_tokens=padded_tokens,
|
| 432 |
+
true_length=true_length,
|
| 433 |
+
)
|
| 434 |
+
request.prefill_result = prefill_result
|
| 435 |
+
# Once prefill is complete, place it on the generation queue.
|
| 436 |
+
self._generate_backlogs[idx].put(request)
|
| 437 |
+
logging.info(
|
| 438 |
+
'Placed request on the generate queue,'
|
| 439 |
+
f' {self._generate_backlogs[idx].qsize()=}'
|
| 440 |
+
)
|
| 441 |
+
except queue.Empty:
|
| 442 |
+
# Otherwise, don't do anything!
|
| 443 |
+
pass
|
| 444 |
+
|
| 445 |
+
def _generate_thread(
|
| 446 |
+
self,
|
| 447 |
+
idx: int,
|
| 448 |
+
generate_engine: engine_api.Engine,
|
| 449 |
+
my_slots: queue.Queue[int],
|
| 450 |
+
my_detokenize_backlog: queue.Queue[tuple[int, engine_api.ResultTokens]],
|
| 451 |
+
backpressure: int = 3,
|
| 452 |
+
):
|
| 453 |
+
"""Step token generation and insert prefills from backlog.
|
| 454 |
+
|
| 455 |
+
Args:
|
| 456 |
+
idx: Idx corresponding to which generation engine idx this is.
|
| 457 |
+
generate_engine: The generate engine corresponding to this thread.
|
| 458 |
+
my_slots: Integers representing free my_slots.
|
| 459 |
+
my_detokenize_backlog: Detokenize backlog for this generate engine.
|
| 460 |
+
backpressure: How many steps we can queue up before pausing, allows us to
|
| 461 |
+
hide dispatch times because jit calls are dispatched one after another.
|
| 462 |
+
We have this in the first place because we don't want to enqueue
|
| 463 |
+
thousands of steps.
|
| 464 |
+
"""
|
| 465 |
+
logging.info('---------Spinning up generate thread %d.---------', idx)
|
| 466 |
+
# Keep track of what step tokens were generated at.
|
| 467 |
+
generate_timestep = 0
|
| 468 |
+
# State to store things like running kv cache in.
|
| 469 |
+
decode_state = generate_engine.init_decode_state()
|
| 470 |
+
generate_params = self._generate_params[idx]
|
| 471 |
+
logging.info('---------Generate params %d loaded.---------', idx)
|
| 472 |
+
time_of_last_generate = time.time()
|
| 473 |
+
time_of_last_print = time.time()
|
| 474 |
+
while self.live:
|
| 475 |
+
if (time.time() - time_of_last_print) > 1:
|
| 476 |
+
logging.info(
|
| 477 |
+
'Generate thread making a decision with:'
|
| 478 |
+
f' prefill_backlog={self._prefill_backlog.qsize()} generate_free_slots={my_slots.qsize()}'
|
| 479 |
+
)
|
| 480 |
+
time_of_last_print = time.time()
|
| 481 |
+
# Check if there are any free my_slots.
|
| 482 |
+
if not my_slots.empty() and not self._generate_backlogs[idx].empty():
|
| 483 |
+
# Only get requests from the backlog corresponding to this engine.
|
| 484 |
+
new_request = self._generate_backlogs[idx].get()
|
| 485 |
+
if new_request is None:
|
| 486 |
+
break
|
| 487 |
+
slot = my_slots.get()
|
| 488 |
+
logging.info(
|
| 489 |
+
'Generate slice %d slot %d step %d',
|
| 490 |
+
idx,
|
| 491 |
+
slot,
|
| 492 |
+
generate_timestep,
|
| 493 |
+
)
|
| 494 |
+
decode_state = generate_engine.insert(
|
| 495 |
+
new_request.prefill_result, decode_state, slot=slot
|
| 496 |
+
)
|
| 497 |
+
delete_pytree(new_request.prefill_result)
|
| 498 |
+
new_request.generate_timestep_added = generate_timestep
|
| 499 |
+
new_request.complete = np.zeros(
|
| 500 |
+
(generate_engine.samples_per_slot,), dtype=np.bool_
|
| 501 |
+
)
|
| 502 |
+
my_detokenize_backlog.put((slot, new_request))
|
| 503 |
+
|
| 504 |
+
if my_detokenize_backlog.qsize() < backpressure:
|
| 505 |
+
decode_state, sampled_tokens = generate_engine.generate(
|
| 506 |
+
generate_params, decode_state
|
| 507 |
+
)
|
| 508 |
+
sampled_tokens.copy_to_host_async()
|
| 509 |
+
my_detokenize_backlog.put((generate_timestep, sampled_tokens))
|
| 510 |
+
generate_timestep += 1
|
| 511 |
+
logging.info(
|
| 512 |
+
'Generate engine %d step %d - slots free : %d / %d, took %.2fms',
|
| 513 |
+
idx,
|
| 514 |
+
generate_timestep,
|
| 515 |
+
my_slots.qsize(),
|
| 516 |
+
generate_engine.max_concurrent_decodes,
|
| 517 |
+
(time.time() - time_of_last_generate) * 10**3,
|
| 518 |
+
)
|
| 519 |
+
time_of_last_generate = time.time()
|
| 520 |
+
|
| 521 |
+
def _detokenize_thread(
|
| 522 |
+
self,
|
| 523 |
+
idx: int,
|
| 524 |
+
generate_engine: engine_api.Engine,
|
| 525 |
+
my_slots: queue.Queue[int],
|
| 526 |
+
my_detokenize_backlog: queue.Queue[
|
| 527 |
+
Union[tuple[int, engine_api.ResultTokens], tuple[int, ActiveRequest]]
|
| 528 |
+
],
|
| 529 |
+
):
|
| 530 |
+
"""Detokenize sampled tokens and returns them to the user."""
|
| 531 |
+
del idx
|
| 532 |
+
# One of these per generate engine.
|
| 533 |
+
# For all filled my_slots, pop the sampled token onto the relevant
|
| 534 |
+
# requests return channel. If it done, place it back onto free slots.
|
| 535 |
+
metadata = generate_engine.get_tokenizer()
|
| 536 |
+
vocab = token_utils.load_vocab(metadata.path, metadata.extra_ids)
|
| 537 |
+
|
| 538 |
+
my_live_requests = {
|
| 539 |
+
i: None for i in range(generate_engine.max_concurrent_decodes)
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
while self.live:
|
| 543 |
+
try:
|
| 544 |
+
data = my_detokenize_backlog.get(block=True)
|
| 545 |
+
if data is None:
|
| 546 |
+
break
|
| 547 |
+
start_detokenise_time = time.time()
|
| 548 |
+
if isinstance(data[1], engine_api.ResultTokens):
|
| 549 |
+
# We want to detokenise them.
|
| 550 |
+
generate_timestep_added, result_tokens = data
|
| 551 |
+
# Disable attribute error because pytype doesn't know this
|
| 552 |
+
# is a result tokens, and we can't annotate the tuple.
|
| 553 |
+
result_tokens = result_tokens.convert_to_numpy() # pytype: disable=attribute-error
|
| 554 |
+
|
| 555 |
+
for slot, request in my_live_requests.items():
|
| 556 |
+
if request is not None:
|
| 557 |
+
# print(vocab)
|
| 558 |
+
# print(dir(vocab))
|
| 559 |
+
# req_vocab = json.loads(request.vocab)
|
| 560 |
+
tempbos_id = request.vocab['bos_id'] if 'bos_id' in request.vocab else vocab.bos_id
|
| 561 |
+
tempeos_id = request.vocab['eos_id'] if 'eos_id' in request.vocab else vocab.eos_id
|
| 562 |
+
temppad_id = request.vocab['pad_id'] if 'pad_id' in request.vocab else vocab.pad_id
|
| 563 |
+
|
| 564 |
+
results, complete = token_utils.process_result_tokens(
|
| 565 |
+
slot=slot,
|
| 566 |
+
slot_max_length=request.max_tokens,
|
| 567 |
+
result_tokens=result_tokens,
|
| 568 |
+
vocab=vocab,
|
| 569 |
+
eos_id = tempeos_id,
|
| 570 |
+
pad_id = temppad_id,
|
| 571 |
+
bos_id = tempbos_id,
|
| 572 |
+
complete=request.complete,
|
| 573 |
+
)
|
| 574 |
+
request.complete = complete
|
| 575 |
+
# Return some tokens.
|
| 576 |
+
request.enqueue_tokens(results)
|
| 577 |
+
if request.complete.all():
|
| 578 |
+
# Place the slot back on the free queue.
|
| 579 |
+
my_live_requests[slot] = None
|
| 580 |
+
my_slots.put(slot)
|
| 581 |
+
logging.info(
|
| 582 |
+
'Detokenising generate step %d took %.2fms',
|
| 583 |
+
generate_timestep_added,
|
| 584 |
+
(time.time() - start_detokenise_time) * 10**3,
|
| 585 |
+
)
|
| 586 |
+
else:
|
| 587 |
+
# We want to update a slot with the new channel.
|
| 588 |
+
slot, active_request = data
|
| 589 |
+
my_live_requests[slot] = active_request
|
| 590 |
+
|
| 591 |
+
except queue.Empty:
|
| 592 |
+
# Nothing to detokenize!
|
| 593 |
+
pass
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
class LLMOrchestrator(jetstream_pb2_grpc.OrchestratorServicer):
|
| 597 |
+
"""Coordinates a set of prefill and generate slices for LLM decoding."""
|
| 598 |
+
|
| 599 |
+
_driver: Driver
|
| 600 |
+
|
| 601 |
+
def __init__(self, driver: Driver):
|
| 602 |
+
self._driver = driver
|
| 603 |
+
|
| 604 |
+
def Decode(
|
| 605 |
+
self,
|
| 606 |
+
request: jetstream_pb2.DecodeRequest,
|
| 607 |
+
context: Optional[grpc.ServicerContext] = None,
|
| 608 |
+
) -> Iterable[jetstream_pb2.DecodeResponse]:
|
| 609 |
+
"""Decode."""
|
| 610 |
+
if context is None:
|
| 611 |
+
logging.warning(
|
| 612 |
+
'LLM orchestrator is being used in offline test mode, and will not'
|
| 613 |
+
' respond to gRPC queries - only direct function calls.'
|
| 614 |
+
)
|
| 615 |
+
# Wrap request as an ActiveRequest.
|
| 616 |
+
active_request = ActiveRequest(
|
| 617 |
+
max_tokens=request.max_tokens,
|
| 618 |
+
vocab=json.loads(request.vocab),
|
| 619 |
+
history_path=request.session_cache,
|
| 620 |
+
prefill_text=request.additional_text,
|
| 621 |
+
)
|
| 622 |
+
# The first stage is being prefilled, all other stages are handled
|
| 623 |
+
# inside the driver (transfer, generate*N, detokenize).
|
| 624 |
+
try:
|
| 625 |
+
self._driver.place_request_on_prefill_queue(active_request)
|
| 626 |
+
except queue.Full:
|
| 627 |
+
# Safely abort the gRPC server thread with a retriable error.
|
| 628 |
+
_abort_or_raise(
|
| 629 |
+
context=context,
|
| 630 |
+
code=grpc.StatusCode.RESOURCE_EXHAUSTED,
|
| 631 |
+
details=(
|
| 632 |
+
'The driver prefill queue is full and more requests cannot be'
|
| 633 |
+
' handled. You may retry this request.'
|
| 634 |
+
),
|
| 635 |
+
)
|
| 636 |
+
logging.info(
|
| 637 |
+
'Placed request on the prefill queue.',
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
while not (
|
| 641 |
+
active_request.complete and active_request.return_channel.empty()
|
| 642 |
+
):
|
| 643 |
+
# When an active request is created a queue is instantiated. New tokens
|
| 644 |
+
# are placed there during the decoding loop, we pop from that queue by
|
| 645 |
+
# using the .next method on the active request.
|
| 646 |
+
# Yielding allows for the response to be a streaming grpc call - which
|
| 647 |
+
# can be called via iterating over a for loop on the other side.
|
| 648 |
+
# The DecodeResponse stream should consume all generated tokens in
|
| 649 |
+
# return_channel when complete signal is received. It should check if
|
| 650 |
+
# return_channel is empty to decide if it should exit the while loop.
|
| 651 |
+
yield jetstream_pb2.DecodeResponse(response=active_request.next())
|
maxtext-setup/jetstream/jetstream/core/orchestrator_test.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
"""Integration test of the orchestrator.
|
| 16 |
+
|
| 17 |
+
This test tests the multi-htreaded orchestrator, where a prefill request is
|
| 18 |
+
popped onto a prefill queue, prefilled, sent to a generation queue and run for
|
| 19 |
+
a number of decoding steps.
|
| 20 |
+
|
| 21 |
+
In operation, it will use gRPC so we can 'yield' from the function to get return
|
| 22 |
+
values in the same way that they would be streamed back.
|
| 23 |
+
|
| 24 |
+
Similar to 'mock_engine_test' we can use known token values and a singleton
|
| 25 |
+
weight to test our operation.
|
| 26 |
+
|
| 27 |
+
Let the prefill engine have a weight of [2] and the generate engine have a
|
| 28 |
+
weight of [3].
|
| 29 |
+
|
| 30 |
+
I.e. if we prefill [2, 65, 66] (i.e. <BOS>, 'A', 'B') using an ACII vocab,
|
| 31 |
+
we should get [4, 130, 132].
|
| 32 |
+
|
| 33 |
+
If we then insert that and run three generation steps, we should see
|
| 34 |
+
266+0 / 2 = 266
|
| 35 |
+
266 + [266] / 4 = 332
|
| 36 |
+
266 + [266, 332] / 4 = 415
|
| 37 |
+
I.e. ['Ċ', 'Ō', 'Ɵ'] when converted back with chr().
|
| 38 |
+
|
| 39 |
+
Therefore we should get back the character sequence '$lǔ' if we request 3 tokens
|
| 40 |
+
decoded (these are the ascii chars at those indices which is what the test
|
| 41 |
+
tokenizer returns).
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
from absl.testing import absltest
|
| 45 |
+
from jetstream.core import orchestrator
|
| 46 |
+
from jetstream.core.proto import jetstream_pb2
|
| 47 |
+
from jetstream.engine import mock_engine
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class OrchestratorTest(absltest.TestCase):
|
| 51 |
+
|
| 52 |
+
def _setup_driver(self):
|
| 53 |
+
prefill_engine = mock_engine.TestEngine(
|
| 54 |
+
batch_size=32, cache_length=256, weight=2.0
|
| 55 |
+
)
|
| 56 |
+
# Create a generate engine with a different set of weights
|
| 57 |
+
# so that we can test that the right one is in use at a given time.
|
| 58 |
+
generate_engine = mock_engine.TestEngine(
|
| 59 |
+
batch_size=4, cache_length=32, weight=4.0
|
| 60 |
+
)
|
| 61 |
+
driver = orchestrator.Driver(
|
| 62 |
+
prefill_engines=[prefill_engine],
|
| 63 |
+
generate_engines=[generate_engine],
|
| 64 |
+
prefill_params=[prefill_engine.load_params()],
|
| 65 |
+
generate_params=[generate_engine.load_params()],
|
| 66 |
+
)
|
| 67 |
+
return driver
|
| 68 |
+
|
| 69 |
+
def test_orchestrator(self):
|
| 70 |
+
"""Test the multithreaded orchestration."""
|
| 71 |
+
driver = self._setup_driver()
|
| 72 |
+
client = orchestrator.LLMOrchestrator(driver=driver)
|
| 73 |
+
|
| 74 |
+
# The string representation of np.array([[65, 66]]), [2] will be prepend
|
| 75 |
+
# as BOS.
|
| 76 |
+
text = 'AB'
|
| 77 |
+
|
| 78 |
+
request = jetstream_pb2.DecodeRequest(
|
| 79 |
+
session_cache='',
|
| 80 |
+
additional_text=text,
|
| 81 |
+
priority=1,
|
| 82 |
+
max_tokens=3,
|
| 83 |
+
)
|
| 84 |
+
iterator = client.Decode(request)
|
| 85 |
+
# chr of [266, 332, 415].
|
| 86 |
+
expected_tokens = ['Ċ', 'Ō', 'Ɵ', '']
|
| 87 |
+
counter = 0
|
| 88 |
+
for token in iterator:
|
| 89 |
+
# Tokens come through as bytes.
|
| 90 |
+
print(
|
| 91 |
+
'actual output: '
|
| 92 |
+
+ bytes(token.response[0], encoding='utf-8').decode()
|
| 93 |
+
)
|
| 94 |
+
assert (
|
| 95 |
+
bytes(token.response[0], encoding='utf-8').decode()
|
| 96 |
+
== expected_tokens[counter]
|
| 97 |
+
)
|
| 98 |
+
counter += 1
|
| 99 |
+
driver.stop()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if __name__ == '__main__':
|
| 103 |
+
absltest.main()
|
maxtext-setup/jetstream/jetstream/core/proto/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
maxtext-setup/jetstream/jetstream/core/proto/jetstream.proto
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
// http://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 |
+
|
| 15 |
+
|
| 16 |
+
syntax = "proto3";
|
| 17 |
+
|
| 18 |
+
package jetstream_proto;
|
| 19 |
+
|
| 20 |
+
// TODO: Merge this with main JetStream core once we settle on an API.
|
| 21 |
+
|
| 22 |
+
service Orchestrator {
|
| 23 |
+
// Generate the next model tokens.
|
| 24 |
+
rpc Decode(DecodeRequest) returns (stream DecodeResponse) {}
|
| 25 |
+
}
|
| 26 |
+
message DecodeRequest {
|
| 27 |
+
// Where to load any pre-existing kv cache from.
|
| 28 |
+
string session_cache = 1;
|
| 29 |
+
// New text from a user or tool.
|
| 30 |
+
string additional_text = 2;
|
| 31 |
+
int32 priority = 3;
|
| 32 |
+
int32 max_tokens = 4;
|
| 33 |
+
string vocab = 5;
|
| 34 |
+
}
|
| 35 |
+
message DecodeResponse {
|
| 36 |
+
// List of responses, one per sample.
|
| 37 |
+
repeated string response = 1;
|
| 38 |
+
}
|
maxtext-setup/jetstream/jetstream/core/proto/jetstream_pb2.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# http://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 |
+
|
| 15 |
+
# -*- coding: utf-8 -*-
|
| 16 |
+
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
| 17 |
+
# source: jetstream/core/proto/jetstream.proto
|
| 18 |
+
# Protobuf Python Version: 4.25.1
|
| 19 |
+
"""Generated protocol buffer code."""
|
| 20 |
+
from google.protobuf import descriptor as _descriptor
|
| 21 |
+
from google.protobuf import descriptor_pool as _descriptor_pool
|
| 22 |
+
from google.protobuf import symbol_database as _symbol_database
|
| 23 |
+
from google.protobuf.internal import builder as _builder
|
| 24 |
+
# @@protoc_insertion_point(imports)
|
| 25 |
+
|
| 26 |
+
_sym_db = _symbol_database.Default()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n$jetstream/core/proto/jetstream.proto\x12\x0fjetstream.proto\x12\x0fjetstream_proto\"t\n\rDecodeRequest\x12\x15\n\rsession_cache\x18\x01 \x01(\t\x12\x17\n\x0f\x61\x64\x64itional_text\x18\x02 \x01(\t\x12\x10\n\x08priority\x18\x03 \x01(\x05\x12\x12\n\nmax_tokens\x18\x04 \x01(\x05\x12\r\n\x05vocab\x18\x05 \x01(\t\"\"\n\x0e\x44\x65\x63odeResponse\x12\x10\n\x08response\x18\x01 \x03(\t2]\n\x0cOrchestrator\x12M\n\x06\x44\x65\x63ode\x12\x1e.jetstream_proto.DecodeRequest\x1a\x1f.jetstream_proto.DecodeResponse\"\x00\x30\x01\x62\x06proto3')
|
| 32 |
+
|
| 33 |
+
_globals = globals()
|
| 34 |
+
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
|
| 35 |
+
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'jetstream.core.proto.jetstream_pb2', _globals)
|
| 36 |
+
# if _descriptor._USE_C_DESCRIPTORS == False:
|
| 37 |
+
# DESCRIPTOR._options = None
|
| 38 |
+
# _globals['_DECODEREQUEST']._serialized_start=57
|
| 39 |
+
# _globals['_DECODEREQUEST']._serialized_end=173 #158
|
| 40 |
+
# _globals['_DECODERESPONSE']._serialized_start=175 #160
|
| 41 |
+
# _globals['_DECODERESPONSE']._serialized_end=209 #194
|
| 42 |
+
# _globals['_ORCHESTRATOR']._serialized_start=196
|
| 43 |
+
# _globals['_ORCHESTRATOR']._serialized_end=289
|
| 44 |
+
# @@protoc_insertion_point(module_scope)
|