diff --git a/maxtext-setup/jetstream/AUTHORS b/maxtext-setup/jetstream/AUTHORS
new file mode 100644
index 0000000000000000000000000000000000000000..943dd484b302f2753a693ea3e5592d76a44132bc
--- /dev/null
+++ b/maxtext-setup/jetstream/AUTHORS
@@ -0,0 +1 @@
+Google LLC
\ No newline at end of file
diff --git a/maxtext-setup/jetstream/CONTRIBUTING.md b/maxtext-setup/jetstream/CONTRIBUTING.md
new file mode 100644
index 0000000000000000000000000000000000000000..23cb9381bace9f96dc5d6b119cb66f63f3d5d67f
--- /dev/null
+++ b/maxtext-setup/jetstream/CONTRIBUTING.md
@@ -0,0 +1,33 @@
+# How to Contribute
+
+We'd love to accept your patches and contributions to this project.
+
+## Before you begin
+
+### Sign our Contributor License Agreement
+
+Contributions to this project must be accompanied by a
+[Contributor License Agreement](https://cla.developers.google.com/about) (CLA).
+You (or your employer) retain the copyright to your contribution; this simply
+gives us permission to use and redistribute your contributions as part of the
+project.
+
+If you or your current employer have already signed the Google CLA (even if it
+was for a different project), you probably don't need to do it again.
+
+Visit to see your current agreements or to
+sign a new one.
+
+### Review our Community Guidelines
+
+This project follows
+[Google's Open Source Community Guidelines](https://opensource.google/conduct/).
+
+## Contribution process
+
+### Code Reviews
+
+All submissions, including submissions by project members, require review. We
+use GitHub pull requests for this purpose. Consult
+[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
+information on using pull requests.
\ No newline at end of file
diff --git a/maxtext-setup/jetstream/LICENSE b/maxtext-setup/jetstream/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7
--- /dev/null
+++ b/maxtext-setup/jetstream/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/maxtext-setup/jetstream/README.md b/maxtext-setup/jetstream/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..9eee75a14ccbca3535a056f52c48e3438c49bd9f
--- /dev/null
+++ b/maxtext-setup/jetstream/README.md
@@ -0,0 +1,38 @@
+# JetStream - A throughput and memory optimized engine for LLM inference on TPU and GPU
+
+## About
+
+JetStream is a fast library for LLM inference and serving on TPU and GPU.
+
+## Getting Started
+
+### Run local server & Testing
+
+Use the following commands to run a server locally:
+```
+# Start a server
+python -m jetstream.core.implementations.mock.server
+
+# Test local mock server
+python -m jetstream.core.tools.requester
+
+# Load test local mock server
+python -m jetstream.core.tools.load_tester
+
+```
+
+### Test core modules
+```
+# Test JetStream core orchestrator
+python -m jetstream.core.orchestrator_test
+
+# Test JetStream core server library
+python -m jetstream.core.server_test
+
+# Test mock JetStream engine implementation
+python -m jetstream.engine.mock_engine_test
+
+# Test mock JetStream token utils
+python -m jetstream.engine.utils_test
+
+```
diff --git a/maxtext-setup/jetstream/benchmarks/README.md b/maxtext-setup/jetstream/benchmarks/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..96a4871f161dcc18483418d3fa905218bbfab141
--- /dev/null
+++ b/maxtext-setup/jetstream/benchmarks/README.md
@@ -0,0 +1,50 @@
+# JetStream Benchmark And Eval
+
+## Install Dependencies
+
+```
+cd ~/JetStream/benchmarks
+pip install -r requirements.in
+```
+
+## Benchmark
+
+### Prepare DataSet
+
+```
+cd ~/data
+wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/resolve/main/ShareGPT_V3_unfiltered_cleaned_split.json
+
+```
+
+### Run Benchmark with maxtext tokenizer
+
+```
+python benchmark_serving.py \
+--tokenizer /home/{username}/maxtext/assets/tokenizer \
+--num-prompts 10 \
+--dataset ~/data/ShareGPT_V3_unfiltered_cleaned_split.json
+
+```
+
+### Save request outputs in Benchmark
+
+Please use --save-request-outputs flag to enable this feature.
+
+```
+python benchmark_serving.py \
+--tokenizer /home/{username}/maxtext/assets/tokenizer \
+--num-prompts 10 \
+--dataset ~/data/ShareGPT_V3_unfiltered_cleaned_split.json \
+--save-request-outputs
+
+```
+
+## Eval Accuracy
+
+Evaluate inference genereted output accuracy using saved request outputs.
+
+```
+python eval_accuracy.py
+
+```
\ No newline at end of file
diff --git a/maxtext-setup/jetstream/benchmarks/benchmark_serving.py b/maxtext-setup/jetstream/benchmarks/benchmark_serving.py
new file mode 100644
index 0000000000000000000000000000000000000000..876264a80bbcd78694620441ccd59cf9f99c005a
--- /dev/null
+++ b/maxtext-setup/jetstream/benchmarks/benchmark_serving.py
@@ -0,0 +1,602 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Benchmark JetStream online serving.
+
+On the server side, run one of the following commands:
+ * For real server, you need to pass correct server config (include the model config that
+ being passed into your engine impl) to the command below. Refer to config_lib.py and
+ implementations/mock/config.py for config impl detail.
+
+ (run with real server)
+ python -m jetstream.core.implementations..server \
+ --config
+
+ (run with mock server)
+ python -m jetstream.core.implementations.mock.server
+
+On the client side, run:
+ * For real server and shareGPT dataset, you need to pass the tokenizer, server config, and
+ dataset flags to the command below, and make some changes to the tokenizer logic in the
+ benchmark script (get_tokenizer and sample_requests func) to use your tokenizer correctly.
+ * Add `--save-result` flag to save the benchmark result to a json file in current folder.
+ * Add `--threads` flag to set the maximum number of threads used for request dispatching.
+
+ (run with real model and engines)
+ python -m benchmarks.benchmark_serving \
+ --tokenizer --dataset \
+ --request-rate
+
+ (run with mock)
+ python -m benchmarks.benchmark_serving \
+ --request-rate 1
+
+e2e example: python3 benchmark_serving.py --tokenizer /home/rwitten/maxtext/assets/tokenizer --num-prompts 100 --dataset ~/ShareGPT_V3_unfiltered_cleaned_split.json
+"""
+
+
+import tensorflow as tf
+import tensorflow_text as tftxt
+
+import argparse
+import asyncio
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass
+from datetime import datetime
+import json
+import random
+import time
+from typing import Any, AsyncGenerator, List, Tuple
+import grpc
+from jetstream.core.proto import jetstream_pb2
+from jetstream.core.proto import jetstream_pb2_grpc
+import numpy as np
+from tqdm.asyncio import tqdm
+
+
+@dataclass
+class BenchmarkMetrics:
+ completed: int
+ total_input: int
+ total_output: int
+ request_throughput: float
+ input_throughput: float
+ output_throughput: float
+ mean_ttft_ms: float
+ median_ttft_ms: float
+ p99_ttft_ms: float
+ mean_tpot_ms: float
+ median_tpot_ms: float
+ p99_tpot_ms: float
+
+
+@dataclass
+class InputRequest:
+ prompt: str = ""
+ prompt_len: int = 0
+ output: str = ""
+ output_len: int = 0
+
+@dataclass
+class RequestFuncOutput:
+ input_request: InputRequest = None
+ generated_token_list: list[str] = None
+ generated_text: str = None
+ success: bool = False
+ latency: float = 0
+ ttft: float = 0
+ prompt_len: int = 0
+
+ # Flatten the structure and return only the necessary results
+ def to_dict(self):
+ return {
+ "prompt": self.input_request.prompt,
+ "original_output": self.input_request.output,
+ "generated_text": self.generated_text,
+ "success": self.success,
+ "latency": self.latency,
+ "prompt_len": self.prompt_len
+ }
+
+
+def get_tokenizer(tokenizer_name: str) -> Any:
+ """Return a tokenizer or a tokenizer placholder."""
+ if tokenizer_name == "test":
+ return "test"
+ else:
+ with tf.io.gfile.GFile(tokenizer_name, 'rb') as model_fp:
+ sp_model = model_fp.read()
+ sp_tokenizer = tftxt.SentencepieceTokenizer(
+ model=sp_model, add_bos=True, add_eos=False, reverse=False)
+ return sp_tokenizer
+
+def sample_requests(
+ dataset_path: str,
+ num_requests: int,
+ tokenizer: Any,
+ max_output_length: int,
+) -> List[InputRequest]:
+ # Load the dataset.
+ with open(dataset_path) as f:
+ dataset = json.load(f)
+ # Filter out the conversations with less than 2 turns.
+ dataset = [data for data in dataset if len(data["conversations"]) >= 2]
+ # Only keep the first two turns of each conversation.
+ dataset = [
+ (data["conversations"][0]["value"], data["conversations"][1]["value"])
+ for data in dataset
+ ]
+
+ # some of these will be filtered out, so sample more than we need
+ sampled_indices = random.sample(range(len(dataset)), int(num_requests * 1.2))
+ dataset = [dataset[i] for i in sampled_indices]
+
+ # Tokenize the prompts and completions.
+ prompts = [prompt for prompt, _ in dataset]
+ prompt_token_ids = tokenizer.tokenize(
+ prompts
+ ) # adjust this code based on tokenizer method
+ completions = [completion for _, completion in dataset]
+ completion_token_ids = tokenizer.tokenize(
+ completions
+ ) # adjust this code based on tokenizer method
+ tokenized_dataset = []
+ for i in range(len(dataset)):
+ output_len = len(completion_token_ids[i])
+ tokenized_dataset.append((prompts[i], prompt_token_ids[i], completions[i], output_len))
+
+ # Filter out too long sequences.
+ filtered_dataset: List[InputRequest] = []
+
+ for prompt, prompt_token_ids, output, output_len in tokenized_dataset:
+ prompt_len = len(prompt_token_ids)
+ if prompt_len < 4 or output_len < 4:
+ # Prune too short sequences.
+ # This is because TGI causes errors when the input or output length
+ # is too short.
+ continue
+ if prompt_len > 1024 or prompt_len + output_len > 2048:
+ # Prune too long sequences.
+ continue
+ reqeust = InputRequest(prompt, prompt_len, output, max_output_length)
+ filtered_dataset.append(reqeust)
+
+ # Sample the requests.
+ sampled_requests = random.sample(filtered_dataset, num_requests)
+ return sampled_requests
+
+
+async def get_request(
+ input_requests: List[InputRequest],
+ request_rate: float,
+) -> AsyncGenerator[InputRequest, None]:
+ input_requests = iter(input_requests)
+ for request in input_requests:
+ yield request
+
+ if request_rate == float("inf"):
+ # If the request rate is infinity, then we don't need to wait.
+ continue
+ # Sample the request interval from the exponential distribution.
+ interval = np.random.exponential(1.0 / request_rate)
+ # The next request will be sent after the interval.
+ await asyncio.sleep(interval)
+
+
+def calculate_metrics(
+ input_requests: List[InputRequest],
+ outputs: List[RequestFuncOutput],
+ dur_s: float,
+ tokenizer: Any,
+) -> BenchmarkMetrics:
+ total_output = 0
+ total_input = 0
+ completed = 0
+ per_token_latencies = []
+ ttfts = []
+ for i in range(len(outputs)):
+ if outputs[i].success:
+ output_len = len(
+ outputs[i].generated_token_list
+ if tokenizer != "test"
+ else ["Ċ", "Ō", "Ɵ"]
+ )
+ total_output += output_len
+ total_input += input_requests[i].prompt_len
+ per_token_latencies.append(outputs[i].latency / output_len)
+ ttfts.append(outputs[i].ttft)
+ completed += 1
+
+ metrics = BenchmarkMetrics(
+ completed=completed,
+ total_input=total_input,
+ total_output=total_output,
+ request_throughput=completed / dur_s,
+ input_throughput=total_input / dur_s,
+ output_throughput=total_output / dur_s,
+ mean_ttft_ms=np.mean(ttfts) * 1000,
+ median_ttft_ms=np.median(ttfts) * 1000,
+ p99_ttft_ms=np.percentile(ttfts, 99) * 1000,
+ mean_tpot_ms=np.mean(per_token_latencies) * 1000,
+ median_tpot_ms=np.median(per_token_latencies) * 1000,
+ p99_tpot_ms=np.percentile(per_token_latencies, 99) * 1000,
+ )
+
+ return metrics
+
+
+def grpc_sync_request(api_url: str, request: Any) -> tuple[list[str], float, float]:
+ """Send grpc synchronous request since the current grpc server is sync."""
+ options = [("grpc.keepalive_timeout_ms", 10000)]
+ with grpc.insecure_channel(api_url, options=options) as channel:
+ grpc.channel_ready_future(channel).result()
+ stub = jetstream_pb2_grpc.OrchestratorStub(channel)
+ print("Making request")
+ ttft = 0
+ token_list = []
+ request_start_time = time.perf_counter()
+ response = stub.Decode(request)
+ for token in response:
+ if ttft == 0:
+ ttft = time.perf_counter() - request_start_time
+ token_list.append(token.response[0])
+ latency = time.perf_counter() - request_start_time
+ return token_list, ttft, latency
+
+
+async def send_request(
+ api_url: str,
+ input_request: InputRequest,
+ pbar: tqdm,
+ session_cache: str,
+ priority: int,
+ threads: int,
+) -> RequestFuncOutput:
+ """Send the request to JetStream server."""
+ loop = asyncio.get_running_loop()
+ loop.set_default_executor(ThreadPoolExecutor(max_workers=threads))
+ request = jetstream_pb2.DecodeRequest(
+ session_cache=session_cache,
+ additional_text=input_request.prompt,
+ priority=priority,
+ max_tokens=input_request.output_len,
+ )
+ output = RequestFuncOutput()
+ output.input_request = input_request
+ output.prompt_len = input_request.prompt_len
+ generated_token_list, ttft, latency = await loop.run_in_executor(
+ None, grpc_sync_request, api_url, request
+ )
+ output.ttft = ttft
+ output.latency = latency
+ output.generated_token_list = generated_token_list
+ output.generated_text = "".join(generated_token_list)
+ output.success = True
+ if pbar:
+ pbar.update(1)
+ return output
+
+
+async def benchmark(
+ api_url: str,
+ tokenizer: Any,
+ input_requests: List[InputRequest],
+ request_rate: float,
+ disable_tqdm: bool,
+ session_cache: str,
+ priority: int,
+ threads: int,
+):
+ """Benchmark the online serving performance."""
+ pbar = None if disable_tqdm else tqdm(total=len(input_requests))
+
+ print(f"Traffic request rate: {request_rate}")
+
+ benchmark_start_time = time.perf_counter()
+ tasks = []
+ async for request in get_request(input_requests, request_rate):
+ tasks.append(
+ asyncio.create_task(
+ send_request(
+ api_url=api_url,
+ input_request=request,
+ pbar=pbar,
+ session_cache=session_cache,
+ priority=priority,
+ threads=threads,
+ )
+ )
+ )
+ outputs = await asyncio.gather(*tasks)
+
+ if not disable_tqdm:
+ pbar.close()
+
+ benchmark_duration = time.perf_counter() - benchmark_start_time
+
+ metrics = calculate_metrics(
+ input_requests=input_requests,
+ outputs=outputs,
+ dur_s=benchmark_duration,
+ tokenizer=tokenizer,
+ )
+
+ print(f"Successful requests: {metrics.completed}")
+ print(f"Benchmark duration: {benchmark_duration:2f} s")
+ print(f"Total input tokens: {metrics.total_input}")
+ print(f"Total generated tokens: {metrics.total_output}")
+ print(f"Request throughput: {metrics.request_throughput:.2f} requests/s")
+ print(f"Input token throughput: {metrics.input_throughput:.2f} tokens/s")
+ print(f"Output token throughput: {metrics.output_throughput:.2f} tokens/s")
+ print(f"Mean TTFT: {metrics.mean_ttft_ms:.2f} ms")
+ print(f"Median TTFT: {metrics.median_ttft_ms:.2f} ms")
+ print(f"P99 TTFT: {metrics.p99_ttft_ms:.2f} ms")
+ print(f"Mean TPOT: {metrics.mean_tpot_ms:.2f} ms")
+ print(f"Median TPOT: {metrics.median_tpot_ms:.2f} ms")
+ print(f"P99 TPOT: {metrics.p99_tpot_ms:.2f} ms")
+
+ result = {
+ "duration": benchmark_duration,
+ "completed": metrics.completed,
+ "total_input_tokens": metrics.total_input,
+ "total_output_tokens": metrics.total_output,
+ "request_inthroughput": metrics.request_throughput,
+ "input_throughput": metrics.input_throughput,
+ "output_throughput": metrics.output_throughput,
+ "mean_ttft_ms": metrics.mean_ttft_ms,
+ "median_ttft_ms": metrics.median_ttft_ms,
+ "p99_ttft_ms": metrics.p99_ttft_ms,
+ "mean_tpot_ms": metrics.mean_tpot_ms,
+ "median_tpot_ms": metrics.median_tpot_ms,
+ "p99_tpot_ms": metrics.p99_tpot_ms,
+ }
+ return result, outputs
+
+
+def mock_requests(total_mock_requests: int):
+ """Generates a list of mock requests containing mock data."""
+ data = []
+ for _ in range(total_mock_requests):
+ reqeust = InputRequest()
+ reqeust.prompt = f"Prompt {random.randint(1, 1000)}"
+ reqeust.prompt_len = random.randint(10, 100)
+ reqeust.out = f"Output {random.randint(1, 1000)}"
+ reqeust.output_len = random.randint(1, 10)
+ data.append(reqeust)
+ return data
+
+
+def sample_warmup_requests(requests):
+ interesting_buckets = [
+ 0,
+ 16,
+ 32,
+ 64,
+ 128,
+ 256,
+ 512,
+ 1024,]
+
+ for start, end in zip(interesting_buckets[:-1], interesting_buckets[1:]):
+ for request in requests:
+ if start < request.prompt_len <= end:
+ yield request
+ break
+
+
+def main(args: argparse.Namespace):
+ print(args)
+ random.seed(args.seed)
+ np.random.seed(args.seed)
+
+ model_id = args.model
+ tokenizer_id = args.tokenizer
+
+ api_url = f"{args.server}:{args.port}"
+
+ tokenizer = get_tokenizer(tokenizer_id)
+ if tokenizer == "test" or args.dataset == "test":
+ input_requests = mock_requests(args.total_mock_requests) # e.g. [("AB", 2, "AB", 3)]
+ else:
+ input_requests = sample_requests(args.dataset, args.num_prompts, tokenizer, args.max_output_length)
+
+ if args.warmup_first:
+ print('Warm up start:' )
+ warmup_requests = list(sample_warmup_requests(input_requests)) * 2
+ benchmark_result, request_outputs = asyncio.run(
+ benchmark(
+ api_url=api_url,
+ tokenizer=tokenizer,
+ input_requests=warmup_requests,
+ request_rate=args.request_rate,
+ disable_tqdm=args.disable_tqdm,
+ session_cache=args.session_cache,
+ priority=args.priority,
+ threads=args.threads,
+ )
+ )
+ print('Warm up done')
+
+ benchmark_result, request_outputs = asyncio.run(
+ benchmark(
+ api_url=api_url,
+ tokenizer=tokenizer,
+ input_requests=input_requests,
+ request_rate=args.request_rate,
+ disable_tqdm=args.disable_tqdm,
+ session_cache=args.session_cache,
+ priority=args.priority,
+ threads=args.threads,
+ )
+ )
+
+ # Save config and results to json
+ if args.save_result:
+ result_json = {}
+
+ # Setup
+ current_dt = datetime.now().strftime("%Y%m%d-%H%M%S")
+ result_json["date"] = current_dt
+ result_json["model_id"] = model_id
+ result_json["tokenizer_id"] = tokenizer_id
+ result_json["num_prompts"] = args.num_prompts
+
+ # Traffic
+ result_json["request_rate"] = (
+ args.request_rate if args.request_rate < float("inf") else "inf"
+ )
+
+ # Merge with benchmark result
+ result_json = {**result_json, **benchmark_result}
+
+ # Save to file
+ base_model_id = model_id.split("/")[-1]
+ file_name = (
+ f"JetStream-{args.request_rate}qps-{base_model_id}-{current_dt}.json"
+ )
+ with open(file_name, "w") as outfile:
+ json.dump(result_json, outfile)
+
+ if args.save_request_outputs:
+ file_path = args.request_outputs_file_path
+ with open(file_path, "w") as output_file:
+ json.dump([output.to_dict() for output in request_outputs], output_file, indent=4)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(
+ description="Benchmark the online serving throughput."
+ )
+ parser.add_argument(
+ "--server",
+ type=str,
+ default="dns:///[::1]",
+ help="Server address.",
+ )
+ parser.add_argument("--port", type=str, default=9000)
+ parser.add_argument(
+ "--dataset", type=str, default="test", help="Path to the dataset."
+ )
+ parser.add_argument(
+ "--model",
+ type=str,
+ default="no_model",
+ help=(
+ "Name of the model. (it's just used to label the benchmark, the model"
+ " config is defined in config_lib, and passed as the server config"
+ " flag when we run the JetStream server)"
+ ),
+ )
+ parser.add_argument(
+ "--tokenizer",
+ type=str,
+ default="test",
+ help=(
+ "Name or path of the tokenizer. (For mock model testing, use the"
+ " default value)"
+ ),
+ )
+ parser.add_argument(
+ "--num-prompts",
+ type=int,
+ default=1000,
+ help=(
+ "Number of prompts to process. (number of sample requests we randomly"
+ " collect from dataset)"
+ ),
+ )
+ parser.add_argument(
+ "--request-rate",
+ type=float,
+ default=float("inf"),
+ help=(
+ "Number of requests per second. If this is inf, "
+ "then all the requests are sent at time 0. "
+ "Otherwise, we use Poisson process to synthesize "
+ "the request arrival times."
+ ),
+ )
+ parser.add_argument(
+ "--threads",
+ type=int,
+ default=110,
+ help="The maximum number of threads used for request dispatching.",
+ )
+ parser.add_argument(
+ "--total-mock-requests",
+ type=int,
+ default=150,
+ help="The maximum number of mock requests to send for benchmark testing.",
+ )
+
+ parser.add_argument(
+ "--max-output-length",
+ type=int,
+ default=1024,
+ help="The maximum output length for reference request.",
+ )
+
+ parser.add_argument("--seed", type=int, default=0)
+ parser.add_argument(
+ "--disable-tqdm",
+ action="store_true",
+ help="Specify to disable tqdm progress bar.",
+ )
+ parser.add_argument(
+ "--save-result",
+ action="store_true",
+ help="Specify to save benchmark results to a json file",
+ )
+ parser.add_argument(
+ "--priority",
+ type=int,
+ default=0,
+ help=(
+ "Message priority. (currently no business logic implemented, use"
+ " default 0)"
+ ),
+ )
+ parser.add_argument(
+ "--session-cache",
+ type=str,
+ default="",
+ help=(
+ "Location of any pre-cached results. (currently _load_cache_history"
+ " not implemented, use default empty str)"
+ ),
+ )
+ parser.add_argument(
+ "--save-request-outputs",
+ action="store_true",
+ help="Specify to store request outputs into a json file",
+ )
+ parser.add_argument(
+ "--request-outputs-file-path",
+ type=str,
+ default="/tmp/request-outputs.json",
+ help=(
+ "File path to store request outputs"
+ ),
+ )
+ parser.add_argument(
+ "--warmup-first",
+ type=bool,
+ default=False,
+ help=(
+ "Whether to send warmup req first"
+ ),
+ )
+
+ args = parser.parse_args()
+ main(args)
diff --git a/maxtext-setup/jetstream/benchmarks/eval_accuracy.py b/maxtext-setup/jetstream/benchmarks/eval_accuracy.py
new file mode 100644
index 0000000000000000000000000000000000000000..a46ba78ffe2a070ec058474c7c9d5df1b85b088d
--- /dev/null
+++ b/maxtext-setup/jetstream/benchmarks/eval_accuracy.py
@@ -0,0 +1,55 @@
+import argparse
+import nltk
+import evaluate
+import json
+
+import numpy as np
+
+def postprocess_text(preds, targets):
+ preds = [pred.strip() for pred in preds]
+ targets = [target.strip() for target in targets]
+
+ # rougeLSum expects newline after each sentence
+ preds = ["\n".join(nltk.sent_tokenize(pred)) for pred in preds]
+ targets = ["\n".join(nltk.sent_tokenize(target)) for target in targets]
+
+ return preds, targets
+
+
+def eval_accuracy(request_outputs_dict):
+ metric = evaluate.load("rouge")
+ nltk.download('punkt')
+ preds = []
+ targets = []
+
+ for output in request_outputs_dict:
+ preds.append(output["generated_text"])
+ targets.append(output["original_output"])
+ preds, targets = postprocess_text(preds, targets)
+ result = metric.compute(
+ predictions=preds, references=targets, use_stemmer=True, use_aggregator=False)
+ result = {k: round(np.mean(v) * 100, 4) for k, v in result.items()}
+ prediction_lens = [len(pred) for pred in preds]
+ result["gen_len"] = np.sum(prediction_lens)
+ result["gen_num"] = len(preds)
+ print("\nResults\n")
+ print(result)
+
+
+def main(args):
+ with open(args.output_path) as f:
+ request_outputs_dict = json.load(f)
+
+ eval_accuracy(request_outputs_dict)
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "--output_path", type=str,
+ default="/tmp/request-outputs.json",
+ help="File path which has original_output and inference generated_text.")
+
+ args = parser.parse_args()
+
+ main(args)
diff --git a/maxtext-setup/jetstream/benchmarks/requirements.in b/maxtext-setup/jetstream/benchmarks/requirements.in
new file mode 100644
index 0000000000000000000000000000000000000000..7e19e55747ddee7acda7d649428e52b546684c34
--- /dev/null
+++ b/maxtext-setup/jetstream/benchmarks/requirements.in
@@ -0,0 +1,3 @@
+nltk
+evaluate
+rouge-score
\ No newline at end of file
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/__init__.py b/maxtext-setup/jetstream/build/lib/jetstream/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c38dc3b14ab36f34985ad3f1b20071f4a6a16e82
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/core/__init__.py b/maxtext-setup/jetstream/build/lib/jetstream/core/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c38dc3b14ab36f34985ad3f1b20071f4a6a16e82
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/core/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/core/config_lib.py b/maxtext-setup/jetstream/build/lib/jetstream/core/config_lib.py
new file mode 100644
index 0000000000000000000000000000000000000000..700694da55b2f1ead239e5ce810900fd28333ed0
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/core/config_lib.py
@@ -0,0 +1,155 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Configs of engines for the orchestrator to load."""
+
+import dataclasses
+import functools
+import math
+from typing import Any, Callable, List, Tuple, Type
+
+from jetstream.engine import engine_api
+from jetstream.engine import mock_engine
+
+
+Devices = Any
+
+CreateEngineFn = Callable[[Devices], engine_api.Engine]
+
+
+@dataclasses.dataclass
+class ServerConfig:
+ """Configs for slices to put engines on."""
+
+ prefill_slices: Tuple[str, ...] = ()
+ generate_slices: Tuple[str, ...] = ()
+ interleaved_slices: Tuple[str, ...] = ()
+ prefill_engine_create_fns: Tuple[CreateEngineFn, ...] = ()
+ generate_engine_create_fns: Tuple[CreateEngineFn, ...] = ()
+ interleaved_engine_create_fns: Tuple[CreateEngineFn, ...] = ()
+
+ def get_slices_to_launch(self: 'ServerConfig') -> str:
+ """Used when launching this config via xm config."""
+ return ','.join(
+ self.prefill_slices + self.generate_slices + self.interleaved_slices
+ )
+
+
+@dataclasses.dataclass
+class InstantiatedEngines:
+ prefill_engines: List[engine_api.Engine]
+ generate_engines: List[engine_api.Engine]
+ interleaved_engines: List[engine_api.Engine]
+
+
+# ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼#
+
+
+def get_test_engine(devices: Devices, weight: int) -> engine_api.Engine:
+ del devices
+ return mock_engine.TestEngine(
+ batch_size=8,
+ cache_length=32,
+ weight=weight,
+ )
+
+
+@dataclasses.dataclass
+class CPUTestServer(ServerConfig):
+ prefill_slices = ('cpu=1',)
+ generate_slices = ('cpu=1',)
+ prefill_engine_create_fns = (functools.partial(get_test_engine, weight=2),)
+ generate_engine_create_fns = (functools.partial(get_test_engine, weight=4),)
+
+
+@dataclasses.dataclass
+class InterleavedCPUTestServer(ServerConfig):
+ interleaved_slices = ('cpu=1',)
+ interleaved_engine_create_fns = (
+ functools.partial(get_test_engine, weight=2),
+ )
+
+
+# ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼#
+
+
+def slice_to_num_chips(s: str) -> int:
+ """Converts a TPU spec like v5e=4x2 to the number of chips, 8."""
+ # Account for the case where it is written 'v5e:4x2'.
+ delim = '=' if '=' in s else ':'
+ i = math.prod([int(c) for c in s.split(delim)[1].split('x')])
+ return i
+
+
+def _split_devices_by_slices(
+ devices: list[Devices], slices: list[int]
+) -> List[List[Devices]]:
+ """Converts an ordered list of devices into slices."""
+ assert sum(slices) == len(devices), f'{sum(slices)} != {len(devices)}'
+ cumsum = 0
+ slice_split_devices = []
+ for sl in slices:
+ slice_split_devices.append(devices[cumsum : cumsum + sl])
+ cumsum += sl
+ return slice_split_devices
+
+
+def get_engines(
+ server_config: Type[ServerConfig], devices: List[Devices]
+) -> InstantiatedEngines:
+ """Processes config to get the appropriate engines.
+
+ Args:
+ server_config: ServerConfig.
+ devices: Device objects.
+
+ Returns:
+ Instantiated engines!
+
+ Devices are popped in order!
+ """
+ # Now, we need to split devices by slice due to TPU backend config.
+ slices: list[int] = [
+ slice_to_num_chips(s)
+ for s in list(server_config.prefill_slices)
+ + list(server_config.generate_slices)
+ + list(server_config.interleaved_slices)
+ ]
+ if sum(slices) != len(devices):
+ raise ValueError(
+ f'The number of available devices ({len(devices)}) do not match the '
+ f'expected number of devices on all the slices ({sum(slices)}) '
+ 'specified in the server_config:\n'
+ f'{server_config.prefill_slices=}\n'
+ f'{server_config.generate_slices=}\n'
+ f'{server_config.interleaved_slices=}\n'
+ )
+ # e.g. [[tpu_0], [tpu_1]] corresponding to prefill: v5e=1x1
+ # generate = v5e=1x1; or [[tpu_0, tpu_1, tpu_2, tpu_3]] corresponding to
+ # interleaved: v5e=2x2
+ split_devices = _split_devices_by_slices(devices, slices)
+ prefill_engines = [
+ e(split_devices.pop(0)) for e in server_config.prefill_engine_create_fns
+ ]
+ generate_engines = [
+ e(split_devices.pop(0)) for e in server_config.generate_engine_create_fns
+ ]
+ # These share chips and weights for prefill and generation.
+ interleaved_engines = [
+ e(split_devices.pop(0))
+ for e in server_config.interleaved_engine_create_fns
+ ]
+ return InstantiatedEngines(
+ prefill_engines, generate_engines, interleaved_engines
+ )
\ No newline at end of file
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/core/implementations/__init__.py b/maxtext-setup/jetstream/build/lib/jetstream/core/implementations/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c38dc3b14ab36f34985ad3f1b20071f4a6a16e82
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/core/implementations/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/__init__.py b/maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c38dc3b14ab36f34985ad3f1b20071f4a6a16e82
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/config.py b/maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0d5aeacb7f34c0c07e741720a08baefb55e30e1
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/config.py
@@ -0,0 +1,30 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Config for mock."""
+
+from typing import Type
+
+
+from jetstream.core import config_lib
+
+def get_server_config(config_str: str) -> Type[config_lib.ServerConfig]:
+ match config_str:
+ case 'InterleavedCPUTestServer':
+ server_config = config_lib.InterleavedCPUTestServer
+ case 'CPUTestServer':
+ server_config = config_lib.CPUTestServer
+ case _:
+ raise NotImplementedError
+ return server_config
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/server.py b/maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/server.py
new file mode 100644
index 0000000000000000000000000000000000000000..6355469c720f47baddd0c4adc02b8782ab16963f
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/core/implementations/mock/server.py
@@ -0,0 +1,49 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a mock server."""
+
+from typing import Sequence
+
+from absl import app
+from absl import flags
+
+from jetstream.core.implementations.mock import config as mock_config
+from jetstream.core import server_lib
+
+
+_PORT = flags.DEFINE_integer('port', 9000, 'port to listen on')
+_CONFIG = flags.DEFINE_string(
+ 'config',
+ 'InterleavedCPUTestServer',
+ 'available servers',
+)
+
+def main(argv: Sequence[str]):
+ del argv
+ # No devices for local cpu test. A None for prefill and a None for generate.
+ devices = server_lib.get_devices()
+ server_config = mock_config.get_server_config(_CONFIG.value)
+ # We separate credential from run so that we can unit test it with local credentials.
+ # TODO: Add grpc credentials for OSS.
+ jetstream_server = server_lib.run(
+ port=_PORT.value,
+ config=server_config,
+ devices=devices,
+ )
+ jetstream_server.wait_for_termination()
+
+
+if __name__ == '__main__':
+ app.run(main)
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/core/orchestrator.py b/maxtext-setup/jetstream/build/lib/jetstream/core/orchestrator.py
new file mode 100644
index 0000000000000000000000000000000000000000..bebbb64fcbcabb0c3cd0fe0de011bbf876bf2025
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/core/orchestrator.py
@@ -0,0 +1,651 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Orchestrates the engines for the inference workflow with performance optimization.
+
+1. A client sends a DecodeRequest via gRPC to the server, an 'LLMOrchestrator'.
+2. This gets wrapped as an 'ActiveRequest' inside the orchestrator, with a
+ 'return_channel' queue as a place that output tokens can be placed.
+ - The ActiveRequest is placed on the 'prefill_queue'.
+ - A while loop runs continuously, yielding any tokens placed on the return
+ channel until an end condition is met (EOS token or max tokens).
+3. There is a prefill_thread per prefill_engine, each of which runs on a
+ distinct prefill_slice.
+4. There is a generate_thread per generate_engine, each of which runs on a
+ distinct generate_slice.
+5. Within a prefill thread:
+ - It attempts to pop ActiveRequests off the prefill_queue.
+ - It tokenizes the request.
+ - When successful, it performs a prefill operation, transfers the kv cache
+ to the generation slice and pops this information (still wrapped in the
+ same ActiveRequest) onto the generation queue.
+6. Within a generation thread:
+ - There is a queue of integers representing 'available slots'.
+ - It checks if there is something on both the slots_queue and generation_
+ queue.
+ - If so, the kv_cache associated with that request into the decoding state
+ of the generation loop at the relevant slot.
+ - Regardless, it performs a step.
+ - It takes the sampled tokens, and places them on a 'detokenizing_queue'.
+7. Within the detokenizing thread:
+ - Tokens are detokenized for every 'slot' in a given set of sampled tokens.
+ - When an end condition is met, the 'slot' integer is returned to the
+ respective generation queue.
+ - This does mean that a single generation step may run after detokenizing
+ indicates that row is no longer valid (if the detokenizing is running behind
+ generation steps), this is fine as it avoids detokenizing being blocking of
+ the generate thread.
+
+If you haven't worked with concurrency in python before - queues are thread-safe
+by default, so we can happily use them to transfer pointers to data between
+different processes. The structure of this server is simple as a result - a
+thread for each thing we might want to do (prefill, transfer, generate,
+detokenize), and corresponding queues that an active request is passed between.
+The same goes for the 'return_channel' of the request itself, where we can just
+pop tokens once they are done and try to pop them back to transmit them over
+grpc.
+It is literally queues all the way down! :)
+The primary concern is GIL contention between threads, which is why we block
+on queues that don't have an ongoing activity (i.e. everything but the
+generation queue) because we don't control to go back to those queues until
+necessary. Blocking means that the GIL doesn't switch back to that thread,
+wheras continual queue get operations 'chop' control and mean that we do not
+achieve good throughput. This is okay on the prefill/transfer/detokenisation
+threads because we don't need to do anything other than react to the presence
+of items on these queues, wheras the generation thread needs to also run a
+step - so it cannot block until it has new things to insert.
+
+## Testing
+This server is intended to be easy to locally test.
+
+Either use :orchestrator test, which tests the multi-threading components,
+:server_test, which extends this to test grpc_components, or run it locally
+to debug hangs due to bugs in threads (it is easier to debug with live logs).
+"""
+
+import dataclasses
+import functools
+import itertools
+import logging
+import os
+import queue
+import signal
+import sys
+import threading
+import time
+import traceback
+import json
+from typing import Any, Iterable, Optional, Union
+
+import grpc
+import jax
+from jetstream.core.proto import jetstream_pb2
+from jetstream.core.proto import jetstream_pb2_grpc
+from jetstream.engine import engine_api
+from jetstream.engine import token_utils
+import numpy as np
+
+
+root = logging.getLogger()
+root.setLevel(logging.DEBUG)
+
+handler = logging.StreamHandler(sys.stdout)
+handler.setLevel(logging.DEBUG)
+formatter = logging.Formatter(
+ '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+)
+handler.setFormatter(formatter)
+root.addHandler(handler)
+
+
+def delete_pytree(p):
+ def delete_leaf(leaf):
+ if isinstance(leaf, jax.Array):
+ leaf.delete()
+ del leaf
+
+ jax.tree_map(delete_leaf, p)
+
+
+@dataclasses.dataclass
+class ActiveRequest:
+ """Current state of the driver."""
+
+ #################### Information relevant for generation #####################
+ max_tokens: int
+ vocab: str
+ # [num_samples,] which corresponds to whether each sample is complete for the
+ # requests.
+ complete: Optional[np.ndarray] = None
+ prefill_result: Any = None
+ #################### Information relevant for prefill ########################
+ history_path: Optional[str] = None
+ prefill_text: Optional[str] = None
+ ################## Information relevant for detokenisation ###################
+ # Which generate step this was added at.
+ generate_timestep_added: Optional[int] = None
+ # We keep prefill and decode information together in the same object so that
+ # there is less indirection about where this return channel is.
+ # The return channel returns a list of strings, one per sample for that query.
+ return_channel: queue.Queue[list[str]] = dataclasses.field(
+ default_factory=queue.Queue
+ )
+
+ def next(self: 'ActiveRequest'):
+ """Blocks until the next token is available, call from RPC threads."""
+ return self.return_channel.get()
+
+ def enqueue_tokens(self, generated_tokens: list[str]):
+ """Records information about the step.
+
+ Args:
+ generated_tokens: One token to put into the return channel
+
+ This should be called only from within the Drivers background thread.
+ """
+ self.return_channel.put(generated_tokens)
+
+
+class JetThread(threading.Thread):
+ """Thread that kills the program if it fails.
+
+ If a driver thread goes down, we can't operate.
+ """
+
+ def run(self):
+ try:
+ super().run()
+ except Exception as e: # pylint: disable=broad-exception-caught
+ print(f'Thread {self.name} encountered an error: {e}')
+ traceback.print_exc()
+ os.kill(os.getpid(), signal.SIGKILL)
+
+
+def _abort_or_raise(
+ context: grpc.ServicerContext | None, code: grpc.StatusCode, details: str
+):
+ """Safely aborts a gRPC context if available, or raises an Exception."""
+ if context is None:
+ raise RuntimeError(details)
+
+ context.abort(code, details)
+
+
+class Driver:
+ """Drives the engines."""
+
+ _prefill_engines: list[engine_api.Engine]
+ _generate_engines: list[engine_api.Engine]
+ # Allows us to pre-load the params, primarily so that we can iterate quickly
+ # on the driver in colab without reloading weights.
+ _prefill_params: Optional[dict[int, Any]] = {}
+ _generate_params: Optional[dict[int, Any]] = {}
+ # Stage 1
+ _prefill_backlog: queue.Queue[ActiveRequest | None]
+ # Stage 2
+ # We keep this as a dict to avoid a possibly expensive object comparison
+ # when logging the index of the generate engine we send a prefill result
+ # to, it allows us to natively have the index from the min operation, rather
+ # than have to call .index()
+ _generate_backlogs: dict[int, queue.Queue[ActiveRequest | None]] = {}
+ # Stage 3
+ # This can be a list because we can pass it as an arg to generate and
+ # detokenize threads. It is a list of tokens to be detokenized.
+ _detokenize_backlogs: list[queue.Queue[engine_api.ResultTokens]] = []
+ _generate_slots: list[queue.Queue[int]] = []
+ _active_requests: list[queue.Queue[tuple[int, ActiveRequest | None]]] = []
+
+ def __init__(
+ self,
+ prefill_engines=None,
+ generate_engines=None,
+ prefill_params=None,
+ generate_params=None,
+ ):
+ logging.info(
+ 'Initialising driver with %d prefill engines and %d generate engines.',
+ len(prefill_engines),
+ len(generate_engines),
+ )
+ self._prefill_engines = prefill_engines
+ self._generate_engines = generate_engines
+ self._prefill_params = prefill_params if prefill_params else {}
+ self._generate_params = generate_params if generate_params else {}
+ # Stages 1-4 represent the life cycle of a request.
+ # Stage 1
+ # At first, a request is placed here in order to get prefilled.
+ self._prefill_backlog = queue.Queue()
+ # Stage 2
+ # Each generate engine accesses its own generate backlog.
+ self._generate_backlogs = {
+ idx: queue.Queue() for idx, _ in enumerate(generate_engines)
+ }
+ # Stage 3
+ # After generation, ActiveRequests are placed on the detokenization backlog
+ # for tokens to be sent into each ActiveRequest's return channel.
+ # We have one of these per generate engine to simplify the logic keeping
+ # track of which generation engine to replace slots on.
+ # This is a queue of either - tuple[int, ActiveRequest] which represents our
+ # active requests, or tuple[int, sample_tokens]. We combine these into one
+ # queue because it allows us to be somewhat clever with how we do
+ # detokenization.
+ # If the detokenization receives an (int, ActiveRequest) this signifies
+ # that slot int should from now be placing tokens in the return channel of
+ # the ActiveRequest.
+ # If it receives (int, sample_tokens) then it actually
+ # does a detokenisation for any slots which have previously been set active
+ # via the previous kind of object, and the int is used to log which step
+ # the tokens were created at. By having them in one queue we prevent
+ # the possibility of race conditions where a slot is made live before the
+ # tokens are ready and it receives tokens from a different sequence,
+ # or tokens detokenized before the relevant slot is live.
+ self._detokenize_backlogs = [queue.Queue() for _ in generate_engines]
+ # Finally we have a queue that doesn't represent a stage, but tracks the
+ # internal status of a request within the generation loop.
+ # a) A queue of integers representing available 'slots' in the decode
+ # operation. I.e. potentially available rows in the batch and/or
+ # microbatch. When we want to insert a prefill result, we pop an integer
+ # to insert at. When this is empty, it means all slots are full.
+
+ # Construct a)
+ self._generate_slots = [queue.Queue() for _ in generate_engines]
+ _ = [
+ [
+ self._generate_slots[idx].put(i)
+ for i in range(engine.max_concurrent_decodes)
+ ]
+ for idx, engine in enumerate(generate_engines)
+ ]
+
+ # Kick off all our threads
+ self._prefill_threads = [
+ JetThread(
+ target=functools.partial(self._prefill_thread, idx, engine),
+ name=f'prefill-{idx}',
+ )
+ for idx, engine in enumerate(self._prefill_engines)
+ ]
+ self._generate_threads = [
+ JetThread(
+ target=functools.partial(
+ self._generate_thread,
+ idx,
+ engine,
+ self._generate_slots[idx],
+ self._detokenize_backlogs[idx],
+ ),
+ name=f'generate-{idx}',
+ )
+ for idx, engine in enumerate(self._generate_engines)
+ ]
+ # Construct b)
+ self.detokenize_threads = [
+ JetThread(
+ target=functools.partial(
+ self._detokenize_thread,
+ idx,
+ engine,
+ self._generate_slots[idx],
+ self._detokenize_backlogs[idx],
+ ),
+ name=f'detokenize-{idx}',
+ )
+ for idx, engine in enumerate(self._generate_engines)
+ ]
+ self._all_threads = list(
+ itertools.chain(
+ self._prefill_threads,
+ self._generate_threads,
+ self.detokenize_threads,
+ )
+ )
+ self.live = True
+ # Kick off all threads
+ for t in self._all_threads:
+ t.start()
+
+ def stop(self):
+ """Stops the driver and all background threads."""
+ # Signal to all threads that they should stop.
+ self.live = False
+
+ all_backlogs = list(
+ itertools.chain(
+ [self._prefill_backlog],
+ self._generate_backlogs.values(),
+ self._detokenize_backlogs,
+ )
+ )
+
+ while any(t.is_alive() for t in self._all_threads):
+ # Empty all backlogs and mark any remaining requests as cancelled.
+ for q in all_backlogs:
+ while True:
+ try:
+ r = q.get_nowait()
+ if r is None:
+ continue
+ elif isinstance(r, ActiveRequest):
+ r.return_channel = None
+ else: # detokenize backlog
+ _, r = r
+ if isinstance(r, ActiveRequest):
+ r.return_channel = None
+ except queue.Empty:
+ break
+
+ # Put sentinels to unblock threads.
+ for q in all_backlogs:
+ try:
+ q.put_nowait(None)
+ except queue.Full:
+ pass
+
+ # Wait for all threads to stop.
+ for t in self._all_threads:
+ t.join()
+
+ def get_total_concurrent_requests(self) -> int:
+ """Returns the total number of concurrent requests the driver can service."""
+ # We don't support filling all backlogs at once because it can cause GIL
+ # contention.
+ total_max_concurrent_decodes = sum(
+ [e.max_concurrent_decodes for e in self._generate_engines]
+ )
+ return total_max_concurrent_decodes
+
+ def place_request_on_prefill_queue(self, request: ActiveRequest):
+ """Used to place new requests for prefilling and generation."""
+ self._prefill_backlog.put(request)
+
+ def _load_cache_history(self, path: str) -> Union[None, Any]:
+ """Loads previous kv cache for a longer conversation."""
+ if path:
+ raise NotImplementedError
+ else:
+ return None
+
+ def _prefill_thread(
+ self,
+ idx: int,
+ prefill_engine: engine_api.Engine,
+ generate_backpressure: int = 3,
+ ):
+ """Thread which runs in the background performing prefills."""
+ logging.info('---------Spinning up prefill thread %d.---------', idx)
+ prefill_params = self._prefill_params[idx]
+ metadata = prefill_engine.get_tokenizer()
+ vocab = token_utils.load_vocab(metadata.path, metadata.extra_ids)
+ logging.info('---------Prefill params %d loaded.---------', idx)
+
+ while self.live:
+ # We don't want to keep lots of kv caches live in memory on the prefill
+ # slice that aren't about to be sent over to a generation slice.
+ if self._generate_backlogs[idx].qsize() < generate_backpressure:
+ # Check if there is anything on the prefill backlog, pop if so.
+ try:
+ request = self._prefill_backlog.get(block=True)
+ if request is None:
+ break
+ tempbos_id = request.vocab['bos_id'] if 'bos_id' in request.vocab else vocab.bos_id
+ tempeos_id = request.vocab['eos_id'] if 'eos_id' in request.vocab else vocab.eos_id
+ temppad_id = request.vocab['pad_id'] if 'pad_id' in request.vocab else vocab.pad_id
+
+ # TODO: Implement hot/cold cache for history.
+ history = self._load_cache_history(request.history_path) # pylint: disable = assignment-from-none
+ # Tokenize, and introduce a leading dimension
+ is_bos = not bool(request.history_path)
+ logging.info(
+ 'Prefilling on prefill engine %d : prefill queue size, %d,'
+ ' is_bos: %s, history: %s',
+ idx,
+ self._prefill_backlog.qsize(),
+ is_bos,
+ request.history_path,
+ ) # pylint: disable = line-too-long
+ padded_tokens, true_length = token_utils.tokenize_and_pad(
+ request.prefill_text,
+ vocab,
+ is_bos=is_bos,
+ eos_id = tempeos_id,
+ pad_id = temppad_id,
+ bos_id = tempbos_id,
+ max_prefill_length=prefill_engine.max_prefill_length,
+ )
+ # Compute new kv cache for the prefill_text, conditional on
+ # history.
+ prefill_result = prefill_engine.prefill(
+ params=prefill_params,
+ existing_prefix=history,
+ padded_tokens=padded_tokens,
+ true_length=true_length,
+ )
+ request.prefill_result = prefill_result
+ # Once prefill is complete, place it on the generation queue.
+ self._generate_backlogs[idx].put(request)
+ logging.info(
+ 'Placed request on the generate queue,'
+ f' {self._generate_backlogs[idx].qsize()=}'
+ )
+ except queue.Empty:
+ # Otherwise, don't do anything!
+ pass
+
+ def _generate_thread(
+ self,
+ idx: int,
+ generate_engine: engine_api.Engine,
+ my_slots: queue.Queue[int],
+ my_detokenize_backlog: queue.Queue[tuple[int, engine_api.ResultTokens]],
+ backpressure: int = 3,
+ ):
+ """Step token generation and insert prefills from backlog.
+
+ Args:
+ idx: Idx corresponding to which generation engine idx this is.
+ generate_engine: The generate engine corresponding to this thread.
+ my_slots: Integers representing free my_slots.
+ my_detokenize_backlog: Detokenize backlog for this generate engine.
+ backpressure: How many steps we can queue up before pausing, allows us to
+ hide dispatch times because jit calls are dispatched one after another.
+ We have this in the first place because we don't want to enqueue
+ thousands of steps.
+ """
+ logging.info('---------Spinning up generate thread %d.---------', idx)
+ # Keep track of what step tokens were generated at.
+ generate_timestep = 0
+ # State to store things like running kv cache in.
+ decode_state = generate_engine.init_decode_state()
+ generate_params = self._generate_params[idx]
+ logging.info('---------Generate params %d loaded.---------', idx)
+ time_of_last_generate = time.time()
+ time_of_last_print = time.time()
+ while self.live:
+ if (time.time() - time_of_last_print) > 1:
+ logging.info(
+ 'Generate thread making a decision with:'
+ f' prefill_backlog={self._prefill_backlog.qsize()} generate_free_slots={my_slots.qsize()}'
+ )
+ time_of_last_print = time.time()
+ # Check if there are any free my_slots.
+ if not my_slots.empty() and not self._generate_backlogs[idx].empty():
+ # Only get requests from the backlog corresponding to this engine.
+ new_request = self._generate_backlogs[idx].get()
+ if new_request is None:
+ break
+ slot = my_slots.get()
+ logging.info(
+ 'Generate slice %d slot %d step %d',
+ idx,
+ slot,
+ generate_timestep,
+ )
+ decode_state = generate_engine.insert(
+ new_request.prefill_result, decode_state, slot=slot
+ )
+ delete_pytree(new_request.prefill_result)
+ new_request.generate_timestep_added = generate_timestep
+ new_request.complete = np.zeros(
+ (generate_engine.samples_per_slot,), dtype=np.bool_
+ )
+ my_detokenize_backlog.put((slot, new_request))
+
+ if my_detokenize_backlog.qsize() < backpressure:
+ decode_state, sampled_tokens = generate_engine.generate(
+ generate_params, decode_state
+ )
+ sampled_tokens.copy_to_host_async()
+ my_detokenize_backlog.put((generate_timestep, sampled_tokens))
+ generate_timestep += 1
+ logging.info(
+ 'Generate engine %d step %d - slots free : %d / %d, took %.2fms',
+ idx,
+ generate_timestep,
+ my_slots.qsize(),
+ generate_engine.max_concurrent_decodes,
+ (time.time() - time_of_last_generate) * 10**3,
+ )
+ time_of_last_generate = time.time()
+
+ def _detokenize_thread(
+ self,
+ idx: int,
+ generate_engine: engine_api.Engine,
+ my_slots: queue.Queue[int],
+ my_detokenize_backlog: queue.Queue[
+ Union[tuple[int, engine_api.ResultTokens], tuple[int, ActiveRequest]]
+ ],
+ ):
+ """Detokenize sampled tokens and returns them to the user."""
+ del idx
+ # One of these per generate engine.
+ # For all filled my_slots, pop the sampled token onto the relevant
+ # requests return channel. If it done, place it back onto free slots.
+ metadata = generate_engine.get_tokenizer()
+ vocab = token_utils.load_vocab(metadata.path, metadata.extra_ids)
+
+ my_live_requests = {
+ i: None for i in range(generate_engine.max_concurrent_decodes)
+ }
+
+ while self.live:
+ try:
+ data = my_detokenize_backlog.get(block=True)
+ if data is None:
+ break
+ start_detokenise_time = time.time()
+ if isinstance(data[1], engine_api.ResultTokens):
+ # We want to detokenise them.
+ generate_timestep_added, result_tokens = data
+ # Disable attribute error because pytype doesn't know this
+ # is a result tokens, and we can't annotate the tuple.
+ result_tokens = result_tokens.convert_to_numpy() # pytype: disable=attribute-error
+
+ for slot, request in my_live_requests.items():
+ if request is not None:
+ # print(vocab)
+ # print(dir(vocab))
+ # req_vocab = json.loads(request.vocab)
+ tempbos_id = request.vocab['bos_id'] if 'bos_id' in request.vocab else vocab.bos_id
+ tempeos_id = request.vocab['eos_id'] if 'eos_id' in request.vocab else vocab.eos_id
+ temppad_id = request.vocab['pad_id'] if 'pad_id' in request.vocab else vocab.pad_id
+
+ results, complete = token_utils.process_result_tokens(
+ slot=slot,
+ slot_max_length=request.max_tokens,
+ result_tokens=result_tokens,
+ vocab=vocab,
+ eos_id = tempeos_id,
+ pad_id = temppad_id,
+ bos_id = tempbos_id,
+ complete=request.complete,
+ )
+ request.complete = complete
+ # Return some tokens.
+ request.enqueue_tokens(results)
+ if request.complete.all():
+ # Place the slot back on the free queue.
+ my_live_requests[slot] = None
+ my_slots.put(slot)
+ logging.info(
+ 'Detokenising generate step %d took %.2fms',
+ generate_timestep_added,
+ (time.time() - start_detokenise_time) * 10**3,
+ )
+ else:
+ # We want to update a slot with the new channel.
+ slot, active_request = data
+ my_live_requests[slot] = active_request
+
+ except queue.Empty:
+ # Nothing to detokenize!
+ pass
+
+
+class LLMOrchestrator(jetstream_pb2_grpc.OrchestratorServicer):
+ """Coordinates a set of prefill and generate slices for LLM decoding."""
+
+ _driver: Driver
+
+ def __init__(self, driver: Driver):
+ self._driver = driver
+
+ def Decode(
+ self,
+ request: jetstream_pb2.DecodeRequest,
+ context: Optional[grpc.ServicerContext] = None,
+ ) -> Iterable[jetstream_pb2.DecodeResponse]:
+ """Decode."""
+ if context is None:
+ logging.warning(
+ 'LLM orchestrator is being used in offline test mode, and will not'
+ ' respond to gRPC queries - only direct function calls.'
+ )
+ # Wrap request as an ActiveRequest.
+ active_request = ActiveRequest(
+ max_tokens=request.max_tokens,
+ vocab=json.loads(request.vocab),
+ history_path=request.session_cache,
+ prefill_text=request.additional_text,
+ )
+ # The first stage is being prefilled, all other stages are handled
+ # inside the driver (transfer, generate*N, detokenize).
+ try:
+ self._driver.place_request_on_prefill_queue(active_request)
+ except queue.Full:
+ # Safely abort the gRPC server thread with a retriable error.
+ _abort_or_raise(
+ context=context,
+ code=grpc.StatusCode.RESOURCE_EXHAUSTED,
+ details=(
+ 'The driver prefill queue is full and more requests cannot be'
+ ' handled. You may retry this request.'
+ ),
+ )
+ logging.info(
+ 'Placed request on the prefill queue.',
+ )
+
+ while not (
+ active_request.complete and active_request.return_channel.empty()
+ ):
+ # When an active request is created a queue is instantiated. New tokens
+ # are placed there during the decoding loop, we pop from that queue by
+ # using the .next method on the active request.
+ # Yielding allows for the response to be a streaming grpc call - which
+ # can be called via iterating over a for loop on the other side.
+ # The DecodeResponse stream should consume all generated tokens in
+ # return_channel when complete signal is received. It should check if
+ # return_channel is empty to decide if it should exit the while loop.
+ yield jetstream_pb2.DecodeResponse(response=active_request.next())
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/core/orchestrator_test.py b/maxtext-setup/jetstream/build/lib/jetstream/core/orchestrator_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9880f93b01f3a932712b27085fb99b13ef63991
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/core/orchestrator_test.py
@@ -0,0 +1,103 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Integration test of the orchestrator.
+
+This test tests the multi-htreaded orchestrator, where a prefill request is
+popped onto a prefill queue, prefilled, sent to a generation queue and run for
+a number of decoding steps.
+
+In operation, it will use gRPC so we can 'yield' from the function to get return
+values in the same way that they would be streamed back.
+
+Similar to 'mock_engine_test' we can use known token values and a singleton
+weight to test our operation.
+
+Let the prefill engine have a weight of [2] and the generate engine have a
+weight of [3].
+
+I.e. if we prefill [2, 65, 66] (i.e. , 'A', 'B') using an ACII vocab,
+we should get [4, 130, 132].
+
+If we then insert that and run three generation steps, we should see
+266+0 / 2 = 266
+266 + [266] / 4 = 332
+266 + [266, 332] / 4 = 415
+I.e. ['Ċ', 'Ō', 'Ɵ'] when converted back with chr().
+
+Therefore we should get back the character sequence '$lǔ' if we request 3 tokens
+decoded (these are the ascii chars at those indices which is what the test
+tokenizer returns).
+"""
+
+from absl.testing import absltest
+from jetstream.core import orchestrator
+from jetstream.core.proto import jetstream_pb2
+from jetstream.engine import mock_engine
+
+
+class OrchestratorTest(absltest.TestCase):
+
+ def _setup_driver(self):
+ prefill_engine = mock_engine.TestEngine(
+ batch_size=32, cache_length=256, weight=2.0
+ )
+ # Create a generate engine with a different set of weights
+ # so that we can test that the right one is in use at a given time.
+ generate_engine = mock_engine.TestEngine(
+ batch_size=4, cache_length=32, weight=4.0
+ )
+ driver = orchestrator.Driver(
+ prefill_engines=[prefill_engine],
+ generate_engines=[generate_engine],
+ prefill_params=[prefill_engine.load_params()],
+ generate_params=[generate_engine.load_params()],
+ )
+ return driver
+
+ def test_orchestrator(self):
+ """Test the multithreaded orchestration."""
+ driver = self._setup_driver()
+ client = orchestrator.LLMOrchestrator(driver=driver)
+
+ # The string representation of np.array([[65, 66]]), [2] will be prepend
+ # as BOS.
+ text = 'AB'
+
+ request = jetstream_pb2.DecodeRequest(
+ session_cache='',
+ additional_text=text,
+ priority=1,
+ max_tokens=3,
+ )
+ iterator = client.Decode(request)
+ # chr of [266, 332, 415].
+ expected_tokens = ['Ċ', 'Ō', 'Ɵ', '']
+ counter = 0
+ for token in iterator:
+ # Tokens come through as bytes.
+ print(
+ 'actual output: '
+ + bytes(token.response[0], encoding='utf-8').decode()
+ )
+ assert (
+ bytes(token.response[0], encoding='utf-8').decode()
+ == expected_tokens[counter]
+ )
+ counter += 1
+ driver.stop()
+
+
+if __name__ == '__main__':
+ absltest.main()
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/core/proto/__init__.py b/maxtext-setup/jetstream/build/lib/jetstream/core/proto/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c38dc3b14ab36f34985ad3f1b20071f4a6a16e82
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/core/proto/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/core/proto/jetstream_pb2.py b/maxtext-setup/jetstream/build/lib/jetstream/core/proto/jetstream_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7815029c197f71495d182d238d76d9fc972bf47
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/core/proto/jetstream_pb2.py
@@ -0,0 +1,44 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: jetstream/core/proto/jetstream.proto
+# Protobuf Python Version: 4.25.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+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')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'jetstream.core.proto.jetstream_pb2', _globals)
+# if _descriptor._USE_C_DESCRIPTORS == False:
+# DESCRIPTOR._options = None
+# _globals['_DECODEREQUEST']._serialized_start=57
+# _globals['_DECODEREQUEST']._serialized_end=173 #158
+# _globals['_DECODERESPONSE']._serialized_start=175 #160
+# _globals['_DECODERESPONSE']._serialized_end=209 #194
+# _globals['_ORCHESTRATOR']._serialized_start=196
+# _globals['_ORCHESTRATOR']._serialized_end=289
+# @@protoc_insertion_point(module_scope)
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/core/proto/jetstream_pb2_grpc.py b/maxtext-setup/jetstream/build/lib/jetstream/core/proto/jetstream_pb2_grpc.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e2fb885921e7c7a77d0343522118a28d892ba0e
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/core/proto/jetstream_pb2_grpc.py
@@ -0,0 +1,87 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
+"""Client and server classes corresponding to protobuf-defined services."""
+import grpc
+
+from jetstream.core.proto import jetstream_pb2 as jetstream_dot_core_dot_proto_dot_jetstream__pb2
+
+
+class OrchestratorStub(object):
+ """TODO: Merge this with main JetStream core once we settle on an API.
+
+ """
+
+ def __init__(self, channel):
+ """Constructor.
+
+ Args:
+ channel: A grpc.Channel.
+ """
+ self.Decode = channel.unary_stream(
+ '/jetstream_proto.Orchestrator/Decode',
+ request_serializer=jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeRequest.SerializeToString,
+ response_deserializer=jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeResponse.FromString,
+ )
+
+
+class OrchestratorServicer(object):
+ """TODO: Merge this with main JetStream core once we settle on an API.
+
+ """
+
+ def Decode(self, request, context):
+ """Generate the next model tokens.
+ """
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details('Method not implemented!')
+ raise NotImplementedError('Method not implemented!')
+
+
+def add_OrchestratorServicer_to_server(servicer, server):
+ rpc_method_handlers = {
+ 'Decode': grpc.unary_stream_rpc_method_handler(
+ servicer.Decode,
+ request_deserializer=jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeRequest.FromString,
+ response_serializer=jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeResponse.SerializeToString,
+ ),
+ }
+ generic_handler = grpc.method_handlers_generic_handler(
+ 'jetstream_proto.Orchestrator', rpc_method_handlers)
+ server.add_generic_rpc_handlers((generic_handler,))
+
+
+ # This class is part of an EXPERIMENTAL API.
+class Orchestrator(object):
+ """TODO: Merge this with main JetStream core once we settle on an API.
+
+ """
+
+ @staticmethod
+ def Decode(request,
+ target,
+ options=(),
+ channel_credentials=None,
+ call_credentials=None,
+ insecure=False,
+ compression=None,
+ wait_for_ready=None,
+ timeout=None,
+ metadata=None):
+ return grpc.experimental.unary_stream(request, target, '/jetstream_proto.Orchestrator/Decode',
+ jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeRequest.SerializeToString,
+ jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeResponse.FromString,
+ options, channel_credentials,
+ insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/core/server_lib.py b/maxtext-setup/jetstream/build/lib/jetstream/core/server_lib.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f0c10932eac66f6c83cef4220bd6cec1a52ff92
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/core/server_lib.py
@@ -0,0 +1,105 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Contains common functions for a JetStream core server.
+
+See implementations/*/sever.py for examples.
+"""
+
+from concurrent import futures
+import logging
+from typing import Any, Type
+
+import grpc
+import jax
+from jetstream.core import config_lib
+from jetstream.core import orchestrator
+from jetstream.core.proto import jetstream_pb2_grpc
+
+
+_HOST = '[::]'
+
+
+class JetStreamServer:
+ """JetStream grpc server."""
+
+ def __init__(self, driver: orchestrator.Driver, server: grpc.Server):
+ self._driver = driver
+ self._server = server
+
+ def start(self, port, credentials) -> None:
+ self._server.add_secure_port(f'{_HOST}:{port}', credentials)
+ self._server.start()
+
+ def stop(self) -> None:
+ # Gracefully clean up threads in the orchestrator.
+ self._driver.stop()
+ self._server.stop(0)
+
+ def wait_for_termination(self) -> None:
+ self._server.wait_for_termination()
+
+
+def run(
+ port: int,
+ config: Type[config_lib.ServerConfig],
+ devices: Any,
+ credentials: Any = grpc.insecure_server_credentials(),
+ threads: int | None = None,
+) -> JetStreamServer:
+ """Runs a server with a specified config.
+
+ Args:
+ port: Port on which the server will be made available.
+ config: A ServerConfig to config engine, model, device slices, etc.
+ devices: Device objects, will be used to get engine with proper slicing.
+ credentials: Should use grpc credentials by default.
+ threads: Number of RPC handlers worker threads. This should be at least
+ equal to the decoding batch size to fully saturate the decoding queue.
+
+ Returns:
+ JetStreamServer that wraps the grpc server and orchestrator driver.
+ """
+ logging.info('Kicking off gRPC server.')
+ engines = config_lib.get_engines(config, devices=devices)
+ prefill_params = [pe.load_params() for pe in engines.prefill_engines]
+ generate_params = [ge.load_params() for ge in engines.generate_engines]
+ shared_params = [ie.load_params() for ie in engines.interleaved_engines]
+ logging.info('Loaded all weights.')
+ driver = orchestrator.Driver(
+ prefill_engines=engines.prefill_engines + engines.interleaved_engines,
+ generate_engines=engines.generate_engines + engines.interleaved_engines,
+ prefill_params=prefill_params + shared_params,
+ generate_params=generate_params + shared_params,
+ )
+ # We default threads to the total number of concurrent allowed decodes,
+ # to make sure we can fully saturate the model. Set default minimum to 64.
+ threads = threads or max(driver.get_total_concurrent_requests(), 64)
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=threads)) # pytype: disable=wrong-keyword-args
+ jetstream_pb2_grpc.add_OrchestratorServicer_to_server(
+ orchestrator.LLMOrchestrator(driver=driver), server
+ )
+ logging.info('Starting server on port %d with %d threads', port, threads)
+
+ jetstream_server = JetStreamServer(driver, server)
+ jetstream_server.start(port, credentials)
+ return jetstream_server
+
+
+def get_devices() -> Any:
+ """Gets devices locally."""
+ # Run interleaved engine on local device.
+ devices = jax.devices()
+ logging.info('Using local devices for interleaved serving: %d', len(devices))
+ return devices
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/core/server_test.py b/maxtext-setup/jetstream/build/lib/jetstream/core/server_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1f3c0507888f39f885fe5adc3730ddb2bbc0f8d
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/core/server_test.py
@@ -0,0 +1,98 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Tests gRPC server end-to-end.
+
+See orchestrator test for why these characters specifically will be the
+response.
+"""
+
+from typing import Any, Type
+
+from absl.testing import absltest, parameterized
+import grpc
+from jetstream.core import config_lib
+from jetstream.core import server_lib
+from jetstream.core.proto import jetstream_pb2
+from jetstream.core.proto import jetstream_pb2_grpc
+import portpicker
+
+
+class ServerTest(parameterized.TestCase):
+
+ @parameterized.parameters(
+ # Uses weight 2 for prefill, 4 for decode.
+ (
+ config_lib.CPUTestServer,
+ ['Ċ', 'Ō', 'Ɵ', ''],
+ [None, None],
+ ),
+ # Uses the same prefill / generate weights (2).
+ (
+ config_lib.InterleavedCPUTestServer,
+ ['Ċ', 'Ə', 'ɖ', ''],
+ [None],
+ ),
+ )
+ def test_server(
+ self,
+ config: Type[config_lib.ServerConfig],
+ expected_tokens: list[str],
+ devices: list[Any],
+ ):
+ """Sets up a server and requests token responses."""
+ ######################### Server side ######################################
+ port = portpicker.pick_unused_port()
+ print('port: ' + str(port))
+ credentials = grpc.local_server_credentials()
+
+ server = server_lib.run(
+ port=port,
+ config=config,
+ devices=devices,
+ credentials=credentials,
+ )
+ ###################### Requester side ######################################
+ channel = grpc.secure_channel(
+ f'localhost:{port}', grpc.local_channel_credentials()
+ )
+ stub = jetstream_pb2_grpc.OrchestratorStub(channel)
+
+ # The string representation of np.array([[65, 66]]), [2] will be prependd
+ # as BOS
+ text = 'AB'
+ request = jetstream_pb2.DecodeRequest(
+ session_cache='',
+ additional_text=text,
+ priority=1,
+ max_tokens=3,
+ )
+ iterator = stub.Decode(request)
+ counter = 0
+ for token in iterator:
+ # Tokens come through as bytes
+ print(
+ 'actual output: '
+ + bytes(token.response[0], encoding='utf-8').decode()
+ )
+ assert (
+ bytes(token.response[0], encoding='utf-8').decode()
+ == expected_tokens[counter]
+ )
+ counter += 1
+ server.stop()
+
+
+if __name__ == '__main__':
+ absltest.main()
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/engine/__init__.py b/maxtext-setup/jetstream/build/lib/jetstream/engine/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c38dc3b14ab36f34985ad3f1b20071f4a6a16e82
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/engine/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/engine/engine_api.py b/maxtext-setup/jetstream/build/lib/jetstream/engine/engine_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..deb3a592c131beca95335ca7a890c1854d026311
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/engine/engine_api.py
@@ -0,0 +1,225 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Defines the JetStream API.
+
+These functions are the accelerator functions which an outer sampling loop
+could want to call, enabling interleaved (continuous batching) inference.
+"""
+
+import abc
+from typing import Any, Optional, Tuple, Union
+
+from flax import struct
+import jax
+import numpy as np
+
+from jetstream.engine import tokenizer_pb2
+
+
+# The model parameters - their partitioning will be unique for different prefill
+# and decode topoologies.
+Params = Any
+# The result of a prefill operation, often a batch size 1 KVCache.
+Prefix = Any
+# The inputs into a generation step, often a prefill and generate cache tuple.
+DecodeState = Any
+# Accelerator representation of tokens.
+DeviceTokens = Any
+# Cpus asscociated with the mesh.
+CpuDevices = Any
+
+
+@struct.dataclass
+class SlotData:
+ """Class to store slot data."""
+ tokens: Union[jax.Array, np.ndarray]
+ valid: Union[jax.Array, np.ndarray]
+ lengths: Union[jax.Array, np.ndarray]
+
+# pylint: disable=g-doc-args
+@struct.dataclass
+class ResultTokens(abc.ABC):
+ """Class to store returned tokens in.
+
+ We store everything in one array, and keep indexes - because copying
+ a single array to host is much faster.
+ Each tuple represents the indices of the relevant data.
+ """
+
+ # Shape: [batch, tokens.shape[1] + validity.shape[1] + lengths.shape[1]]
+ data: Union[jax.Array, np.ndarray]
+ # The range of indices which contain tokens.
+ tokens_idx: tuple[int, int] = struct.field(
+ pytree_node=False,
+ )
+ # The range of indices which contain the validity of
+ # the tokens.
+ valid_idx: tuple[int, int] = struct.field(
+ pytree_node=False,
+ )
+ # The range of indices which contain the lengths up till now of the lengths
+ # of each generated sequence.
+ length_idx: tuple[int, int] = struct.field(
+ pytree_node=False,
+ )
+ samples_per_slot: int = struct.field(
+ pytree_node=False,
+ )
+
+ def copy_to_host_async(self: 'ResultTokens') -> None:
+ """Copy to host asynchronously."""
+ self.data.copy_to_host_async()
+
+ def convert_to_numpy(self: 'ResultTokens') -> 'ResultTokens':
+ """Converts to numpy."""
+ return ResultTokens(
+ np.array(self.data),
+ self.tokens_idx,
+ self.valid_idx,
+ self.length_idx,
+ self.samples_per_slot,
+ )
+
+ def get_result_at_slot(
+ self, slot: int
+ ) -> SlotData:
+ """Returns the token at a given slot.
+
+ Args:
+ slot: An integer from [0, n) representing an index into the batch.
+
+ Note: implementations of this method must correctly handle
+ microbatches, if microbatches are used.
+ """
+ # Potentially get multiple beams for given slot.
+ start_idx = slot * self.samples_per_slot
+ end_idx = (slot + 1) * self.samples_per_slot
+ # Mask out any non valid tokens.
+ return SlotData(
+ tokens=self.data[start_idx:end_idx, self.tokens_idx[0]:self.tokens_idx[1]],
+ valid=self.data[start_idx:end_idx, self.valid_idx[0]:self.valid_idx[1]],
+ # Only get a 1D representation here
+ lengths=self.data[start_idx:end_idx, self.length_idx[0]:self.length_idx[1]][:, 0]
+ )
+
+
+class Engine(abc.ABC):
+ """The computational core of the generative model server.
+
+ Engine defines an API that models must adhere to as they plug into the
+ JetStream efficient serving infrastructure.
+ """
+
+ @abc.abstractmethod
+ def prefill(
+ self,
+ *,
+ params: Params,
+ existing_prefix: Optional[Prefix] = None,
+ padded_tokens: jax.Array,
+ true_length: int,
+ ) -> Prefix:
+ """Computes a kv-cache for a set of tokens conditional on existing cache.
+
+ existing_prefix (if provided) represents a prefix that has already been
+ processed by the underlying model. tokens is logically appended
+ to the text represented by `existing_prefix`. This method returns a new
+ kv_cache (typically) for the resulting text.
+ """
+
+ @abc.abstractmethod
+ def generate(
+ self,
+ params: Params,
+ decode_state: DecodeState
+ ) -> Tuple[DecodeState, ResultTokens]:
+ """Generates tokens for each sequence being decoded in parallel.
+
+ Generate takes a batch of pre-computed kv-caches, and computes:
+ - the predicted next token for each of the sequences
+ - an updated set of kv-caches
+
+ In the case of pipelining, this will handle N cycles (where each cycle
+ consists of each microbatch progressing through every stage), in
+ non-pipelined code this is a full forward pass. In both cases, this accounts
+ for a full embed-layerstack-unembed-sample operation.
+ """
+
+ @abc.abstractmethod
+ def insert(
+ self,
+ prefix: Prefix,
+ decode_state: DecodeState,
+ slot: int,
+ ) -> DecodeState:
+ """Adds `new_request` into `caches` at 'slot'.
+
+ When decoding multiple requests in parallel, when one request finishes, a
+ new request must be slotted into the recently vacated spot: `insert`!
+
+ This can occur in between and async to generate calls, and takes a lock over
+ that row of the cache.
+
+ The slot may represent a tuple of positions (e.g. microbatch, pipeline stage
+ and batch), but at the engine interface level all of these are exposed as
+ a [0, n) range of slots and converted internally.
+ """
+
+ @abc.abstractmethod
+ def load_params(self, *args, **kwargs) -> Params:
+ """Loads parameters.
+
+ May not be used in full production form, where weights are part of the saved
+ model.
+ """
+
+ @abc.abstractmethod
+ def get_prefix_destination_sharding(self) -> Any:
+ """Returns the shardings necessary to transfer data between engines."""
+
+ @abc.abstractmethod
+ def get_tokenizer(
+ self,
+ ) -> tokenizer_pb2.TokenizerParameters:
+ """Returns the info to construct a sentencepiece tokenizer in py/c++."""
+
+ @abc.abstractmethod
+ def init_decode_state(self, *args, **kwargs) -> DecodeState:
+ """Initialises any state which a generation step transforms."""
+
+ @property
+ @abc.abstractmethod
+ def max_concurrent_decodes(self) -> int:
+ """Total capacity."""
+
+ @property
+ @abc.abstractmethod
+ def samples_per_slot(self) -> int:
+ """Total samples per slot."""
+
+ @property
+ @abc.abstractmethod
+ def max_prefill_length(self) -> int:
+ """Maximum prefill length."""
+
+ @property
+ @abc.abstractmethod
+ def mesh(self) -> jax.sharding.Mesh:
+ """Mesh which the engine is running on."""
+
+ @property
+ @abc.abstractmethod
+ def colocated_cpus(self) -> Union[list[CpuDevices], None]:
+ """CPU devices colocated with the engine's accelerators."""
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/engine/mock_engine.py b/maxtext-setup/jetstream/build/lib/jetstream/engine/mock_engine.py
new file mode 100644
index 0000000000000000000000000000000000000000..69c9d3a0cdee2f4bbc2467abd5ea94049ebb45ce
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/engine/mock_engine.py
@@ -0,0 +1,258 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Simple test engine for the JetStream API described.
+
+Contains simple functions that we can hand calculate the desired outcome of.
+
+Prefill: Doubles the sequence by multiplying it with an integer weight.
+Insert: Writes this sequence into a cache row.
+Generate step: Return sum(prefill_cache) + sum(generate_cache)/weight.
+
+I.e. if we prefill [2, 65, 66] (i.e. , 'A', 'B') using an ACII vocab,
+we should get [4, 130, 132].
+
+If we then insert that and run three generation steps, we should see
+266+0 / 2 = 266
+266 + [266] /2 = 399
+266 + [266, 399] /2 = 598
+I.e. ['Ċ', 'Ə', 'ɖ'] when converted back with chr()
+"""
+
+import functools
+from typing import Any, Optional, Tuple
+
+from flax import struct
+import jax
+from jax.experimental import mesh_utils
+import jax.numpy as jnp
+
+from jetstream.engine import engine_api
+from jetstream.engine import tokenizer_pb2
+
+
+Params = jax.Array # [1,].
+Prefix = jax.Array # [batch,] of strings with different lengths.
+
+
+@struct.dataclass
+class DecodeState:
+ """The inputs into a generation step."""
+ prefill_cache: jax.Array
+ generate_cache: jax.Array
+ generate_cache_index: int
+ generate_lengths: jax.Array
+
+
+class TestEngine(engine_api.Engine):
+ """The computational core of the generative model server.
+
+ Engine defines an API that models must adhere to as they plug into the
+ JetStream efficient serving infrastructure.
+ """
+
+ def __init__(self, batch_size: int, cache_length: int, weight: float):
+ self.prefill_cache_batch = batch_size
+ self.generate_cache_batch = batch_size
+ self.cache_length = cache_length
+ self.weight = weight
+ self._mesh = jax.sharding.Mesh(
+ mesh_utils.create_device_mesh((1, 1, 1), jax.devices()), ('x', 'y', 'z')
+ )
+
+ def load_params(self) -> Params:
+ """Loads model weights."""
+ # An integer, used to multiply inputs.
+ return jnp.array([self.weight], dtype=jnp.float32)
+
+ @functools.partial(jax.jit, static_argnums=(0,))
+ def prefill(
+ self,
+ *,
+ params: Params,
+ existing_prefix: Optional[jax.Array] = None,
+ padded_tokens: jax.Array,
+ true_length: int,
+ ) -> Prefix:
+ """Computes a kv-cache for a new generate request.
+
+ Args:
+ params: Scalar multiplier.
+ existing_prefix: If provided, represents a prefix that has already been
+ processed by the underlying model.
+ padded_tokens: Logically appended tokens to any existing prefix, this is
+ what we compute prefill on.
+ true_length: The real length of the tokens, pre-pad.
+ Returns:
+ kv_cache: For the resulting text.
+ """
+ if existing_prefix is not None:
+ raise NotImplementedError
+ del true_length
+ assert padded_tokens.ndim == 1
+ # Wait to simulate model step time.
+ fake_size = 4096
+ fake_work = jnp.ones((fake_size, fake_size)) @ jnp.ones(
+ (fake_size, fake_size)
+ )
+ # Do some fake work that isn't eliminated by dead code elimination (DCE).
+ params = params + fake_work.mean() - fake_work.mean()
+ return padded_tokens[None, :] * params
+
+ @functools.partial(jax.jit, static_argnums=(0,))
+ def generate(
+ self, params: Params, decode_state: DecodeState
+ ) -> Tuple[DecodeState, engine_api.ResultTokens]:
+ """Generates tokens for each sequence being decoded in parallel."""
+ prefill_cache, generate_cache, generate_cache_index, generate_lengths = (
+ decode_state.prefill_cache,
+ decode_state.generate_cache,
+ decode_state.generate_cache_index,
+ decode_state.generate_lengths,
+ )
+ # Sum each row of prefill cache and generate cache to produce new timestep,
+ # multiply by params.
+ l_iota = jax.lax.broadcasted_iota(
+ jnp.int32,
+ (self.generate_cache_batch, self.cache_length),
+ dimension=1,
+ )
+
+ # The generate cache should be circular and right aligned.
+ # TODO: Do we need a left aligned one to test spec sampling?
+ # Don't need the + 1 you normally would, because we don't provide a
+ # token from prefill in the dummy.
+ # This iota and masking is to allow for a cicular cache.
+ length_mask = (
+ -(l_iota - generate_cache_index + 1) % self.cache_length
+ ) <= generate_lengths[:, None]
+ length_masked_gen_cache = generate_cache * length_mask
+ new_timestep = (
+ prefill_cache.sum(axis=-1)
+ + (length_masked_gen_cache.sum(axis=-1) / params)
+ )[:, jnp.newaxis]
+ generate_cache = jax.lax.dynamic_update_slice_in_dim(
+ generate_cache, new_timestep, start_index=generate_cache_index, axis=1
+ )
+ generate_cache_index = (generate_cache_index + 1) % self.cache_length
+ # Wait to simulate model step time.
+ fake_size = 4096
+ fake_work = jnp.ones((fake_size, fake_size)) @ jnp.ones(
+ (fake_size, fake_size)
+ )
+ # Do some fake work that isn't eliminated by dead code elimination (DCE).
+ generate_cache = generate_cache + fake_work.mean() - fake_work.mean()
+ new_lengths = generate_lengths + 1
+ speculations = new_timestep.shape[1]
+ # Concatenates the tokens, their validity and the lengths of each sequence
+ # into one tensor so that copy operations are faster on Cloud TPU infrastructure.
+ token_data = jnp.concatenate(
+ [new_timestep, jnp.ones_like(new_timestep), new_lengths[:, None]],
+ axis=-1,
+ )
+ return DecodeState(
+ prefill_cache=prefill_cache,
+ generate_cache=generate_cache,
+ generate_cache_index=generate_cache_index,
+ generate_lengths=new_lengths,
+ ), engine_api.ResultTokens(
+ data=token_data.astype(jnp.int32),
+ # Tokens are shape [batch, speculations], so when we concatenate
+ # tokens, validity and length along their index 1 dimension then they
+ # occupy 0:speculations.
+ tokens_idx=(0, speculations),
+ # Validity occupies the same amount of space, but next in line.
+ valid_idx=(speculations, 2 * speculations),
+ # And lengths is rank 1.
+ length_idx=(2 * speculations, 2 * speculations + 1),
+ samples_per_slot=self.generate_cache_batch // self.prefill_cache_batch,
+ )
+
+ @functools.partial(jax.jit, static_argnums=(0,), donate_argnums=(2,))
+ def insert(
+ self,
+ prefix: Prefix,
+ decode_state: DecodeState,
+ slot: int,
+ ) -> DecodeState:
+ """Adds `prefix` into `decode_state` at `slot`."""
+ # [B, T], [T,] -> [B, T]
+ prefill_cache = jax.lax.dynamic_update_slice_in_dim(
+ decode_state.prefill_cache, prefix, slot, axis=0
+ )
+ generate_cache = jax.lax.dynamic_update_slice_in_dim(
+ decode_state.generate_cache, jnp.zeros((1, self.cache_length)),
+ slot, axis=0
+ )
+ samples_per_slot = self.generate_cache_batch // self.prefill_cache_batch
+ generate_lengths = jax.lax.dynamic_update_slice_in_dim(
+ decode_state.generate_lengths,
+ jnp.zeros((samples_per_slot), dtype=jnp.int32),
+ slot * samples_per_slot,
+ axis=0,
+ )
+ return decode_state.replace(
+ prefill_cache=prefill_cache,
+ generate_cache=generate_cache,
+ generate_lengths=generate_lengths,
+ )
+
+ def get_prefix_destination_sharding(self) -> Any:
+ return jax.sharding.NamedSharding(
+ mesh=self.mesh, spec=jax.sharding.PartitionSpec()
+ )
+
+ def get_tokenizer(self) -> tokenizer_pb2.TokenizerParameters:
+ """Return a protobuf of tokenizer info, callable from Py or C++."""
+ return tokenizer_pb2.TokenizerParameters(path='test', extra_ids=0)
+
+ def init_decode_state(self) -> DecodeState:
+ """Initialises any state which a generation step transforms."""
+ return DecodeState(
+ prefill_cache=jnp.zeros(
+ (self.prefill_cache_batch, self.cache_length), dtype=jnp.float32
+ ),
+ generate_cache=jnp.zeros(
+ (self.generate_cache_batch, self.cache_length), dtype=jnp.float32
+ ),
+ generate_cache_index=0,
+ generate_lengths=jnp.zeros(
+ (self.generate_cache_batch), dtype=jnp.int32
+ ),
+ )
+
+ @property
+ def max_concurrent_decodes(self) -> int:
+ """Free slots."""
+ return self.prefill_cache_batch
+
+ @property
+ def max_prefill_length(self) -> int:
+ """Maximum prefill length."""
+ return self.cache_length
+
+ @property
+ def samples_per_slot(self) -> int:
+ """Number of samples per slot."""
+ return self.generate_cache_batch // self.max_concurrent_decodes
+
+ @property
+ def mesh(self) -> jax.sharding.Mesh:
+ """Mesh which the engine is running on."""
+ return self._mesh
+
+ @property
+ def colocated_cpus(self) -> None:
+ """CPU devices colocated with the engine's accelerators."""
+ raise NotImplementedError
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/engine/mock_engine_test.py b/maxtext-setup/jetstream/build/lib/jetstream/engine/mock_engine_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e01168acae193d71ad5b445e0956a053c6cb3b0
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/engine/mock_engine_test.py
@@ -0,0 +1,114 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Tests for a mock version of the engine API.
+
+What should we expect?
+
+Prefill: Doubles the sequence by multiplying it with a weight [2].
+Insert: Writes this sequence into a cache row
+Generate step: Return sum(prefill_cache) + sum(generate_cache)/weight
+
+I.e. if we prefill [2, 65, 66] (i.e. , 'A', 'B') using an ACII vocab,
+we should get [4, 130, 132].
+
+If we then insert that and run three generation steps, we should see
+266+0 / 2 = 266
+266 + [266] /2 = 399
+266 + [266, 399] /2 = 598
+I.e. ['Ċ', 'Ə', 'ɖ'] when converted back with chr()
+"""
+
+import jax.numpy as jnp
+import numpy as np
+
+from jetstream.engine import mock_engine
+from jetstream.engine import token_utils
+from absl.testing import absltest
+
+
+class EngineTest(absltest.TestCase):
+
+ def _setup(self):
+ """Initialises a test engine."""
+ engine = mock_engine.TestEngine(batch_size=32, cache_length=256, weight=2.0)
+ params = engine.load_params()
+ return engine, params
+
+ def _prefill(self):
+ """Performs prefill and returns a kv cache."""
+ engine, params = self._setup()
+ # A 2 will be pre-pended as 'bos' token from the vocab.
+ text = 'AB'
+ metadata = engine.get_tokenizer()
+ vocab = token_utils.load_vocab(metadata.path, metadata.extra_ids)
+ tokens, true_length = token_utils.tokenize_and_pad(text, vocab, is_bos=True)
+ prefill_result = engine.prefill(
+ params=params, padded_tokens=tokens, true_length=3
+ )
+ return engine, params, prefill_result, true_length
+
+ def _generate(self, slot=1):
+ """Performs a single generation step."""
+ engine, params, prefill_result, _ = self._prefill()
+ decode_state = engine.init_decode_state()
+ decode_state = engine.insert(
+ prefix=prefill_result, decode_state=decode_state, slot=slot
+ )
+ decode_state, sampled_tokens = engine.generate(
+ params=params, decode_state=decode_state
+ )
+ return engine, params, decode_state, sampled_tokens
+
+ def test_load_params(self):
+ """Just loads params."""
+ _, params = self._setup()
+ assert params == jnp.array([2.0])
+
+ def test_prefill(self):
+ """Tests prefill with weight = 2."""
+ _, _, prefill_result, true_length = self._prefill()
+ np.testing.assert_array_equal(
+ prefill_result[:, :true_length], np.array([[4.0, 130.0, 132.0]])
+ )
+
+ def test_generate(self, slot=1):
+ """Tests multiple generation steps."""
+ engine, params, decode_state, sampled_tokens = self._generate(slot=slot)
+ metadata = engine.get_tokenizer()
+ tokenizer = token_utils.load_vocab(
+ metadata.path, metadata.extra_ids
+ ).tokenizer
+ # Char for 266
+ token_data = sampled_tokens.get_result_at_slot(slot)
+ tok = token_data.tokens
+ assert tokenizer.IdToPiece(int(tok.item())) == 'Ċ'
+ decode_state, sampled_tokens = engine.generate(
+ params=params, decode_state=decode_state
+ )
+ # Char for 399
+ token_data = sampled_tokens.get_result_at_slot(slot)
+ tok = token_data.tokens
+ assert tokenizer.IdToPiece(int(tok.item())) == 'Ə'
+ _, sampled_tokens = engine.generate(
+ params=params, decode_state=decode_state
+ )
+ # Char for 598
+ token_data = sampled_tokens.get_result_at_slot(slot)
+ tok = token_data.tokens
+ assert tokenizer.IdToPiece(int(tok.item())) == 'ɖ'
+
+
+if __name__ == '__main__':
+ absltest.main()
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/engine/mock_utils.py b/maxtext-setup/jetstream/build/lib/jetstream/engine/mock_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..63e2d87b9cb3954cc4a4e382fdb75c96b0f5efa7
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/engine/mock_utils.py
@@ -0,0 +1,77 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Utils for engine operation."""
+
+from typing import List, Sequence
+from flax import struct
+import numpy as np
+from seqio.vocabularies import Vocabulary
+
+
+@struct.dataclass
+class TestTokenizer:
+ """Tokenizer used for testing purposes."""
+
+ def IdToPiece(self, integer: int) -> str: # pylint: disable=invalid-name
+ """In the real version, unlike encode_tf/decode_tf, doesn't strip trailing whitespace."""
+ return chr(integer)
+
+
+@struct.dataclass
+class TestVocab(Vocabulary):
+ """Mock vocabulary used for tests.
+
+ These methods are duplicative on the test vocab, but required to fit
+ the seqio.Vocabulary interface.
+ """
+
+ pad_id = 0
+ eos_id = 1
+ bos_id = 2
+ unk_id = 3
+ _base_vocab_size = 2**16
+ tokenizer: TestTokenizer = TestTokenizer()
+
+ def _encode(self, s: str) -> Sequence[int]:
+ """Converts a string into a integer sequenc."""
+ # 'We use array methods, not python iterables so we don't
+ # implement this method in the mock vocab.
+ raise NotImplementedError
+
+ def _decode(self, tokens: np.ndarray):
+ """Converts a numpy array into a string."""
+ # 'We use array methods, not python iterables so we don't
+ # implement this method in the mock vocab.
+ raise NotImplementedError
+
+ def _encode_tf(self, text: str) -> np.ndarray:
+ """Converts a string into a numpy array."""
+ # We mock using numpy to avoid propagating tf dependencies.
+ chars = np.array([ord(c) for c in text]).astype(np.int32)
+ return chars
+
+ def _decode_tf(self, tokens: np.ndarray) -> List[str]:
+ """Converts a numpy array into a string."""
+ # We mock using numpy to avoid propagating tf dependencies.
+ results = np.split(tokens, tokens.shape[0])
+ return [''.join([chr(r) for r in list(line[0])]) for line in results]
+
+ def encode_tf(self, text: str) -> np.ndarray:
+ """Converts a string into a numpy array."""
+ return self._encode_tf(text)
+
+ def decode_tf(self, tokens: np.ndarray) -> List[str]:
+ """Converts a numpy array into a string."""
+ return self._decode_tf(tokens)
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/engine/token_utils.py b/maxtext-setup/jetstream/build/lib/jetstream/engine/token_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f6aa66a5a9ddd63776ace3334753cbab0a184cd
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/engine/token_utils.py
@@ -0,0 +1,207 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Token manipulation utilities."""
+
+from bisect import bisect_left
+import logging
+from typing import List, Optional, Tuple
+
+import jax
+import jax.numpy as jnp
+import numpy as np
+from seqio.vocabularies import SentencePieceVocabulary
+from seqio.vocabularies import Vocabulary
+
+from jetstream.engine import engine_api
+from jetstream.engine import mock_utils
+
+
+def take_nearest_length(lengths: list[int], length: int) -> int:
+ """Gets the nearest length to the right in a set of lengths."""
+ pos = bisect_left(lengths, length)
+ if pos == len(lengths):
+ return lengths[-1]
+ return lengths[pos]
+
+
+def tokenize_and_pad(
+ s: str,
+ vocab: Vocabulary,
+ eos_id: int,
+ pad_id: int,
+ bos_id: int,
+ is_bos: bool = True,
+ prefill_lengths: Optional[List[int]] = None,
+ max_prefill_length: Optional[int] = None,
+) -> Tuple[jax.Array, int]:
+ """Tokenize and pads a string.
+
+ Args:
+ s: String to tokenize.
+ vocab: Vocabulary to tokenize with.
+ is_bos: Whether or not this is the beginning of a sequence. Default to yes
+ as prefill is typically used when beginning sequences.
+ prefill_lengths: Buckets to pad the sequence to for static compilation.
+ max_prefill_length: Maximum bucket to use.
+
+ Returns:
+ tokens: Tokenized into integers.
+ true_length: Actual length of the non-padded sequence.
+ """
+ if prefill_lengths is None:
+ prefill_lengths = [
+ 16,
+ 32,
+ 64,
+ 128,
+ 256,
+ 512,
+ 1024,
+ 2048,
+ 4096,
+ 8192,
+ 16384,
+ 32768,
+ ]
+ if max_prefill_length is not None:
+ prefill_lengths = prefill_lengths[
+ : prefill_lengths.index(max_prefill_length)
+ ] + [
+ max_prefill_length,
+ ]
+ tokens = np.array(vocab.encode_tf(s)) # [Length]
+ # Add a beginning of sequence token if this is the beginning.
+ if is_bos:
+ tokens = np.concatenate(
+ [
+ np.array([
+ bos_id,
+ ]),
+ tokens,
+ ],
+ axis=-1,
+ )
+ true_length = tokens.shape[-1]
+ padded_length = take_nearest_length(prefill_lengths, true_length)
+ padding = padded_length - true_length
+ assert pad_id == 0, 'Further logic required if pad_id not 0.'
+ if padding < 0:
+ logging.warning('Provided sequence longer than available.')
+ # Take the last N tokens if we have too many.
+ padded_tokens = tokens[-padded_length:]
+ else:
+ padded_tokens = np.pad(tokens, (0, padding))
+ return jnp.array(padded_tokens), true_length
+
+
+def process_result_tokens(
+ slot: int,
+ slot_max_length: int,
+ result_tokens: engine_api.ResultTokens,
+ vocab: Vocabulary,
+ eos_id: int,
+ pad_id: int,
+ bos_id: int,
+ complete: np.ndarray,
+ debug: bool = False,
+) -> Tuple[List[str], np.ndarray]:
+ """Processes a result tokens into a list of strings, handling multiple samples.
+
+ Args:
+ slot: The slot at which to draw tokens from.
+ slot_max_length: Max length for a sample in the slot.
+ result_tokens: The tokens to access by slot.
+ vocab: For the detokenizer.
+ complete: Array representing the completion status of each sample in the
+ slot.
+ debug: Whether to log step by step detokenisation.
+
+ Returns:
+ sample_return: List of strings, one per sample.
+ complete: Updated complete.
+ """
+ # tokens: [samples, speculations]
+ slot_data = result_tokens.get_result_at_slot(slot)
+ slot_tokens = slot_data.tokens
+ slot_valid = slot_data.valid
+ slot_lengths = slot_data.lengths
+ samples, speculations = slot_tokens.shape
+ stop_tokens = [eos_id, pad_id]
+ # Stop anything which has reached it's max length.
+ complete = complete | (slot_lengths > slot_max_length)
+ if debug:
+ logging.info(
+ 'Complete %s, slot_tokens: %s, slot_lengths: %s',
+ complete.__str__(),
+ slot_tokens.__str__(),
+ slot_lengths.__str__(),
+ )
+ sample_return = []
+ for idx in range(samples):
+ string_so_far = ''
+ if not complete[idx].item():
+ for spec_idx in range(speculations):
+ tok_id = slot_tokens[idx, spec_idx].item()
+ valid = slot_valid[idx, spec_idx].item()
+ if debug:
+ logging.info(
+ 'Sample idx: %d Speculation idx: %d Token: %d',
+ idx,
+ spec_idx,
+ tok_id,
+ )
+ if tok_id in stop_tokens or not valid:
+ complete[idx] = True
+ break
+ else:
+ try:
+ token = vocab.tokenizer.IdToPiece(tok_id) # pytype: disable=attribute-error
+ # ▁ or _ encodes a blank space.
+ token = token.replace('▁', ' ').replace('_', ' ')
+ except ValueError:
+ # This error only occurs when using tests where the vocab range is
+ # computed via addition and int->char is computed using chr(). Real
+ # models have vocab logits which are at max the size of the vocab.
+ logging.warning('%d exceeded vocab range', tok_id)
+ token = ''
+ string_so_far += token
+ sample_return.append(string_so_far)
+ if debug:
+ logging.info('Sampled return %s', sample_return.__str__())
+ return sample_return, complete
+
+
+def load_vocab(path: str, extra_ids: int = 0) -> Vocabulary:
+ """Eagerly loads a vocabulary.
+
+ Args:
+ path: Vocabulary file path.
+ extra_ids: Number of extra IDs.
+
+ Returns:
+ A seqio Vocabulary.
+ """
+ if path == 'test':
+ return mock_utils.TestVocab()
+ else:
+ vocab = SentencePieceVocabulary(
+ path,
+ extra_ids=extra_ids,
+ )
+ # SentencePieceVocabulary uses lazy loading. Request access to a property,
+ # forcing the lazy loading to happen now.
+ sp_model = vocab.sp_model
+ del sp_model
+ return vocab
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/engine/tokenizer_pb2.py b/maxtext-setup/jetstream/build/lib/jetstream/engine/tokenizer_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..b247a6b931b431f28771199560db7e04e2540c07
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/engine/tokenizer_pb2.py
@@ -0,0 +1,41 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: jetstream/engine/tokenizer.proto
+# Protobuf Python Version: 4.25.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+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')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'jetstream.engine.tokenizer_pb2', _globals)
+if _descriptor._USE_C_DESCRIPTORS == False:
+ _globals['DESCRIPTOR']._options = None
+ _globals['DESCRIPTOR']._serialized_options = b'P\001'
+ _globals['_TOKENIZERPARAMETERS']._serialized_start=44
+ _globals['_TOKENIZERPARAMETERS']._serialized_end=98
+# @@protoc_insertion_point(module_scope)
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/engine/tokenizer_pb2_grpc.py b/maxtext-setup/jetstream/build/lib/jetstream/engine/tokenizer_pb2_grpc.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae028862035d22ad67e5b57f49c97b5d79cd6ed5
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/engine/tokenizer_pb2_grpc.py
@@ -0,0 +1,18 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
+"""Client and server classes corresponding to protobuf-defined services."""
+import grpc
+
diff --git a/maxtext-setup/jetstream/build/lib/jetstream/engine/utils_test.py b/maxtext-setup/jetstream/build/lib/jetstream/engine/utils_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..297161dfba759eb8136de891f66664c15ae71b19
--- /dev/null
+++ b/maxtext-setup/jetstream/build/lib/jetstream/engine/utils_test.py
@@ -0,0 +1,83 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Tests functionality of the token processing utils using mock engine vocab."""
+
+import numpy as np
+from jetstream.engine import engine_api
+from jetstream.engine import mock_utils
+from jetstream.engine import token_utils
+from absl.testing import absltest
+
+
+class UtilsTest(absltest.TestCase):
+
+ def test_speculations_with_multi_sample_slots(self, samples_per_slot=2):
+ # [4, 1]
+ mock_tokens = np.array([
+ [0, ord('A')],
+ [ord('A'), ord('D')],
+ [ord('T'), ord('3')],
+ [ord('A'), 1],
+ ]).astype(np.int32)
+ mock_valid_tokens = np.ones_like(mock_tokens, dtype=np.int32)
+ mock_lengths = np.ones(mock_tokens.shape[0], dtype=np.int32)*2
+ # completion is 'per slot' because we track it for a given request.
+ mock_complete = np.zeros(
+ (mock_tokens.shape[0] // samples_per_slot), dtype=np.int32
+ )
+ data = np.concatenate(
+ [
+ mock_tokens,
+ mock_valid_tokens,
+ mock_lengths[:, None],
+ ],
+ axis=-1,
+ )
+ speculations = mock_tokens.shape[1]
+ result_tokens = engine_api.ResultTokens(
+ data=data.astype(np.int32),
+ tokens_idx=(0, speculations),
+ valid_idx=(speculations, 2 * speculations),
+ length_idx=(2 * speculations, 2 * speculations + 1),
+ samples_per_slot=2,
+ )
+ per_channel, complete = token_utils.process_result_tokens(
+ slot=0,
+ slot_max_length=4,
+ result_tokens=result_tokens,
+ vocab=mock_utils.TestVocab(),
+ complete=mock_complete,
+ )
+ np.testing.assert_equal(complete, np.array([1, 0]))
+
+ assert not per_channel[0] # i.e. == '', because of the pad.
+ assert per_channel[1] == 'AD'
+ mock_complete = np.zeros(
+ (mock_tokens.shape[0] // samples_per_slot), dtype=np.int32
+ )
+ per_channel, complete = token_utils.process_result_tokens(
+ slot=1,
+ slot_max_length=4,
+ result_tokens=result_tokens,
+ vocab=mock_utils.TestVocab(),
+ complete=mock_complete,
+ )
+ assert per_channel[0] == 'T3'
+ assert per_channel[1] == 'A' # second token is padded.
+ np.testing.assert_equal(complete, np.array([0, 1]))
+
+
+if __name__ == '__main__':
+ absltest.main()
diff --git a/maxtext-setup/jetstream/google_jetstream.egg-info/PKG-INFO b/maxtext-setup/jetstream/google_jetstream.egg-info/PKG-INFO
new file mode 100644
index 0000000000000000000000000000000000000000..56129177ab255daf554dda44f8b0809ce88b9cd8
--- /dev/null
+++ b/maxtext-setup/jetstream/google_jetstream.egg-info/PKG-INFO
@@ -0,0 +1,52 @@
+Metadata-Version: 2.1
+Name: google-jetstream
+Version: 0.1.1
+Summary: A throughput and memory optimized engine for LLM inference on TPU and GPU.
+Home-page: https://github.com/google/JetStream
+Author: Google LLC
+Classifier: Programming Language :: Python :: 3.10
+Classifier: License :: OSI Approved :: Apache Software License
+Classifier: Operating System :: OS Independent
+Requires-Python: >=3.10
+Description-Content-Type: text/markdown
+License-File: LICENSE
+License-File: AUTHORS
+
+# JetStream - A throughput and memory optimized engine for LLM inference on TPU and GPU
+
+## About
+
+JetStream is a fast library for LLM inference and serving on TPU and GPU.
+
+## Getting Started
+
+### Run local server & Testing
+
+Use the following commands to run a server locally:
+```
+# Start a server
+python -m jetstream.core.implementations.mock.server
+
+# Test local mock server
+python -m jetstream.core.tools.requester
+
+# Load test local mock server
+python -m jetstream.core.tools.load_tester
+
+```
+
+### Test core modules
+```
+# Test JetStream core orchestrator
+python -m jetstream.core.orchestrator_test
+
+# Test JetStream core server library
+python -m jetstream.core.server_test
+
+# Test mock JetStream engine implementation
+python -m jetstream.engine.mock_engine_test
+
+# Test mock JetStream token utils
+python -m jetstream.engine.utils_test
+
+```
diff --git a/maxtext-setup/jetstream/google_jetstream.egg-info/SOURCES.txt b/maxtext-setup/jetstream/google_jetstream.egg-info/SOURCES.txt
new file mode 100644
index 0000000000000000000000000000000000000000..77e4973e065e005892d0ef487d250987b54495ee
--- /dev/null
+++ b/maxtext-setup/jetstream/google_jetstream.egg-info/SOURCES.txt
@@ -0,0 +1,32 @@
+AUTHORS
+LICENSE
+README.md
+setup.py
+google_jetstream.egg-info/PKG-INFO
+google_jetstream.egg-info/SOURCES.txt
+google_jetstream.egg-info/dependency_links.txt
+google_jetstream.egg-info/requires.txt
+google_jetstream.egg-info/top_level.txt
+jetstream/__init__.py
+jetstream/core/__init__.py
+jetstream/core/config_lib.py
+jetstream/core/orchestrator.py
+jetstream/core/orchestrator_test.py
+jetstream/core/server_lib.py
+jetstream/core/server_test.py
+jetstream/core/implementations/__init__.py
+jetstream/core/implementations/mock/__init__.py
+jetstream/core/implementations/mock/config.py
+jetstream/core/implementations/mock/server.py
+jetstream/core/proto/__init__.py
+jetstream/core/proto/jetstream_pb2.py
+jetstream/core/proto/jetstream_pb2_grpc.py
+jetstream/engine/__init__.py
+jetstream/engine/engine_api.py
+jetstream/engine/mock_engine.py
+jetstream/engine/mock_engine_test.py
+jetstream/engine/mock_utils.py
+jetstream/engine/token_utils.py
+jetstream/engine/tokenizer_pb2.py
+jetstream/engine/tokenizer_pb2_grpc.py
+jetstream/engine/utils_test.py
\ No newline at end of file
diff --git a/maxtext-setup/jetstream/google_jetstream.egg-info/dependency_links.txt b/maxtext-setup/jetstream/google_jetstream.egg-info/dependency_links.txt
new file mode 100644
index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc
--- /dev/null
+++ b/maxtext-setup/jetstream/google_jetstream.egg-info/dependency_links.txt
@@ -0,0 +1 @@
+
diff --git a/maxtext-setup/jetstream/google_jetstream.egg-info/requires.txt b/maxtext-setup/jetstream/google_jetstream.egg-info/requires.txt
new file mode 100644
index 0000000000000000000000000000000000000000..50e93732f7734e889febe683e331f72d828f2d1c
--- /dev/null
+++ b/maxtext-setup/jetstream/google_jetstream.egg-info/requires.txt
@@ -0,0 +1,8 @@
+absl-py
+flax
+grpcio
+jax
+jaxlib
+portpicker
+numpy
+seqio
diff --git a/maxtext-setup/jetstream/google_jetstream.egg-info/top_level.txt b/maxtext-setup/jetstream/google_jetstream.egg-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..77b18d8b19799f26b97b1d0a50bda8271b56df26
--- /dev/null
+++ b/maxtext-setup/jetstream/google_jetstream.egg-info/top_level.txt
@@ -0,0 +1 @@
+jetstream
diff --git a/maxtext-setup/jetstream/jetstream/__init__.py b/maxtext-setup/jetstream/jetstream/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c38dc3b14ab36f34985ad3f1b20071f4a6a16e82
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
diff --git a/maxtext-setup/jetstream/jetstream/core/README.md b/maxtext-setup/jetstream/jetstream/core/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..50532c700d858cdd4dec79816a88ac163ec90f2b
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/README.md
@@ -0,0 +1,3 @@
+# JetStream core Subpackage - Server and Library that support continuous batching serving.
+
+Interleaved mode: Provide continuous batching to optimize inference. Uses JAX directy on single-host TPU.
\ No newline at end of file
diff --git a/maxtext-setup/jetstream/jetstream/core/__init__.py b/maxtext-setup/jetstream/jetstream/core/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c38dc3b14ab36f34985ad3f1b20071f4a6a16e82
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
diff --git a/maxtext-setup/jetstream/jetstream/core/config_lib.py b/maxtext-setup/jetstream/jetstream/core/config_lib.py
new file mode 100644
index 0000000000000000000000000000000000000000..700694da55b2f1ead239e5ce810900fd28333ed0
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/config_lib.py
@@ -0,0 +1,155 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Configs of engines for the orchestrator to load."""
+
+import dataclasses
+import functools
+import math
+from typing import Any, Callable, List, Tuple, Type
+
+from jetstream.engine import engine_api
+from jetstream.engine import mock_engine
+
+
+Devices = Any
+
+CreateEngineFn = Callable[[Devices], engine_api.Engine]
+
+
+@dataclasses.dataclass
+class ServerConfig:
+ """Configs for slices to put engines on."""
+
+ prefill_slices: Tuple[str, ...] = ()
+ generate_slices: Tuple[str, ...] = ()
+ interleaved_slices: Tuple[str, ...] = ()
+ prefill_engine_create_fns: Tuple[CreateEngineFn, ...] = ()
+ generate_engine_create_fns: Tuple[CreateEngineFn, ...] = ()
+ interleaved_engine_create_fns: Tuple[CreateEngineFn, ...] = ()
+
+ def get_slices_to_launch(self: 'ServerConfig') -> str:
+ """Used when launching this config via xm config."""
+ return ','.join(
+ self.prefill_slices + self.generate_slices + self.interleaved_slices
+ )
+
+
+@dataclasses.dataclass
+class InstantiatedEngines:
+ prefill_engines: List[engine_api.Engine]
+ generate_engines: List[engine_api.Engine]
+ interleaved_engines: List[engine_api.Engine]
+
+
+# ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼#
+
+
+def get_test_engine(devices: Devices, weight: int) -> engine_api.Engine:
+ del devices
+ return mock_engine.TestEngine(
+ batch_size=8,
+ cache_length=32,
+ weight=weight,
+ )
+
+
+@dataclasses.dataclass
+class CPUTestServer(ServerConfig):
+ prefill_slices = ('cpu=1',)
+ generate_slices = ('cpu=1',)
+ prefill_engine_create_fns = (functools.partial(get_test_engine, weight=2),)
+ generate_engine_create_fns = (functools.partial(get_test_engine, weight=4),)
+
+
+@dataclasses.dataclass
+class InterleavedCPUTestServer(ServerConfig):
+ interleaved_slices = ('cpu=1',)
+ interleaved_engine_create_fns = (
+ functools.partial(get_test_engine, weight=2),
+ )
+
+
+# ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼#
+
+
+def slice_to_num_chips(s: str) -> int:
+ """Converts a TPU spec like v5e=4x2 to the number of chips, 8."""
+ # Account for the case where it is written 'v5e:4x2'.
+ delim = '=' if '=' in s else ':'
+ i = math.prod([int(c) for c in s.split(delim)[1].split('x')])
+ return i
+
+
+def _split_devices_by_slices(
+ devices: list[Devices], slices: list[int]
+) -> List[List[Devices]]:
+ """Converts an ordered list of devices into slices."""
+ assert sum(slices) == len(devices), f'{sum(slices)} != {len(devices)}'
+ cumsum = 0
+ slice_split_devices = []
+ for sl in slices:
+ slice_split_devices.append(devices[cumsum : cumsum + sl])
+ cumsum += sl
+ return slice_split_devices
+
+
+def get_engines(
+ server_config: Type[ServerConfig], devices: List[Devices]
+) -> InstantiatedEngines:
+ """Processes config to get the appropriate engines.
+
+ Args:
+ server_config: ServerConfig.
+ devices: Device objects.
+
+ Returns:
+ Instantiated engines!
+
+ Devices are popped in order!
+ """
+ # Now, we need to split devices by slice due to TPU backend config.
+ slices: list[int] = [
+ slice_to_num_chips(s)
+ for s in list(server_config.prefill_slices)
+ + list(server_config.generate_slices)
+ + list(server_config.interleaved_slices)
+ ]
+ if sum(slices) != len(devices):
+ raise ValueError(
+ f'The number of available devices ({len(devices)}) do not match the '
+ f'expected number of devices on all the slices ({sum(slices)}) '
+ 'specified in the server_config:\n'
+ f'{server_config.prefill_slices=}\n'
+ f'{server_config.generate_slices=}\n'
+ f'{server_config.interleaved_slices=}\n'
+ )
+ # e.g. [[tpu_0], [tpu_1]] corresponding to prefill: v5e=1x1
+ # generate = v5e=1x1; or [[tpu_0, tpu_1, tpu_2, tpu_3]] corresponding to
+ # interleaved: v5e=2x2
+ split_devices = _split_devices_by_slices(devices, slices)
+ prefill_engines = [
+ e(split_devices.pop(0)) for e in server_config.prefill_engine_create_fns
+ ]
+ generate_engines = [
+ e(split_devices.pop(0)) for e in server_config.generate_engine_create_fns
+ ]
+ # These share chips and weights for prefill and generation.
+ interleaved_engines = [
+ e(split_devices.pop(0))
+ for e in server_config.interleaved_engine_create_fns
+ ]
+ return InstantiatedEngines(
+ prefill_engines, generate_engines, interleaved_engines
+ )
\ No newline at end of file
diff --git a/maxtext-setup/jetstream/jetstream/core/implementations/__init__.py b/maxtext-setup/jetstream/jetstream/core/implementations/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c38dc3b14ab36f34985ad3f1b20071f4a6a16e82
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/implementations/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
diff --git a/maxtext-setup/jetstream/jetstream/core/implementations/mock/README.md b/maxtext-setup/jetstream/jetstream/core/implementations/mock/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..64c53fdcf2211c700e4720035d27fa2c9c6116b4
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/implementations/mock/README.md
@@ -0,0 +1,3 @@
+# Mock server
+
+Implements Mock JetStream core with mock model config.
\ No newline at end of file
diff --git a/maxtext-setup/jetstream/jetstream/core/implementations/mock/__init__.py b/maxtext-setup/jetstream/jetstream/core/implementations/mock/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c38dc3b14ab36f34985ad3f1b20071f4a6a16e82
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/implementations/mock/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
diff --git a/maxtext-setup/jetstream/jetstream/core/implementations/mock/config.py b/maxtext-setup/jetstream/jetstream/core/implementations/mock/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0d5aeacb7f34c0c07e741720a08baefb55e30e1
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/implementations/mock/config.py
@@ -0,0 +1,30 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Config for mock."""
+
+from typing import Type
+
+
+from jetstream.core import config_lib
+
+def get_server_config(config_str: str) -> Type[config_lib.ServerConfig]:
+ match config_str:
+ case 'InterleavedCPUTestServer':
+ server_config = config_lib.InterleavedCPUTestServer
+ case 'CPUTestServer':
+ server_config = config_lib.CPUTestServer
+ case _:
+ raise NotImplementedError
+ return server_config
diff --git a/maxtext-setup/jetstream/jetstream/core/implementations/mock/server.py b/maxtext-setup/jetstream/jetstream/core/implementations/mock/server.py
new file mode 100644
index 0000000000000000000000000000000000000000..6355469c720f47baddd0c4adc02b8782ab16963f
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/implementations/mock/server.py
@@ -0,0 +1,49 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a mock server."""
+
+from typing import Sequence
+
+from absl import app
+from absl import flags
+
+from jetstream.core.implementations.mock import config as mock_config
+from jetstream.core import server_lib
+
+
+_PORT = flags.DEFINE_integer('port', 9000, 'port to listen on')
+_CONFIG = flags.DEFINE_string(
+ 'config',
+ 'InterleavedCPUTestServer',
+ 'available servers',
+)
+
+def main(argv: Sequence[str]):
+ del argv
+ # No devices for local cpu test. A None for prefill and a None for generate.
+ devices = server_lib.get_devices()
+ server_config = mock_config.get_server_config(_CONFIG.value)
+ # We separate credential from run so that we can unit test it with local credentials.
+ # TODO: Add grpc credentials for OSS.
+ jetstream_server = server_lib.run(
+ port=_PORT.value,
+ config=server_config,
+ devices=devices,
+ )
+ jetstream_server.wait_for_termination()
+
+
+if __name__ == '__main__':
+ app.run(main)
diff --git a/maxtext-setup/jetstream/jetstream/core/orchestrator.py b/maxtext-setup/jetstream/jetstream/core/orchestrator.py
new file mode 100644
index 0000000000000000000000000000000000000000..bebbb64fcbcabb0c3cd0fe0de011bbf876bf2025
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/orchestrator.py
@@ -0,0 +1,651 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Orchestrates the engines for the inference workflow with performance optimization.
+
+1. A client sends a DecodeRequest via gRPC to the server, an 'LLMOrchestrator'.
+2. This gets wrapped as an 'ActiveRequest' inside the orchestrator, with a
+ 'return_channel' queue as a place that output tokens can be placed.
+ - The ActiveRequest is placed on the 'prefill_queue'.
+ - A while loop runs continuously, yielding any tokens placed on the return
+ channel until an end condition is met (EOS token or max tokens).
+3. There is a prefill_thread per prefill_engine, each of which runs on a
+ distinct prefill_slice.
+4. There is a generate_thread per generate_engine, each of which runs on a
+ distinct generate_slice.
+5. Within a prefill thread:
+ - It attempts to pop ActiveRequests off the prefill_queue.
+ - It tokenizes the request.
+ - When successful, it performs a prefill operation, transfers the kv cache
+ to the generation slice and pops this information (still wrapped in the
+ same ActiveRequest) onto the generation queue.
+6. Within a generation thread:
+ - There is a queue of integers representing 'available slots'.
+ - It checks if there is something on both the slots_queue and generation_
+ queue.
+ - If so, the kv_cache associated with that request into the decoding state
+ of the generation loop at the relevant slot.
+ - Regardless, it performs a step.
+ - It takes the sampled tokens, and places them on a 'detokenizing_queue'.
+7. Within the detokenizing thread:
+ - Tokens are detokenized for every 'slot' in a given set of sampled tokens.
+ - When an end condition is met, the 'slot' integer is returned to the
+ respective generation queue.
+ - This does mean that a single generation step may run after detokenizing
+ indicates that row is no longer valid (if the detokenizing is running behind
+ generation steps), this is fine as it avoids detokenizing being blocking of
+ the generate thread.
+
+If you haven't worked with concurrency in python before - queues are thread-safe
+by default, so we can happily use them to transfer pointers to data between
+different processes. The structure of this server is simple as a result - a
+thread for each thing we might want to do (prefill, transfer, generate,
+detokenize), and corresponding queues that an active request is passed between.
+The same goes for the 'return_channel' of the request itself, where we can just
+pop tokens once they are done and try to pop them back to transmit them over
+grpc.
+It is literally queues all the way down! :)
+The primary concern is GIL contention between threads, which is why we block
+on queues that don't have an ongoing activity (i.e. everything but the
+generation queue) because we don't control to go back to those queues until
+necessary. Blocking means that the GIL doesn't switch back to that thread,
+wheras continual queue get operations 'chop' control and mean that we do not
+achieve good throughput. This is okay on the prefill/transfer/detokenisation
+threads because we don't need to do anything other than react to the presence
+of items on these queues, wheras the generation thread needs to also run a
+step - so it cannot block until it has new things to insert.
+
+## Testing
+This server is intended to be easy to locally test.
+
+Either use :orchestrator test, which tests the multi-threading components,
+:server_test, which extends this to test grpc_components, or run it locally
+to debug hangs due to bugs in threads (it is easier to debug with live logs).
+"""
+
+import dataclasses
+import functools
+import itertools
+import logging
+import os
+import queue
+import signal
+import sys
+import threading
+import time
+import traceback
+import json
+from typing import Any, Iterable, Optional, Union
+
+import grpc
+import jax
+from jetstream.core.proto import jetstream_pb2
+from jetstream.core.proto import jetstream_pb2_grpc
+from jetstream.engine import engine_api
+from jetstream.engine import token_utils
+import numpy as np
+
+
+root = logging.getLogger()
+root.setLevel(logging.DEBUG)
+
+handler = logging.StreamHandler(sys.stdout)
+handler.setLevel(logging.DEBUG)
+formatter = logging.Formatter(
+ '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+)
+handler.setFormatter(formatter)
+root.addHandler(handler)
+
+
+def delete_pytree(p):
+ def delete_leaf(leaf):
+ if isinstance(leaf, jax.Array):
+ leaf.delete()
+ del leaf
+
+ jax.tree_map(delete_leaf, p)
+
+
+@dataclasses.dataclass
+class ActiveRequest:
+ """Current state of the driver."""
+
+ #################### Information relevant for generation #####################
+ max_tokens: int
+ vocab: str
+ # [num_samples,] which corresponds to whether each sample is complete for the
+ # requests.
+ complete: Optional[np.ndarray] = None
+ prefill_result: Any = None
+ #################### Information relevant for prefill ########################
+ history_path: Optional[str] = None
+ prefill_text: Optional[str] = None
+ ################## Information relevant for detokenisation ###################
+ # Which generate step this was added at.
+ generate_timestep_added: Optional[int] = None
+ # We keep prefill and decode information together in the same object so that
+ # there is less indirection about where this return channel is.
+ # The return channel returns a list of strings, one per sample for that query.
+ return_channel: queue.Queue[list[str]] = dataclasses.field(
+ default_factory=queue.Queue
+ )
+
+ def next(self: 'ActiveRequest'):
+ """Blocks until the next token is available, call from RPC threads."""
+ return self.return_channel.get()
+
+ def enqueue_tokens(self, generated_tokens: list[str]):
+ """Records information about the step.
+
+ Args:
+ generated_tokens: One token to put into the return channel
+
+ This should be called only from within the Drivers background thread.
+ """
+ self.return_channel.put(generated_tokens)
+
+
+class JetThread(threading.Thread):
+ """Thread that kills the program if it fails.
+
+ If a driver thread goes down, we can't operate.
+ """
+
+ def run(self):
+ try:
+ super().run()
+ except Exception as e: # pylint: disable=broad-exception-caught
+ print(f'Thread {self.name} encountered an error: {e}')
+ traceback.print_exc()
+ os.kill(os.getpid(), signal.SIGKILL)
+
+
+def _abort_or_raise(
+ context: grpc.ServicerContext | None, code: grpc.StatusCode, details: str
+):
+ """Safely aborts a gRPC context if available, or raises an Exception."""
+ if context is None:
+ raise RuntimeError(details)
+
+ context.abort(code, details)
+
+
+class Driver:
+ """Drives the engines."""
+
+ _prefill_engines: list[engine_api.Engine]
+ _generate_engines: list[engine_api.Engine]
+ # Allows us to pre-load the params, primarily so that we can iterate quickly
+ # on the driver in colab without reloading weights.
+ _prefill_params: Optional[dict[int, Any]] = {}
+ _generate_params: Optional[dict[int, Any]] = {}
+ # Stage 1
+ _prefill_backlog: queue.Queue[ActiveRequest | None]
+ # Stage 2
+ # We keep this as a dict to avoid a possibly expensive object comparison
+ # when logging the index of the generate engine we send a prefill result
+ # to, it allows us to natively have the index from the min operation, rather
+ # than have to call .index()
+ _generate_backlogs: dict[int, queue.Queue[ActiveRequest | None]] = {}
+ # Stage 3
+ # This can be a list because we can pass it as an arg to generate and
+ # detokenize threads. It is a list of tokens to be detokenized.
+ _detokenize_backlogs: list[queue.Queue[engine_api.ResultTokens]] = []
+ _generate_slots: list[queue.Queue[int]] = []
+ _active_requests: list[queue.Queue[tuple[int, ActiveRequest | None]]] = []
+
+ def __init__(
+ self,
+ prefill_engines=None,
+ generate_engines=None,
+ prefill_params=None,
+ generate_params=None,
+ ):
+ logging.info(
+ 'Initialising driver with %d prefill engines and %d generate engines.',
+ len(prefill_engines),
+ len(generate_engines),
+ )
+ self._prefill_engines = prefill_engines
+ self._generate_engines = generate_engines
+ self._prefill_params = prefill_params if prefill_params else {}
+ self._generate_params = generate_params if generate_params else {}
+ # Stages 1-4 represent the life cycle of a request.
+ # Stage 1
+ # At first, a request is placed here in order to get prefilled.
+ self._prefill_backlog = queue.Queue()
+ # Stage 2
+ # Each generate engine accesses its own generate backlog.
+ self._generate_backlogs = {
+ idx: queue.Queue() for idx, _ in enumerate(generate_engines)
+ }
+ # Stage 3
+ # After generation, ActiveRequests are placed on the detokenization backlog
+ # for tokens to be sent into each ActiveRequest's return channel.
+ # We have one of these per generate engine to simplify the logic keeping
+ # track of which generation engine to replace slots on.
+ # This is a queue of either - tuple[int, ActiveRequest] which represents our
+ # active requests, or tuple[int, sample_tokens]. We combine these into one
+ # queue because it allows us to be somewhat clever with how we do
+ # detokenization.
+ # If the detokenization receives an (int, ActiveRequest) this signifies
+ # that slot int should from now be placing tokens in the return channel of
+ # the ActiveRequest.
+ # If it receives (int, sample_tokens) then it actually
+ # does a detokenisation for any slots which have previously been set active
+ # via the previous kind of object, and the int is used to log which step
+ # the tokens were created at. By having them in one queue we prevent
+ # the possibility of race conditions where a slot is made live before the
+ # tokens are ready and it receives tokens from a different sequence,
+ # or tokens detokenized before the relevant slot is live.
+ self._detokenize_backlogs = [queue.Queue() for _ in generate_engines]
+ # Finally we have a queue that doesn't represent a stage, but tracks the
+ # internal status of a request within the generation loop.
+ # a) A queue of integers representing available 'slots' in the decode
+ # operation. I.e. potentially available rows in the batch and/or
+ # microbatch. When we want to insert a prefill result, we pop an integer
+ # to insert at. When this is empty, it means all slots are full.
+
+ # Construct a)
+ self._generate_slots = [queue.Queue() for _ in generate_engines]
+ _ = [
+ [
+ self._generate_slots[idx].put(i)
+ for i in range(engine.max_concurrent_decodes)
+ ]
+ for idx, engine in enumerate(generate_engines)
+ ]
+
+ # Kick off all our threads
+ self._prefill_threads = [
+ JetThread(
+ target=functools.partial(self._prefill_thread, idx, engine),
+ name=f'prefill-{idx}',
+ )
+ for idx, engine in enumerate(self._prefill_engines)
+ ]
+ self._generate_threads = [
+ JetThread(
+ target=functools.partial(
+ self._generate_thread,
+ idx,
+ engine,
+ self._generate_slots[idx],
+ self._detokenize_backlogs[idx],
+ ),
+ name=f'generate-{idx}',
+ )
+ for idx, engine in enumerate(self._generate_engines)
+ ]
+ # Construct b)
+ self.detokenize_threads = [
+ JetThread(
+ target=functools.partial(
+ self._detokenize_thread,
+ idx,
+ engine,
+ self._generate_slots[idx],
+ self._detokenize_backlogs[idx],
+ ),
+ name=f'detokenize-{idx}',
+ )
+ for idx, engine in enumerate(self._generate_engines)
+ ]
+ self._all_threads = list(
+ itertools.chain(
+ self._prefill_threads,
+ self._generate_threads,
+ self.detokenize_threads,
+ )
+ )
+ self.live = True
+ # Kick off all threads
+ for t in self._all_threads:
+ t.start()
+
+ def stop(self):
+ """Stops the driver and all background threads."""
+ # Signal to all threads that they should stop.
+ self.live = False
+
+ all_backlogs = list(
+ itertools.chain(
+ [self._prefill_backlog],
+ self._generate_backlogs.values(),
+ self._detokenize_backlogs,
+ )
+ )
+
+ while any(t.is_alive() for t in self._all_threads):
+ # Empty all backlogs and mark any remaining requests as cancelled.
+ for q in all_backlogs:
+ while True:
+ try:
+ r = q.get_nowait()
+ if r is None:
+ continue
+ elif isinstance(r, ActiveRequest):
+ r.return_channel = None
+ else: # detokenize backlog
+ _, r = r
+ if isinstance(r, ActiveRequest):
+ r.return_channel = None
+ except queue.Empty:
+ break
+
+ # Put sentinels to unblock threads.
+ for q in all_backlogs:
+ try:
+ q.put_nowait(None)
+ except queue.Full:
+ pass
+
+ # Wait for all threads to stop.
+ for t in self._all_threads:
+ t.join()
+
+ def get_total_concurrent_requests(self) -> int:
+ """Returns the total number of concurrent requests the driver can service."""
+ # We don't support filling all backlogs at once because it can cause GIL
+ # contention.
+ total_max_concurrent_decodes = sum(
+ [e.max_concurrent_decodes for e in self._generate_engines]
+ )
+ return total_max_concurrent_decodes
+
+ def place_request_on_prefill_queue(self, request: ActiveRequest):
+ """Used to place new requests for prefilling and generation."""
+ self._prefill_backlog.put(request)
+
+ def _load_cache_history(self, path: str) -> Union[None, Any]:
+ """Loads previous kv cache for a longer conversation."""
+ if path:
+ raise NotImplementedError
+ else:
+ return None
+
+ def _prefill_thread(
+ self,
+ idx: int,
+ prefill_engine: engine_api.Engine,
+ generate_backpressure: int = 3,
+ ):
+ """Thread which runs in the background performing prefills."""
+ logging.info('---------Spinning up prefill thread %d.---------', idx)
+ prefill_params = self._prefill_params[idx]
+ metadata = prefill_engine.get_tokenizer()
+ vocab = token_utils.load_vocab(metadata.path, metadata.extra_ids)
+ logging.info('---------Prefill params %d loaded.---------', idx)
+
+ while self.live:
+ # We don't want to keep lots of kv caches live in memory on the prefill
+ # slice that aren't about to be sent over to a generation slice.
+ if self._generate_backlogs[idx].qsize() < generate_backpressure:
+ # Check if there is anything on the prefill backlog, pop if so.
+ try:
+ request = self._prefill_backlog.get(block=True)
+ if request is None:
+ break
+ tempbos_id = request.vocab['bos_id'] if 'bos_id' in request.vocab else vocab.bos_id
+ tempeos_id = request.vocab['eos_id'] if 'eos_id' in request.vocab else vocab.eos_id
+ temppad_id = request.vocab['pad_id'] if 'pad_id' in request.vocab else vocab.pad_id
+
+ # TODO: Implement hot/cold cache for history.
+ history = self._load_cache_history(request.history_path) # pylint: disable = assignment-from-none
+ # Tokenize, and introduce a leading dimension
+ is_bos = not bool(request.history_path)
+ logging.info(
+ 'Prefilling on prefill engine %d : prefill queue size, %d,'
+ ' is_bos: %s, history: %s',
+ idx,
+ self._prefill_backlog.qsize(),
+ is_bos,
+ request.history_path,
+ ) # pylint: disable = line-too-long
+ padded_tokens, true_length = token_utils.tokenize_and_pad(
+ request.prefill_text,
+ vocab,
+ is_bos=is_bos,
+ eos_id = tempeos_id,
+ pad_id = temppad_id,
+ bos_id = tempbos_id,
+ max_prefill_length=prefill_engine.max_prefill_length,
+ )
+ # Compute new kv cache for the prefill_text, conditional on
+ # history.
+ prefill_result = prefill_engine.prefill(
+ params=prefill_params,
+ existing_prefix=history,
+ padded_tokens=padded_tokens,
+ true_length=true_length,
+ )
+ request.prefill_result = prefill_result
+ # Once prefill is complete, place it on the generation queue.
+ self._generate_backlogs[idx].put(request)
+ logging.info(
+ 'Placed request on the generate queue,'
+ f' {self._generate_backlogs[idx].qsize()=}'
+ )
+ except queue.Empty:
+ # Otherwise, don't do anything!
+ pass
+
+ def _generate_thread(
+ self,
+ idx: int,
+ generate_engine: engine_api.Engine,
+ my_slots: queue.Queue[int],
+ my_detokenize_backlog: queue.Queue[tuple[int, engine_api.ResultTokens]],
+ backpressure: int = 3,
+ ):
+ """Step token generation and insert prefills from backlog.
+
+ Args:
+ idx: Idx corresponding to which generation engine idx this is.
+ generate_engine: The generate engine corresponding to this thread.
+ my_slots: Integers representing free my_slots.
+ my_detokenize_backlog: Detokenize backlog for this generate engine.
+ backpressure: How many steps we can queue up before pausing, allows us to
+ hide dispatch times because jit calls are dispatched one after another.
+ We have this in the first place because we don't want to enqueue
+ thousands of steps.
+ """
+ logging.info('---------Spinning up generate thread %d.---------', idx)
+ # Keep track of what step tokens were generated at.
+ generate_timestep = 0
+ # State to store things like running kv cache in.
+ decode_state = generate_engine.init_decode_state()
+ generate_params = self._generate_params[idx]
+ logging.info('---------Generate params %d loaded.---------', idx)
+ time_of_last_generate = time.time()
+ time_of_last_print = time.time()
+ while self.live:
+ if (time.time() - time_of_last_print) > 1:
+ logging.info(
+ 'Generate thread making a decision with:'
+ f' prefill_backlog={self._prefill_backlog.qsize()} generate_free_slots={my_slots.qsize()}'
+ )
+ time_of_last_print = time.time()
+ # Check if there are any free my_slots.
+ if not my_slots.empty() and not self._generate_backlogs[idx].empty():
+ # Only get requests from the backlog corresponding to this engine.
+ new_request = self._generate_backlogs[idx].get()
+ if new_request is None:
+ break
+ slot = my_slots.get()
+ logging.info(
+ 'Generate slice %d slot %d step %d',
+ idx,
+ slot,
+ generate_timestep,
+ )
+ decode_state = generate_engine.insert(
+ new_request.prefill_result, decode_state, slot=slot
+ )
+ delete_pytree(new_request.prefill_result)
+ new_request.generate_timestep_added = generate_timestep
+ new_request.complete = np.zeros(
+ (generate_engine.samples_per_slot,), dtype=np.bool_
+ )
+ my_detokenize_backlog.put((slot, new_request))
+
+ if my_detokenize_backlog.qsize() < backpressure:
+ decode_state, sampled_tokens = generate_engine.generate(
+ generate_params, decode_state
+ )
+ sampled_tokens.copy_to_host_async()
+ my_detokenize_backlog.put((generate_timestep, sampled_tokens))
+ generate_timestep += 1
+ logging.info(
+ 'Generate engine %d step %d - slots free : %d / %d, took %.2fms',
+ idx,
+ generate_timestep,
+ my_slots.qsize(),
+ generate_engine.max_concurrent_decodes,
+ (time.time() - time_of_last_generate) * 10**3,
+ )
+ time_of_last_generate = time.time()
+
+ def _detokenize_thread(
+ self,
+ idx: int,
+ generate_engine: engine_api.Engine,
+ my_slots: queue.Queue[int],
+ my_detokenize_backlog: queue.Queue[
+ Union[tuple[int, engine_api.ResultTokens], tuple[int, ActiveRequest]]
+ ],
+ ):
+ """Detokenize sampled tokens and returns them to the user."""
+ del idx
+ # One of these per generate engine.
+ # For all filled my_slots, pop the sampled token onto the relevant
+ # requests return channel. If it done, place it back onto free slots.
+ metadata = generate_engine.get_tokenizer()
+ vocab = token_utils.load_vocab(metadata.path, metadata.extra_ids)
+
+ my_live_requests = {
+ i: None for i in range(generate_engine.max_concurrent_decodes)
+ }
+
+ while self.live:
+ try:
+ data = my_detokenize_backlog.get(block=True)
+ if data is None:
+ break
+ start_detokenise_time = time.time()
+ if isinstance(data[1], engine_api.ResultTokens):
+ # We want to detokenise them.
+ generate_timestep_added, result_tokens = data
+ # Disable attribute error because pytype doesn't know this
+ # is a result tokens, and we can't annotate the tuple.
+ result_tokens = result_tokens.convert_to_numpy() # pytype: disable=attribute-error
+
+ for slot, request in my_live_requests.items():
+ if request is not None:
+ # print(vocab)
+ # print(dir(vocab))
+ # req_vocab = json.loads(request.vocab)
+ tempbos_id = request.vocab['bos_id'] if 'bos_id' in request.vocab else vocab.bos_id
+ tempeos_id = request.vocab['eos_id'] if 'eos_id' in request.vocab else vocab.eos_id
+ temppad_id = request.vocab['pad_id'] if 'pad_id' in request.vocab else vocab.pad_id
+
+ results, complete = token_utils.process_result_tokens(
+ slot=slot,
+ slot_max_length=request.max_tokens,
+ result_tokens=result_tokens,
+ vocab=vocab,
+ eos_id = tempeos_id,
+ pad_id = temppad_id,
+ bos_id = tempbos_id,
+ complete=request.complete,
+ )
+ request.complete = complete
+ # Return some tokens.
+ request.enqueue_tokens(results)
+ if request.complete.all():
+ # Place the slot back on the free queue.
+ my_live_requests[slot] = None
+ my_slots.put(slot)
+ logging.info(
+ 'Detokenising generate step %d took %.2fms',
+ generate_timestep_added,
+ (time.time() - start_detokenise_time) * 10**3,
+ )
+ else:
+ # We want to update a slot with the new channel.
+ slot, active_request = data
+ my_live_requests[slot] = active_request
+
+ except queue.Empty:
+ # Nothing to detokenize!
+ pass
+
+
+class LLMOrchestrator(jetstream_pb2_grpc.OrchestratorServicer):
+ """Coordinates a set of prefill and generate slices for LLM decoding."""
+
+ _driver: Driver
+
+ def __init__(self, driver: Driver):
+ self._driver = driver
+
+ def Decode(
+ self,
+ request: jetstream_pb2.DecodeRequest,
+ context: Optional[grpc.ServicerContext] = None,
+ ) -> Iterable[jetstream_pb2.DecodeResponse]:
+ """Decode."""
+ if context is None:
+ logging.warning(
+ 'LLM orchestrator is being used in offline test mode, and will not'
+ ' respond to gRPC queries - only direct function calls.'
+ )
+ # Wrap request as an ActiveRequest.
+ active_request = ActiveRequest(
+ max_tokens=request.max_tokens,
+ vocab=json.loads(request.vocab),
+ history_path=request.session_cache,
+ prefill_text=request.additional_text,
+ )
+ # The first stage is being prefilled, all other stages are handled
+ # inside the driver (transfer, generate*N, detokenize).
+ try:
+ self._driver.place_request_on_prefill_queue(active_request)
+ except queue.Full:
+ # Safely abort the gRPC server thread with a retriable error.
+ _abort_or_raise(
+ context=context,
+ code=grpc.StatusCode.RESOURCE_EXHAUSTED,
+ details=(
+ 'The driver prefill queue is full and more requests cannot be'
+ ' handled. You may retry this request.'
+ ),
+ )
+ logging.info(
+ 'Placed request on the prefill queue.',
+ )
+
+ while not (
+ active_request.complete and active_request.return_channel.empty()
+ ):
+ # When an active request is created a queue is instantiated. New tokens
+ # are placed there during the decoding loop, we pop from that queue by
+ # using the .next method on the active request.
+ # Yielding allows for the response to be a streaming grpc call - which
+ # can be called via iterating over a for loop on the other side.
+ # The DecodeResponse stream should consume all generated tokens in
+ # return_channel when complete signal is received. It should check if
+ # return_channel is empty to decide if it should exit the while loop.
+ yield jetstream_pb2.DecodeResponse(response=active_request.next())
diff --git a/maxtext-setup/jetstream/jetstream/core/orchestrator_test.py b/maxtext-setup/jetstream/jetstream/core/orchestrator_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9880f93b01f3a932712b27085fb99b13ef63991
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/orchestrator_test.py
@@ -0,0 +1,103 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Integration test of the orchestrator.
+
+This test tests the multi-htreaded orchestrator, where a prefill request is
+popped onto a prefill queue, prefilled, sent to a generation queue and run for
+a number of decoding steps.
+
+In operation, it will use gRPC so we can 'yield' from the function to get return
+values in the same way that they would be streamed back.
+
+Similar to 'mock_engine_test' we can use known token values and a singleton
+weight to test our operation.
+
+Let the prefill engine have a weight of [2] and the generate engine have a
+weight of [3].
+
+I.e. if we prefill [2, 65, 66] (i.e. , 'A', 'B') using an ACII vocab,
+we should get [4, 130, 132].
+
+If we then insert that and run three generation steps, we should see
+266+0 / 2 = 266
+266 + [266] / 4 = 332
+266 + [266, 332] / 4 = 415
+I.e. ['Ċ', 'Ō', 'Ɵ'] when converted back with chr().
+
+Therefore we should get back the character sequence '$lǔ' if we request 3 tokens
+decoded (these are the ascii chars at those indices which is what the test
+tokenizer returns).
+"""
+
+from absl.testing import absltest
+from jetstream.core import orchestrator
+from jetstream.core.proto import jetstream_pb2
+from jetstream.engine import mock_engine
+
+
+class OrchestratorTest(absltest.TestCase):
+
+ def _setup_driver(self):
+ prefill_engine = mock_engine.TestEngine(
+ batch_size=32, cache_length=256, weight=2.0
+ )
+ # Create a generate engine with a different set of weights
+ # so that we can test that the right one is in use at a given time.
+ generate_engine = mock_engine.TestEngine(
+ batch_size=4, cache_length=32, weight=4.0
+ )
+ driver = orchestrator.Driver(
+ prefill_engines=[prefill_engine],
+ generate_engines=[generate_engine],
+ prefill_params=[prefill_engine.load_params()],
+ generate_params=[generate_engine.load_params()],
+ )
+ return driver
+
+ def test_orchestrator(self):
+ """Test the multithreaded orchestration."""
+ driver = self._setup_driver()
+ client = orchestrator.LLMOrchestrator(driver=driver)
+
+ # The string representation of np.array([[65, 66]]), [2] will be prepend
+ # as BOS.
+ text = 'AB'
+
+ request = jetstream_pb2.DecodeRequest(
+ session_cache='',
+ additional_text=text,
+ priority=1,
+ max_tokens=3,
+ )
+ iterator = client.Decode(request)
+ # chr of [266, 332, 415].
+ expected_tokens = ['Ċ', 'Ō', 'Ɵ', '']
+ counter = 0
+ for token in iterator:
+ # Tokens come through as bytes.
+ print(
+ 'actual output: '
+ + bytes(token.response[0], encoding='utf-8').decode()
+ )
+ assert (
+ bytes(token.response[0], encoding='utf-8').decode()
+ == expected_tokens[counter]
+ )
+ counter += 1
+ driver.stop()
+
+
+if __name__ == '__main__':
+ absltest.main()
diff --git a/maxtext-setup/jetstream/jetstream/core/proto/__init__.py b/maxtext-setup/jetstream/jetstream/core/proto/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c38dc3b14ab36f34985ad3f1b20071f4a6a16e82
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/proto/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
diff --git a/maxtext-setup/jetstream/jetstream/core/proto/jetstream.proto b/maxtext-setup/jetstream/jetstream/core/proto/jetstream.proto
new file mode 100644
index 0000000000000000000000000000000000000000..f5d3c981130b416f9b29a9dd93198bf28f6ed0b5
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/proto/jetstream.proto
@@ -0,0 +1,38 @@
+// Copyright 2024 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+syntax = "proto3";
+
+package jetstream_proto;
+
+// TODO: Merge this with main JetStream core once we settle on an API.
+
+service Orchestrator {
+ // Generate the next model tokens.
+ rpc Decode(DecodeRequest) returns (stream DecodeResponse) {}
+}
+message DecodeRequest {
+ // Where to load any pre-existing kv cache from.
+ string session_cache = 1;
+ // New text from a user or tool.
+ string additional_text = 2;
+ int32 priority = 3;
+ int32 max_tokens = 4;
+ string vocab = 5;
+}
+message DecodeResponse {
+ // List of responses, one per sample.
+ repeated string response = 1;
+}
\ No newline at end of file
diff --git a/maxtext-setup/jetstream/jetstream/core/proto/jetstream_pb2.py b/maxtext-setup/jetstream/jetstream/core/proto/jetstream_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7815029c197f71495d182d238d76d9fc972bf47
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/proto/jetstream_pb2.py
@@ -0,0 +1,44 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: jetstream/core/proto/jetstream.proto
+# Protobuf Python Version: 4.25.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+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')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'jetstream.core.proto.jetstream_pb2', _globals)
+# if _descriptor._USE_C_DESCRIPTORS == False:
+# DESCRIPTOR._options = None
+# _globals['_DECODEREQUEST']._serialized_start=57
+# _globals['_DECODEREQUEST']._serialized_end=173 #158
+# _globals['_DECODERESPONSE']._serialized_start=175 #160
+# _globals['_DECODERESPONSE']._serialized_end=209 #194
+# _globals['_ORCHESTRATOR']._serialized_start=196
+# _globals['_ORCHESTRATOR']._serialized_end=289
+# @@protoc_insertion_point(module_scope)
diff --git a/maxtext-setup/jetstream/jetstream/core/proto/jetstream_pb2_grpc.py b/maxtext-setup/jetstream/jetstream/core/proto/jetstream_pb2_grpc.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e2fb885921e7c7a77d0343522118a28d892ba0e
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/proto/jetstream_pb2_grpc.py
@@ -0,0 +1,87 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
+"""Client and server classes corresponding to protobuf-defined services."""
+import grpc
+
+from jetstream.core.proto import jetstream_pb2 as jetstream_dot_core_dot_proto_dot_jetstream__pb2
+
+
+class OrchestratorStub(object):
+ """TODO: Merge this with main JetStream core once we settle on an API.
+
+ """
+
+ def __init__(self, channel):
+ """Constructor.
+
+ Args:
+ channel: A grpc.Channel.
+ """
+ self.Decode = channel.unary_stream(
+ '/jetstream_proto.Orchestrator/Decode',
+ request_serializer=jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeRequest.SerializeToString,
+ response_deserializer=jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeResponse.FromString,
+ )
+
+
+class OrchestratorServicer(object):
+ """TODO: Merge this with main JetStream core once we settle on an API.
+
+ """
+
+ def Decode(self, request, context):
+ """Generate the next model tokens.
+ """
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details('Method not implemented!')
+ raise NotImplementedError('Method not implemented!')
+
+
+def add_OrchestratorServicer_to_server(servicer, server):
+ rpc_method_handlers = {
+ 'Decode': grpc.unary_stream_rpc_method_handler(
+ servicer.Decode,
+ request_deserializer=jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeRequest.FromString,
+ response_serializer=jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeResponse.SerializeToString,
+ ),
+ }
+ generic_handler = grpc.method_handlers_generic_handler(
+ 'jetstream_proto.Orchestrator', rpc_method_handlers)
+ server.add_generic_rpc_handlers((generic_handler,))
+
+
+ # This class is part of an EXPERIMENTAL API.
+class Orchestrator(object):
+ """TODO: Merge this with main JetStream core once we settle on an API.
+
+ """
+
+ @staticmethod
+ def Decode(request,
+ target,
+ options=(),
+ channel_credentials=None,
+ call_credentials=None,
+ insecure=False,
+ compression=None,
+ wait_for_ready=None,
+ timeout=None,
+ metadata=None):
+ return grpc.experimental.unary_stream(request, target, '/jetstream_proto.Orchestrator/Decode',
+ jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeRequest.SerializeToString,
+ jetstream_dot_core_dot_proto_dot_jetstream__pb2.DecodeResponse.FromString,
+ options, channel_credentials,
+ insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
diff --git a/maxtext-setup/jetstream/jetstream/core/server_lib.py b/maxtext-setup/jetstream/jetstream/core/server_lib.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f0c10932eac66f6c83cef4220bd6cec1a52ff92
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/server_lib.py
@@ -0,0 +1,105 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Contains common functions for a JetStream core server.
+
+See implementations/*/sever.py for examples.
+"""
+
+from concurrent import futures
+import logging
+from typing import Any, Type
+
+import grpc
+import jax
+from jetstream.core import config_lib
+from jetstream.core import orchestrator
+from jetstream.core.proto import jetstream_pb2_grpc
+
+
+_HOST = '[::]'
+
+
+class JetStreamServer:
+ """JetStream grpc server."""
+
+ def __init__(self, driver: orchestrator.Driver, server: grpc.Server):
+ self._driver = driver
+ self._server = server
+
+ def start(self, port, credentials) -> None:
+ self._server.add_secure_port(f'{_HOST}:{port}', credentials)
+ self._server.start()
+
+ def stop(self) -> None:
+ # Gracefully clean up threads in the orchestrator.
+ self._driver.stop()
+ self._server.stop(0)
+
+ def wait_for_termination(self) -> None:
+ self._server.wait_for_termination()
+
+
+def run(
+ port: int,
+ config: Type[config_lib.ServerConfig],
+ devices: Any,
+ credentials: Any = grpc.insecure_server_credentials(),
+ threads: int | None = None,
+) -> JetStreamServer:
+ """Runs a server with a specified config.
+
+ Args:
+ port: Port on which the server will be made available.
+ config: A ServerConfig to config engine, model, device slices, etc.
+ devices: Device objects, will be used to get engine with proper slicing.
+ credentials: Should use grpc credentials by default.
+ threads: Number of RPC handlers worker threads. This should be at least
+ equal to the decoding batch size to fully saturate the decoding queue.
+
+ Returns:
+ JetStreamServer that wraps the grpc server and orchestrator driver.
+ """
+ logging.info('Kicking off gRPC server.')
+ engines = config_lib.get_engines(config, devices=devices)
+ prefill_params = [pe.load_params() for pe in engines.prefill_engines]
+ generate_params = [ge.load_params() for ge in engines.generate_engines]
+ shared_params = [ie.load_params() for ie in engines.interleaved_engines]
+ logging.info('Loaded all weights.')
+ driver = orchestrator.Driver(
+ prefill_engines=engines.prefill_engines + engines.interleaved_engines,
+ generate_engines=engines.generate_engines + engines.interleaved_engines,
+ prefill_params=prefill_params + shared_params,
+ generate_params=generate_params + shared_params,
+ )
+ # We default threads to the total number of concurrent allowed decodes,
+ # to make sure we can fully saturate the model. Set default minimum to 64.
+ threads = threads or max(driver.get_total_concurrent_requests(), 64)
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=threads)) # pytype: disable=wrong-keyword-args
+ jetstream_pb2_grpc.add_OrchestratorServicer_to_server(
+ orchestrator.LLMOrchestrator(driver=driver), server
+ )
+ logging.info('Starting server on port %d with %d threads', port, threads)
+
+ jetstream_server = JetStreamServer(driver, server)
+ jetstream_server.start(port, credentials)
+ return jetstream_server
+
+
+def get_devices() -> Any:
+ """Gets devices locally."""
+ # Run interleaved engine on local device.
+ devices = jax.devices()
+ logging.info('Using local devices for interleaved serving: %d', len(devices))
+ return devices
diff --git a/maxtext-setup/jetstream/jetstream/core/server_test.py b/maxtext-setup/jetstream/jetstream/core/server_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1f3c0507888f39f885fe5adc3730ddb2bbc0f8d
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/server_test.py
@@ -0,0 +1,98 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Tests gRPC server end-to-end.
+
+See orchestrator test for why these characters specifically will be the
+response.
+"""
+
+from typing import Any, Type
+
+from absl.testing import absltest, parameterized
+import grpc
+from jetstream.core import config_lib
+from jetstream.core import server_lib
+from jetstream.core.proto import jetstream_pb2
+from jetstream.core.proto import jetstream_pb2_grpc
+import portpicker
+
+
+class ServerTest(parameterized.TestCase):
+
+ @parameterized.parameters(
+ # Uses weight 2 for prefill, 4 for decode.
+ (
+ config_lib.CPUTestServer,
+ ['Ċ', 'Ō', 'Ɵ', ''],
+ [None, None],
+ ),
+ # Uses the same prefill / generate weights (2).
+ (
+ config_lib.InterleavedCPUTestServer,
+ ['Ċ', 'Ə', 'ɖ', ''],
+ [None],
+ ),
+ )
+ def test_server(
+ self,
+ config: Type[config_lib.ServerConfig],
+ expected_tokens: list[str],
+ devices: list[Any],
+ ):
+ """Sets up a server and requests token responses."""
+ ######################### Server side ######################################
+ port = portpicker.pick_unused_port()
+ print('port: ' + str(port))
+ credentials = grpc.local_server_credentials()
+
+ server = server_lib.run(
+ port=port,
+ config=config,
+ devices=devices,
+ credentials=credentials,
+ )
+ ###################### Requester side ######################################
+ channel = grpc.secure_channel(
+ f'localhost:{port}', grpc.local_channel_credentials()
+ )
+ stub = jetstream_pb2_grpc.OrchestratorStub(channel)
+
+ # The string representation of np.array([[65, 66]]), [2] will be prependd
+ # as BOS
+ text = 'AB'
+ request = jetstream_pb2.DecodeRequest(
+ session_cache='',
+ additional_text=text,
+ priority=1,
+ max_tokens=3,
+ )
+ iterator = stub.Decode(request)
+ counter = 0
+ for token in iterator:
+ # Tokens come through as bytes
+ print(
+ 'actual output: '
+ + bytes(token.response[0], encoding='utf-8').decode()
+ )
+ assert (
+ bytes(token.response[0], encoding='utf-8').decode()
+ == expected_tokens[counter]
+ )
+ counter += 1
+ server.stop()
+
+
+if __name__ == '__main__':
+ absltest.main()
diff --git a/maxtext-setup/jetstream/jetstream/core/tools/load_tester.py b/maxtext-setup/jetstream/jetstream/core/tools/load_tester.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8c2e95bb5c0bba99a48cc2a86a929e4d537bb44
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/tools/load_tester.py
@@ -0,0 +1,122 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Miniature load test of the mock server."""
+
+import concurrent.futures
+import functools
+import time
+from typing import Sequence, Iterator
+
+from absl import app
+from absl import flags
+import grpc
+
+from jetstream.core.proto import jetstream_pb2
+from jetstream.core.proto import jetstream_pb2_grpc
+
+
+_SERVER = flags.DEFINE_string('server', 'dns:///[::1]', 'server address')
+_PORT = flags.DEFINE_string('port', '9000', 'port to ping')
+_TEXT = flags.DEFINE_string('text', 'quantum mechanics is the', 'The message')
+_MAX_TOKENS = flags.DEFINE_integer(
+ 'max_tokens', 4096, 'Maximum number of tokens'
+)
+
+
+def collect_tokens(
+ response: Iterator[jetstream_pb2.DecodeResponse], print_interim: bool
+) -> list[str]:
+ tokens = []
+ if print_interim:
+ tstart = time.perf_counter()
+ for token_list in response:
+ tok = token_list.response[0]
+ if print_interim:
+ print(tok, end='', flush=True)
+ tokens.append(tok)
+ if print_interim:
+ ttaken = time.perf_counter() - tstart
+ print(f'\n{ttaken:.2f}s')
+ print(f'TPS INDIVIDUAL: {len(tokens) / ttaken:.2f}')
+ return tokens
+
+
+def api_call(
+ stub: jetstream_pb2_grpc.OrchestratorStub,
+ text: str,
+ max_tokens: int,
+ session_cache: str = '',
+ print_interim: bool = True,
+) -> str:
+ """Sends a request to server and returns text."""
+ request = jetstream_pb2.DecodeRequest(
+ session_cache=session_cache,
+ additional_text=text,
+ priority=1,
+ max_tokens=max_tokens,
+ )
+ response = stub.Decode(request)
+ print('---------------------- Sent!!!----------------------')
+ tokens = collect_tokens(response, print_interim=print_interim)
+
+ return ''.join(tokens)
+
+
+def ping(
+ stub: jetstream_pb2_grpc.OrchestratorStub, text: str, number: int
+) -> str:
+ index, text = text
+ response = api_call(stub, text, _MAX_TOKENS.value, print_interim = True if index%96 == 0 else False)
+ print(f'Completed {number}')
+ return response
+
+
+def load_test(
+ stub: jetstream_pb2_grpc.OrchestratorStub,
+ text: list[str],
+ queries: int = 64,
+) -> list[str]:
+ """Sends many queries to the server."""
+ assert queries % len(text) == 0
+ # repeat out
+ text = text * (queries // len(text))
+ number = list(range(len(text)))
+ start = time.time()
+ ping_partial = functools.partial(ping, stub)
+ with concurrent.futures.ThreadPoolExecutor(
+ max_workers=queries) as executor:
+ responses = list(executor.map(ping_partial, enumerate(text), number))
+ time_taken = time.time() - start
+ print(responses[0])
+ print(f'Time taken: {time_taken}')
+ print(f'QPS: {queries/time_taken}')
+ print(f'TPS: {_MAX_TOKENS.value * queries / time_taken}')
+ return responses
+
+
+def main(argv: Sequence[str]):
+ del argv
+ address = f'{_SERVER.value}:{_PORT.value}'
+ # Note: Uses insecure_channel only for local testing. Please add grpc credentials for Production.
+ with grpc.insecure_channel(
+ address
+ ) as channel:
+ grpc.channel_ready_future(channel).result()
+ stub = jetstream_pb2_grpc.OrchestratorStub(channel)
+ _ = load_test(stub, text=[_TEXT.value], queries=192)
+
+
+if __name__ == '__main__':
+ app.run(main)
diff --git a/maxtext-setup/jetstream/jetstream/core/tools/requester.py b/maxtext-setup/jetstream/jetstream/core/tools/requester.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba407306e9a7b1f76fe7d5d53263914fdbd41259
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/core/tools/requester.py
@@ -0,0 +1,70 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""A test request."""
+
+from typing import Sequence
+
+from absl import app
+from absl import flags
+import grpc
+
+from jetstream.core.proto import jetstream_pb2
+from jetstream.core.proto import jetstream_pb2_grpc
+
+
+_SERVER = flags.DEFINE_string('server', 'dns:///[::1]', 'server address')
+_PORT = flags.DEFINE_string('port', '9000', 'port to ping')
+_SESSION_CACHE = flags.DEFINE_string(
+ 'session_cache', '', 'Location of any pre-cached results'
+)
+_TEXT = flags.DEFINE_string('text', 'AB', 'The message')
+_PRIORITY = flags.DEFINE_integer('priority', 0, 'Message priority')
+_MAX_TOKENS = flags.DEFINE_integer('max_tokens', 2048, 'Maximum number of tokens')
+
+
+def _GetResponseAsync(
+ stub: jetstream_pb2_grpc.OrchestratorStub,
+ request: jetstream_pb2.DecodeRequest,
+) -> None:
+ """Gets an async response."""
+
+ response = stub.Decode(request)
+ for token_list in response:
+ print(token_list.response[0], end='', flush=True)
+ print('\n')
+
+
+def main(argv: Sequence[str]) -> None:
+ del argv
+ # Note: Uses insecure_channel only for local testing. Please add grpc credentials for Production.
+ address = f'{_SERVER.value}:{_PORT.value}'
+ print(address)
+ with grpc.insecure_channel(
+ address
+ ) as channel:
+ grpc.channel_ready_future(channel).result()
+ stub = jetstream_pb2_grpc.OrchestratorStub(channel)
+ print('Making request')
+ request = jetstream_pb2.DecodeRequest(
+ session_cache=_SESSION_CACHE.value,
+ additional_text=_TEXT.value,
+ priority=_PRIORITY.value,
+ max_tokens=_MAX_TOKENS.value,
+ )
+ return _GetResponseAsync(stub, request)
+
+
+if __name__ == '__main__':
+ app.run(main)
diff --git a/maxtext-setup/jetstream/jetstream/engine/README.md b/maxtext-setup/jetstream/jetstream/engine/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..38581fb3f9e483518739c0a6b78d23e7103033ae
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/engine/README.md
@@ -0,0 +1,5 @@
+# Inference Engine Subpackage - Defines Engine API Interface
+
+The Engine class in `engine_api.py` is the Engine API Interface.
+
+mock_engine.py is the mock implementation of the Engine API Interface.
diff --git a/maxtext-setup/jetstream/jetstream/engine/__init__.py b/maxtext-setup/jetstream/jetstream/engine/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c38dc3b14ab36f34985ad3f1b20071f4a6a16e82
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/engine/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
diff --git a/maxtext-setup/jetstream/jetstream/engine/engine_api.py b/maxtext-setup/jetstream/jetstream/engine/engine_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..deb3a592c131beca95335ca7a890c1854d026311
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/engine/engine_api.py
@@ -0,0 +1,225 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Defines the JetStream API.
+
+These functions are the accelerator functions which an outer sampling loop
+could want to call, enabling interleaved (continuous batching) inference.
+"""
+
+import abc
+from typing import Any, Optional, Tuple, Union
+
+from flax import struct
+import jax
+import numpy as np
+
+from jetstream.engine import tokenizer_pb2
+
+
+# The model parameters - their partitioning will be unique for different prefill
+# and decode topoologies.
+Params = Any
+# The result of a prefill operation, often a batch size 1 KVCache.
+Prefix = Any
+# The inputs into a generation step, often a prefill and generate cache tuple.
+DecodeState = Any
+# Accelerator representation of tokens.
+DeviceTokens = Any
+# Cpus asscociated with the mesh.
+CpuDevices = Any
+
+
+@struct.dataclass
+class SlotData:
+ """Class to store slot data."""
+ tokens: Union[jax.Array, np.ndarray]
+ valid: Union[jax.Array, np.ndarray]
+ lengths: Union[jax.Array, np.ndarray]
+
+# pylint: disable=g-doc-args
+@struct.dataclass
+class ResultTokens(abc.ABC):
+ """Class to store returned tokens in.
+
+ We store everything in one array, and keep indexes - because copying
+ a single array to host is much faster.
+ Each tuple represents the indices of the relevant data.
+ """
+
+ # Shape: [batch, tokens.shape[1] + validity.shape[1] + lengths.shape[1]]
+ data: Union[jax.Array, np.ndarray]
+ # The range of indices which contain tokens.
+ tokens_idx: tuple[int, int] = struct.field(
+ pytree_node=False,
+ )
+ # The range of indices which contain the validity of
+ # the tokens.
+ valid_idx: tuple[int, int] = struct.field(
+ pytree_node=False,
+ )
+ # The range of indices which contain the lengths up till now of the lengths
+ # of each generated sequence.
+ length_idx: tuple[int, int] = struct.field(
+ pytree_node=False,
+ )
+ samples_per_slot: int = struct.field(
+ pytree_node=False,
+ )
+
+ def copy_to_host_async(self: 'ResultTokens') -> None:
+ """Copy to host asynchronously."""
+ self.data.copy_to_host_async()
+
+ def convert_to_numpy(self: 'ResultTokens') -> 'ResultTokens':
+ """Converts to numpy."""
+ return ResultTokens(
+ np.array(self.data),
+ self.tokens_idx,
+ self.valid_idx,
+ self.length_idx,
+ self.samples_per_slot,
+ )
+
+ def get_result_at_slot(
+ self, slot: int
+ ) -> SlotData:
+ """Returns the token at a given slot.
+
+ Args:
+ slot: An integer from [0, n) representing an index into the batch.
+
+ Note: implementations of this method must correctly handle
+ microbatches, if microbatches are used.
+ """
+ # Potentially get multiple beams for given slot.
+ start_idx = slot * self.samples_per_slot
+ end_idx = (slot + 1) * self.samples_per_slot
+ # Mask out any non valid tokens.
+ return SlotData(
+ tokens=self.data[start_idx:end_idx, self.tokens_idx[0]:self.tokens_idx[1]],
+ valid=self.data[start_idx:end_idx, self.valid_idx[0]:self.valid_idx[1]],
+ # Only get a 1D representation here
+ lengths=self.data[start_idx:end_idx, self.length_idx[0]:self.length_idx[1]][:, 0]
+ )
+
+
+class Engine(abc.ABC):
+ """The computational core of the generative model server.
+
+ Engine defines an API that models must adhere to as they plug into the
+ JetStream efficient serving infrastructure.
+ """
+
+ @abc.abstractmethod
+ def prefill(
+ self,
+ *,
+ params: Params,
+ existing_prefix: Optional[Prefix] = None,
+ padded_tokens: jax.Array,
+ true_length: int,
+ ) -> Prefix:
+ """Computes a kv-cache for a set of tokens conditional on existing cache.
+
+ existing_prefix (if provided) represents a prefix that has already been
+ processed by the underlying model. tokens is logically appended
+ to the text represented by `existing_prefix`. This method returns a new
+ kv_cache (typically) for the resulting text.
+ """
+
+ @abc.abstractmethod
+ def generate(
+ self,
+ params: Params,
+ decode_state: DecodeState
+ ) -> Tuple[DecodeState, ResultTokens]:
+ """Generates tokens for each sequence being decoded in parallel.
+
+ Generate takes a batch of pre-computed kv-caches, and computes:
+ - the predicted next token for each of the sequences
+ - an updated set of kv-caches
+
+ In the case of pipelining, this will handle N cycles (where each cycle
+ consists of each microbatch progressing through every stage), in
+ non-pipelined code this is a full forward pass. In both cases, this accounts
+ for a full embed-layerstack-unembed-sample operation.
+ """
+
+ @abc.abstractmethod
+ def insert(
+ self,
+ prefix: Prefix,
+ decode_state: DecodeState,
+ slot: int,
+ ) -> DecodeState:
+ """Adds `new_request` into `caches` at 'slot'.
+
+ When decoding multiple requests in parallel, when one request finishes, a
+ new request must be slotted into the recently vacated spot: `insert`!
+
+ This can occur in between and async to generate calls, and takes a lock over
+ that row of the cache.
+
+ The slot may represent a tuple of positions (e.g. microbatch, pipeline stage
+ and batch), but at the engine interface level all of these are exposed as
+ a [0, n) range of slots and converted internally.
+ """
+
+ @abc.abstractmethod
+ def load_params(self, *args, **kwargs) -> Params:
+ """Loads parameters.
+
+ May not be used in full production form, where weights are part of the saved
+ model.
+ """
+
+ @abc.abstractmethod
+ def get_prefix_destination_sharding(self) -> Any:
+ """Returns the shardings necessary to transfer data between engines."""
+
+ @abc.abstractmethod
+ def get_tokenizer(
+ self,
+ ) -> tokenizer_pb2.TokenizerParameters:
+ """Returns the info to construct a sentencepiece tokenizer in py/c++."""
+
+ @abc.abstractmethod
+ def init_decode_state(self, *args, **kwargs) -> DecodeState:
+ """Initialises any state which a generation step transforms."""
+
+ @property
+ @abc.abstractmethod
+ def max_concurrent_decodes(self) -> int:
+ """Total capacity."""
+
+ @property
+ @abc.abstractmethod
+ def samples_per_slot(self) -> int:
+ """Total samples per slot."""
+
+ @property
+ @abc.abstractmethod
+ def max_prefill_length(self) -> int:
+ """Maximum prefill length."""
+
+ @property
+ @abc.abstractmethod
+ def mesh(self) -> jax.sharding.Mesh:
+ """Mesh which the engine is running on."""
+
+ @property
+ @abc.abstractmethod
+ def colocated_cpus(self) -> Union[list[CpuDevices], None]:
+ """CPU devices colocated with the engine's accelerators."""
diff --git a/maxtext-setup/jetstream/jetstream/engine/mock_engine.py b/maxtext-setup/jetstream/jetstream/engine/mock_engine.py
new file mode 100644
index 0000000000000000000000000000000000000000..69c9d3a0cdee2f4bbc2467abd5ea94049ebb45ce
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/engine/mock_engine.py
@@ -0,0 +1,258 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Simple test engine for the JetStream API described.
+
+Contains simple functions that we can hand calculate the desired outcome of.
+
+Prefill: Doubles the sequence by multiplying it with an integer weight.
+Insert: Writes this sequence into a cache row.
+Generate step: Return sum(prefill_cache) + sum(generate_cache)/weight.
+
+I.e. if we prefill [2, 65, 66] (i.e. , 'A', 'B') using an ACII vocab,
+we should get [4, 130, 132].
+
+If we then insert that and run three generation steps, we should see
+266+0 / 2 = 266
+266 + [266] /2 = 399
+266 + [266, 399] /2 = 598
+I.e. ['Ċ', 'Ə', 'ɖ'] when converted back with chr()
+"""
+
+import functools
+from typing import Any, Optional, Tuple
+
+from flax import struct
+import jax
+from jax.experimental import mesh_utils
+import jax.numpy as jnp
+
+from jetstream.engine import engine_api
+from jetstream.engine import tokenizer_pb2
+
+
+Params = jax.Array # [1,].
+Prefix = jax.Array # [batch,] of strings with different lengths.
+
+
+@struct.dataclass
+class DecodeState:
+ """The inputs into a generation step."""
+ prefill_cache: jax.Array
+ generate_cache: jax.Array
+ generate_cache_index: int
+ generate_lengths: jax.Array
+
+
+class TestEngine(engine_api.Engine):
+ """The computational core of the generative model server.
+
+ Engine defines an API that models must adhere to as they plug into the
+ JetStream efficient serving infrastructure.
+ """
+
+ def __init__(self, batch_size: int, cache_length: int, weight: float):
+ self.prefill_cache_batch = batch_size
+ self.generate_cache_batch = batch_size
+ self.cache_length = cache_length
+ self.weight = weight
+ self._mesh = jax.sharding.Mesh(
+ mesh_utils.create_device_mesh((1, 1, 1), jax.devices()), ('x', 'y', 'z')
+ )
+
+ def load_params(self) -> Params:
+ """Loads model weights."""
+ # An integer, used to multiply inputs.
+ return jnp.array([self.weight], dtype=jnp.float32)
+
+ @functools.partial(jax.jit, static_argnums=(0,))
+ def prefill(
+ self,
+ *,
+ params: Params,
+ existing_prefix: Optional[jax.Array] = None,
+ padded_tokens: jax.Array,
+ true_length: int,
+ ) -> Prefix:
+ """Computes a kv-cache for a new generate request.
+
+ Args:
+ params: Scalar multiplier.
+ existing_prefix: If provided, represents a prefix that has already been
+ processed by the underlying model.
+ padded_tokens: Logically appended tokens to any existing prefix, this is
+ what we compute prefill on.
+ true_length: The real length of the tokens, pre-pad.
+ Returns:
+ kv_cache: For the resulting text.
+ """
+ if existing_prefix is not None:
+ raise NotImplementedError
+ del true_length
+ assert padded_tokens.ndim == 1
+ # Wait to simulate model step time.
+ fake_size = 4096
+ fake_work = jnp.ones((fake_size, fake_size)) @ jnp.ones(
+ (fake_size, fake_size)
+ )
+ # Do some fake work that isn't eliminated by dead code elimination (DCE).
+ params = params + fake_work.mean() - fake_work.mean()
+ return padded_tokens[None, :] * params
+
+ @functools.partial(jax.jit, static_argnums=(0,))
+ def generate(
+ self, params: Params, decode_state: DecodeState
+ ) -> Tuple[DecodeState, engine_api.ResultTokens]:
+ """Generates tokens for each sequence being decoded in parallel."""
+ prefill_cache, generate_cache, generate_cache_index, generate_lengths = (
+ decode_state.prefill_cache,
+ decode_state.generate_cache,
+ decode_state.generate_cache_index,
+ decode_state.generate_lengths,
+ )
+ # Sum each row of prefill cache and generate cache to produce new timestep,
+ # multiply by params.
+ l_iota = jax.lax.broadcasted_iota(
+ jnp.int32,
+ (self.generate_cache_batch, self.cache_length),
+ dimension=1,
+ )
+
+ # The generate cache should be circular and right aligned.
+ # TODO: Do we need a left aligned one to test spec sampling?
+ # Don't need the + 1 you normally would, because we don't provide a
+ # token from prefill in the dummy.
+ # This iota and masking is to allow for a cicular cache.
+ length_mask = (
+ -(l_iota - generate_cache_index + 1) % self.cache_length
+ ) <= generate_lengths[:, None]
+ length_masked_gen_cache = generate_cache * length_mask
+ new_timestep = (
+ prefill_cache.sum(axis=-1)
+ + (length_masked_gen_cache.sum(axis=-1) / params)
+ )[:, jnp.newaxis]
+ generate_cache = jax.lax.dynamic_update_slice_in_dim(
+ generate_cache, new_timestep, start_index=generate_cache_index, axis=1
+ )
+ generate_cache_index = (generate_cache_index + 1) % self.cache_length
+ # Wait to simulate model step time.
+ fake_size = 4096
+ fake_work = jnp.ones((fake_size, fake_size)) @ jnp.ones(
+ (fake_size, fake_size)
+ )
+ # Do some fake work that isn't eliminated by dead code elimination (DCE).
+ generate_cache = generate_cache + fake_work.mean() - fake_work.mean()
+ new_lengths = generate_lengths + 1
+ speculations = new_timestep.shape[1]
+ # Concatenates the tokens, their validity and the lengths of each sequence
+ # into one tensor so that copy operations are faster on Cloud TPU infrastructure.
+ token_data = jnp.concatenate(
+ [new_timestep, jnp.ones_like(new_timestep), new_lengths[:, None]],
+ axis=-1,
+ )
+ return DecodeState(
+ prefill_cache=prefill_cache,
+ generate_cache=generate_cache,
+ generate_cache_index=generate_cache_index,
+ generate_lengths=new_lengths,
+ ), engine_api.ResultTokens(
+ data=token_data.astype(jnp.int32),
+ # Tokens are shape [batch, speculations], so when we concatenate
+ # tokens, validity and length along their index 1 dimension then they
+ # occupy 0:speculations.
+ tokens_idx=(0, speculations),
+ # Validity occupies the same amount of space, but next in line.
+ valid_idx=(speculations, 2 * speculations),
+ # And lengths is rank 1.
+ length_idx=(2 * speculations, 2 * speculations + 1),
+ samples_per_slot=self.generate_cache_batch // self.prefill_cache_batch,
+ )
+
+ @functools.partial(jax.jit, static_argnums=(0,), donate_argnums=(2,))
+ def insert(
+ self,
+ prefix: Prefix,
+ decode_state: DecodeState,
+ slot: int,
+ ) -> DecodeState:
+ """Adds `prefix` into `decode_state` at `slot`."""
+ # [B, T], [T,] -> [B, T]
+ prefill_cache = jax.lax.dynamic_update_slice_in_dim(
+ decode_state.prefill_cache, prefix, slot, axis=0
+ )
+ generate_cache = jax.lax.dynamic_update_slice_in_dim(
+ decode_state.generate_cache, jnp.zeros((1, self.cache_length)),
+ slot, axis=0
+ )
+ samples_per_slot = self.generate_cache_batch // self.prefill_cache_batch
+ generate_lengths = jax.lax.dynamic_update_slice_in_dim(
+ decode_state.generate_lengths,
+ jnp.zeros((samples_per_slot), dtype=jnp.int32),
+ slot * samples_per_slot,
+ axis=0,
+ )
+ return decode_state.replace(
+ prefill_cache=prefill_cache,
+ generate_cache=generate_cache,
+ generate_lengths=generate_lengths,
+ )
+
+ def get_prefix_destination_sharding(self) -> Any:
+ return jax.sharding.NamedSharding(
+ mesh=self.mesh, spec=jax.sharding.PartitionSpec()
+ )
+
+ def get_tokenizer(self) -> tokenizer_pb2.TokenizerParameters:
+ """Return a protobuf of tokenizer info, callable from Py or C++."""
+ return tokenizer_pb2.TokenizerParameters(path='test', extra_ids=0)
+
+ def init_decode_state(self) -> DecodeState:
+ """Initialises any state which a generation step transforms."""
+ return DecodeState(
+ prefill_cache=jnp.zeros(
+ (self.prefill_cache_batch, self.cache_length), dtype=jnp.float32
+ ),
+ generate_cache=jnp.zeros(
+ (self.generate_cache_batch, self.cache_length), dtype=jnp.float32
+ ),
+ generate_cache_index=0,
+ generate_lengths=jnp.zeros(
+ (self.generate_cache_batch), dtype=jnp.int32
+ ),
+ )
+
+ @property
+ def max_concurrent_decodes(self) -> int:
+ """Free slots."""
+ return self.prefill_cache_batch
+
+ @property
+ def max_prefill_length(self) -> int:
+ """Maximum prefill length."""
+ return self.cache_length
+
+ @property
+ def samples_per_slot(self) -> int:
+ """Number of samples per slot."""
+ return self.generate_cache_batch // self.max_concurrent_decodes
+
+ @property
+ def mesh(self) -> jax.sharding.Mesh:
+ """Mesh which the engine is running on."""
+ return self._mesh
+
+ @property
+ def colocated_cpus(self) -> None:
+ """CPU devices colocated with the engine's accelerators."""
+ raise NotImplementedError
diff --git a/maxtext-setup/jetstream/jetstream/engine/mock_engine_test.py b/maxtext-setup/jetstream/jetstream/engine/mock_engine_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e01168acae193d71ad5b445e0956a053c6cb3b0
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/engine/mock_engine_test.py
@@ -0,0 +1,114 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Tests for a mock version of the engine API.
+
+What should we expect?
+
+Prefill: Doubles the sequence by multiplying it with a weight [2].
+Insert: Writes this sequence into a cache row
+Generate step: Return sum(prefill_cache) + sum(generate_cache)/weight
+
+I.e. if we prefill [2, 65, 66] (i.e. , 'A', 'B') using an ACII vocab,
+we should get [4, 130, 132].
+
+If we then insert that and run three generation steps, we should see
+266+0 / 2 = 266
+266 + [266] /2 = 399
+266 + [266, 399] /2 = 598
+I.e. ['Ċ', 'Ə', 'ɖ'] when converted back with chr()
+"""
+
+import jax.numpy as jnp
+import numpy as np
+
+from jetstream.engine import mock_engine
+from jetstream.engine import token_utils
+from absl.testing import absltest
+
+
+class EngineTest(absltest.TestCase):
+
+ def _setup(self):
+ """Initialises a test engine."""
+ engine = mock_engine.TestEngine(batch_size=32, cache_length=256, weight=2.0)
+ params = engine.load_params()
+ return engine, params
+
+ def _prefill(self):
+ """Performs prefill and returns a kv cache."""
+ engine, params = self._setup()
+ # A 2 will be pre-pended as 'bos' token from the vocab.
+ text = 'AB'
+ metadata = engine.get_tokenizer()
+ vocab = token_utils.load_vocab(metadata.path, metadata.extra_ids)
+ tokens, true_length = token_utils.tokenize_and_pad(text, vocab, is_bos=True)
+ prefill_result = engine.prefill(
+ params=params, padded_tokens=tokens, true_length=3
+ )
+ return engine, params, prefill_result, true_length
+
+ def _generate(self, slot=1):
+ """Performs a single generation step."""
+ engine, params, prefill_result, _ = self._prefill()
+ decode_state = engine.init_decode_state()
+ decode_state = engine.insert(
+ prefix=prefill_result, decode_state=decode_state, slot=slot
+ )
+ decode_state, sampled_tokens = engine.generate(
+ params=params, decode_state=decode_state
+ )
+ return engine, params, decode_state, sampled_tokens
+
+ def test_load_params(self):
+ """Just loads params."""
+ _, params = self._setup()
+ assert params == jnp.array([2.0])
+
+ def test_prefill(self):
+ """Tests prefill with weight = 2."""
+ _, _, prefill_result, true_length = self._prefill()
+ np.testing.assert_array_equal(
+ prefill_result[:, :true_length], np.array([[4.0, 130.0, 132.0]])
+ )
+
+ def test_generate(self, slot=1):
+ """Tests multiple generation steps."""
+ engine, params, decode_state, sampled_tokens = self._generate(slot=slot)
+ metadata = engine.get_tokenizer()
+ tokenizer = token_utils.load_vocab(
+ metadata.path, metadata.extra_ids
+ ).tokenizer
+ # Char for 266
+ token_data = sampled_tokens.get_result_at_slot(slot)
+ tok = token_data.tokens
+ assert tokenizer.IdToPiece(int(tok.item())) == 'Ċ'
+ decode_state, sampled_tokens = engine.generate(
+ params=params, decode_state=decode_state
+ )
+ # Char for 399
+ token_data = sampled_tokens.get_result_at_slot(slot)
+ tok = token_data.tokens
+ assert tokenizer.IdToPiece(int(tok.item())) == 'Ə'
+ _, sampled_tokens = engine.generate(
+ params=params, decode_state=decode_state
+ )
+ # Char for 598
+ token_data = sampled_tokens.get_result_at_slot(slot)
+ tok = token_data.tokens
+ assert tokenizer.IdToPiece(int(tok.item())) == 'ɖ'
+
+
+if __name__ == '__main__':
+ absltest.main()
diff --git a/maxtext-setup/jetstream/jetstream/engine/mock_utils.py b/maxtext-setup/jetstream/jetstream/engine/mock_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..63e2d87b9cb3954cc4a4e382fdb75c96b0f5efa7
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/engine/mock_utils.py
@@ -0,0 +1,77 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Utils for engine operation."""
+
+from typing import List, Sequence
+from flax import struct
+import numpy as np
+from seqio.vocabularies import Vocabulary
+
+
+@struct.dataclass
+class TestTokenizer:
+ """Tokenizer used for testing purposes."""
+
+ def IdToPiece(self, integer: int) -> str: # pylint: disable=invalid-name
+ """In the real version, unlike encode_tf/decode_tf, doesn't strip trailing whitespace."""
+ return chr(integer)
+
+
+@struct.dataclass
+class TestVocab(Vocabulary):
+ """Mock vocabulary used for tests.
+
+ These methods are duplicative on the test vocab, but required to fit
+ the seqio.Vocabulary interface.
+ """
+
+ pad_id = 0
+ eos_id = 1
+ bos_id = 2
+ unk_id = 3
+ _base_vocab_size = 2**16
+ tokenizer: TestTokenizer = TestTokenizer()
+
+ def _encode(self, s: str) -> Sequence[int]:
+ """Converts a string into a integer sequenc."""
+ # 'We use array methods, not python iterables so we don't
+ # implement this method in the mock vocab.
+ raise NotImplementedError
+
+ def _decode(self, tokens: np.ndarray):
+ """Converts a numpy array into a string."""
+ # 'We use array methods, not python iterables so we don't
+ # implement this method in the mock vocab.
+ raise NotImplementedError
+
+ def _encode_tf(self, text: str) -> np.ndarray:
+ """Converts a string into a numpy array."""
+ # We mock using numpy to avoid propagating tf dependencies.
+ chars = np.array([ord(c) for c in text]).astype(np.int32)
+ return chars
+
+ def _decode_tf(self, tokens: np.ndarray) -> List[str]:
+ """Converts a numpy array into a string."""
+ # We mock using numpy to avoid propagating tf dependencies.
+ results = np.split(tokens, tokens.shape[0])
+ return [''.join([chr(r) for r in list(line[0])]) for line in results]
+
+ def encode_tf(self, text: str) -> np.ndarray:
+ """Converts a string into a numpy array."""
+ return self._encode_tf(text)
+
+ def decode_tf(self, tokens: np.ndarray) -> List[str]:
+ """Converts a numpy array into a string."""
+ return self._decode_tf(tokens)
diff --git a/maxtext-setup/jetstream/jetstream/engine/token_utils.py b/maxtext-setup/jetstream/jetstream/engine/token_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f6aa66a5a9ddd63776ace3334753cbab0a184cd
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/engine/token_utils.py
@@ -0,0 +1,207 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Token manipulation utilities."""
+
+from bisect import bisect_left
+import logging
+from typing import List, Optional, Tuple
+
+import jax
+import jax.numpy as jnp
+import numpy as np
+from seqio.vocabularies import SentencePieceVocabulary
+from seqio.vocabularies import Vocabulary
+
+from jetstream.engine import engine_api
+from jetstream.engine import mock_utils
+
+
+def take_nearest_length(lengths: list[int], length: int) -> int:
+ """Gets the nearest length to the right in a set of lengths."""
+ pos = bisect_left(lengths, length)
+ if pos == len(lengths):
+ return lengths[-1]
+ return lengths[pos]
+
+
+def tokenize_and_pad(
+ s: str,
+ vocab: Vocabulary,
+ eos_id: int,
+ pad_id: int,
+ bos_id: int,
+ is_bos: bool = True,
+ prefill_lengths: Optional[List[int]] = None,
+ max_prefill_length: Optional[int] = None,
+) -> Tuple[jax.Array, int]:
+ """Tokenize and pads a string.
+
+ Args:
+ s: String to tokenize.
+ vocab: Vocabulary to tokenize with.
+ is_bos: Whether or not this is the beginning of a sequence. Default to yes
+ as prefill is typically used when beginning sequences.
+ prefill_lengths: Buckets to pad the sequence to for static compilation.
+ max_prefill_length: Maximum bucket to use.
+
+ Returns:
+ tokens: Tokenized into integers.
+ true_length: Actual length of the non-padded sequence.
+ """
+ if prefill_lengths is None:
+ prefill_lengths = [
+ 16,
+ 32,
+ 64,
+ 128,
+ 256,
+ 512,
+ 1024,
+ 2048,
+ 4096,
+ 8192,
+ 16384,
+ 32768,
+ ]
+ if max_prefill_length is not None:
+ prefill_lengths = prefill_lengths[
+ : prefill_lengths.index(max_prefill_length)
+ ] + [
+ max_prefill_length,
+ ]
+ tokens = np.array(vocab.encode_tf(s)) # [Length]
+ # Add a beginning of sequence token if this is the beginning.
+ if is_bos:
+ tokens = np.concatenate(
+ [
+ np.array([
+ bos_id,
+ ]),
+ tokens,
+ ],
+ axis=-1,
+ )
+ true_length = tokens.shape[-1]
+ padded_length = take_nearest_length(prefill_lengths, true_length)
+ padding = padded_length - true_length
+ assert pad_id == 0, 'Further logic required if pad_id not 0.'
+ if padding < 0:
+ logging.warning('Provided sequence longer than available.')
+ # Take the last N tokens if we have too many.
+ padded_tokens = tokens[-padded_length:]
+ else:
+ padded_tokens = np.pad(tokens, (0, padding))
+ return jnp.array(padded_tokens), true_length
+
+
+def process_result_tokens(
+ slot: int,
+ slot_max_length: int,
+ result_tokens: engine_api.ResultTokens,
+ vocab: Vocabulary,
+ eos_id: int,
+ pad_id: int,
+ bos_id: int,
+ complete: np.ndarray,
+ debug: bool = False,
+) -> Tuple[List[str], np.ndarray]:
+ """Processes a result tokens into a list of strings, handling multiple samples.
+
+ Args:
+ slot: The slot at which to draw tokens from.
+ slot_max_length: Max length for a sample in the slot.
+ result_tokens: The tokens to access by slot.
+ vocab: For the detokenizer.
+ complete: Array representing the completion status of each sample in the
+ slot.
+ debug: Whether to log step by step detokenisation.
+
+ Returns:
+ sample_return: List of strings, one per sample.
+ complete: Updated complete.
+ """
+ # tokens: [samples, speculations]
+ slot_data = result_tokens.get_result_at_slot(slot)
+ slot_tokens = slot_data.tokens
+ slot_valid = slot_data.valid
+ slot_lengths = slot_data.lengths
+ samples, speculations = slot_tokens.shape
+ stop_tokens = [eos_id, pad_id]
+ # Stop anything which has reached it's max length.
+ complete = complete | (slot_lengths > slot_max_length)
+ if debug:
+ logging.info(
+ 'Complete %s, slot_tokens: %s, slot_lengths: %s',
+ complete.__str__(),
+ slot_tokens.__str__(),
+ slot_lengths.__str__(),
+ )
+ sample_return = []
+ for idx in range(samples):
+ string_so_far = ''
+ if not complete[idx].item():
+ for spec_idx in range(speculations):
+ tok_id = slot_tokens[idx, spec_idx].item()
+ valid = slot_valid[idx, spec_idx].item()
+ if debug:
+ logging.info(
+ 'Sample idx: %d Speculation idx: %d Token: %d',
+ idx,
+ spec_idx,
+ tok_id,
+ )
+ if tok_id in stop_tokens or not valid:
+ complete[idx] = True
+ break
+ else:
+ try:
+ token = vocab.tokenizer.IdToPiece(tok_id) # pytype: disable=attribute-error
+ # ▁ or _ encodes a blank space.
+ token = token.replace('▁', ' ').replace('_', ' ')
+ except ValueError:
+ # This error only occurs when using tests where the vocab range is
+ # computed via addition and int->char is computed using chr(). Real
+ # models have vocab logits which are at max the size of the vocab.
+ logging.warning('%d exceeded vocab range', tok_id)
+ token = ''
+ string_so_far += token
+ sample_return.append(string_so_far)
+ if debug:
+ logging.info('Sampled return %s', sample_return.__str__())
+ return sample_return, complete
+
+
+def load_vocab(path: str, extra_ids: int = 0) -> Vocabulary:
+ """Eagerly loads a vocabulary.
+
+ Args:
+ path: Vocabulary file path.
+ extra_ids: Number of extra IDs.
+
+ Returns:
+ A seqio Vocabulary.
+ """
+ if path == 'test':
+ return mock_utils.TestVocab()
+ else:
+ vocab = SentencePieceVocabulary(
+ path,
+ extra_ids=extra_ids,
+ )
+ # SentencePieceVocabulary uses lazy loading. Request access to a property,
+ # forcing the lazy loading to happen now.
+ sp_model = vocab.sp_model
+ del sp_model
+ return vocab
diff --git a/maxtext-setup/jetstream/jetstream/engine/tokenizer.proto b/maxtext-setup/jetstream/jetstream/engine/tokenizer.proto
new file mode 100644
index 0000000000000000000000000000000000000000..ffa0af4dd6ebb344a5188d58644be20ab2219396
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/engine/tokenizer.proto
@@ -0,0 +1,24 @@
+// Copyright 2024 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+syntax = "proto3";
+
+package engine;
+
+option java_multiple_files = true;
+
+message TokenizerParameters {
+ string path = 1;
+ int32 extra_ids = 2;
+}
diff --git a/maxtext-setup/jetstream/jetstream/engine/tokenizer_pb2.py b/maxtext-setup/jetstream/jetstream/engine/tokenizer_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..b247a6b931b431f28771199560db7e04e2540c07
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/engine/tokenizer_pb2.py
@@ -0,0 +1,41 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: jetstream/engine/tokenizer.proto
+# Protobuf Python Version: 4.25.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+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')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'jetstream.engine.tokenizer_pb2', _globals)
+if _descriptor._USE_C_DESCRIPTORS == False:
+ _globals['DESCRIPTOR']._options = None
+ _globals['DESCRIPTOR']._serialized_options = b'P\001'
+ _globals['_TOKENIZERPARAMETERS']._serialized_start=44
+ _globals['_TOKENIZERPARAMETERS']._serialized_end=98
+# @@protoc_insertion_point(module_scope)
diff --git a/maxtext-setup/jetstream/jetstream/engine/tokenizer_pb2_grpc.py b/maxtext-setup/jetstream/jetstream/engine/tokenizer_pb2_grpc.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae028862035d22ad67e5b57f49c97b5d79cd6ed5
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/engine/tokenizer_pb2_grpc.py
@@ -0,0 +1,18 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
+"""Client and server classes corresponding to protobuf-defined services."""
+import grpc
+
diff --git a/maxtext-setup/jetstream/jetstream/engine/utils_test.py b/maxtext-setup/jetstream/jetstream/engine/utils_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..297161dfba759eb8136de891f66664c15ae71b19
--- /dev/null
+++ b/maxtext-setup/jetstream/jetstream/engine/utils_test.py
@@ -0,0 +1,83 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Tests functionality of the token processing utils using mock engine vocab."""
+
+import numpy as np
+from jetstream.engine import engine_api
+from jetstream.engine import mock_utils
+from jetstream.engine import token_utils
+from absl.testing import absltest
+
+
+class UtilsTest(absltest.TestCase):
+
+ def test_speculations_with_multi_sample_slots(self, samples_per_slot=2):
+ # [4, 1]
+ mock_tokens = np.array([
+ [0, ord('A')],
+ [ord('A'), ord('D')],
+ [ord('T'), ord('3')],
+ [ord('A'), 1],
+ ]).astype(np.int32)
+ mock_valid_tokens = np.ones_like(mock_tokens, dtype=np.int32)
+ mock_lengths = np.ones(mock_tokens.shape[0], dtype=np.int32)*2
+ # completion is 'per slot' because we track it for a given request.
+ mock_complete = np.zeros(
+ (mock_tokens.shape[0] // samples_per_slot), dtype=np.int32
+ )
+ data = np.concatenate(
+ [
+ mock_tokens,
+ mock_valid_tokens,
+ mock_lengths[:, None],
+ ],
+ axis=-1,
+ )
+ speculations = mock_tokens.shape[1]
+ result_tokens = engine_api.ResultTokens(
+ data=data.astype(np.int32),
+ tokens_idx=(0, speculations),
+ valid_idx=(speculations, 2 * speculations),
+ length_idx=(2 * speculations, 2 * speculations + 1),
+ samples_per_slot=2,
+ )
+ per_channel, complete = token_utils.process_result_tokens(
+ slot=0,
+ slot_max_length=4,
+ result_tokens=result_tokens,
+ vocab=mock_utils.TestVocab(),
+ complete=mock_complete,
+ )
+ np.testing.assert_equal(complete, np.array([1, 0]))
+
+ assert not per_channel[0] # i.e. == '', because of the pad.
+ assert per_channel[1] == 'AD'
+ mock_complete = np.zeros(
+ (mock_tokens.shape[0] // samples_per_slot), dtype=np.int32
+ )
+ per_channel, complete = token_utils.process_result_tokens(
+ slot=1,
+ slot_max_length=4,
+ result_tokens=result_tokens,
+ vocab=mock_utils.TestVocab(),
+ complete=mock_complete,
+ )
+ assert per_channel[0] == 'T3'
+ assert per_channel[1] == 'A' # second token is padded.
+ np.testing.assert_equal(complete, np.array([0, 1]))
+
+
+if __name__ == '__main__':
+ absltest.main()
diff --git a/maxtext-setup/jetstream/requirements.in b/maxtext-setup/jetstream/requirements.in
new file mode 100644
index 0000000000000000000000000000000000000000..e3a05f4259c45325e9a92efd01d76a1c1bfcf690
--- /dev/null
+++ b/maxtext-setup/jetstream/requirements.in
@@ -0,0 +1,8 @@
+absl-py
+flax
+grpcio
+jax
+jaxlib
+portpicker
+numpy
+seqio
\ No newline at end of file
diff --git a/maxtext-setup/jetstream/requirements.txt b/maxtext-setup/jetstream/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0dc7aee19de89537ac8de643921968cfa4293066
--- /dev/null
+++ b/maxtext-setup/jetstream/requirements.txt
@@ -0,0 +1,284 @@
+#
+# This file is autogenerated by pip-compile with Python 3.10
+# by the following command:
+#
+# pip-compile requirements.in
+#
+absl-py==1.4.0
+ # via
+ # -r requirements.in
+ # array-record
+ # chex
+ # clu
+ # etils
+ # ml-collections
+ # optax
+ # orbax-checkpoint
+ # seqio
+ # tensorboard
+ # tensorflow
+ # tensorflow-metadata
+ # tfds-nightly
+array-record==0.5.0
+ # via tfds-nightly
+astunparse==1.6.3
+ # via tensorflow
+cachetools==5.3.2
+ # via google-auth
+certifi==2024.2.2
+ # via requests
+charset-normalizer==3.3.2
+ # via requests
+chex==0.1.7
+ # via optax
+click==8.1.7
+ # via tfds-nightly
+clu==0.0.10
+ # via seqio
+contextlib2==21.6.0
+ # via ml-collections
+dm-tree==0.1.8
+ # via
+ # chex
+ # tfds-nightly
+docstring-parser==0.15
+ # via pyglove
+editdistance==0.6.2
+ # via seqio
+etils[array-types,enp,epath,epy,etqdm,etree]==1.6.0
+ # via
+ # array-record
+ # clu
+ # etils
+ # orbax-checkpoint
+ # tfds-nightly
+flatbuffers==23.5.26
+ # via tensorflow
+flax==0.8.0
+ # via
+ # -r requirements.in
+ # clu
+fsspec==2023.12.2
+ # via etils
+gast==0.4.0
+ # via tensorflow
+google-auth==2.27.0
+ # via
+ # google-auth-oauthlib
+ # tensorboard
+google-auth-oauthlib==1.0.0
+ # via tensorboard
+google-pasta==0.2.0
+ # via tensorflow
+googleapis-common-protos==1.62.0
+ # via tensorflow-metadata
+grpcio==1.60.1
+ # via
+ # -r requirements.in
+ # tensorboard
+ # tensorflow
+h5py==3.10.0
+ # via tensorflow
+idna==3.6
+ # via requests
+importlib-resources==6.1.1
+ # via etils
+jax==0.4.23
+ # via
+ # -r requirements.in
+ # chex
+ # clu
+ # flax
+ # optax
+ # orbax-checkpoint
+ # seqio
+jaxlib==0.4.23
+ # via
+ # -r requirements.in
+ # chex
+ # clu
+ # optax
+ # orbax-checkpoint
+ # seqio
+keras==2.13.1
+ # via tensorflow
+libclang==16.0.6
+ # via tensorflow
+markdown==3.5.2
+ # via tensorboard
+markdown-it-py==3.0.0
+ # via rich
+markupsafe==2.1.5
+ # via werkzeug
+mdurl==0.1.2
+ # via markdown-it-py
+ml-collections==0.1.1
+ # via clu
+ml-dtypes==0.3.2
+ # via
+ # jax
+ # jaxlib
+ # tensorstore
+msgpack==1.0.7
+ # via
+ # flax
+ # orbax-checkpoint
+nest-asyncio==1.6.0
+ # via orbax-checkpoint
+numpy==1.23.1
+ # via
+ # -r requirements.in
+ # chex
+ # clu
+ # etils
+ # flax
+ # h5py
+ # jax
+ # jaxlib
+ # ml-dtypes
+ # opt-einsum
+ # optax
+ # orbax-checkpoint
+ # scipy
+ # seqio
+ # tensorboard
+ # tensorflow
+ # tensorflow-hub
+ # tensorstore
+ # tfds-nightly
+oauthlib==3.2.2
+ # via requests-oauthlib
+opt-einsum==3.3.0
+ # via
+ # jax
+ # tensorflow
+optax==0.1.8
+ # via flax
+orbax-checkpoint==0.5.2
+ # via flax
+packaging==23.2
+ # via
+ # clu
+ # seqio
+ # tensorflow
+portpicker==1.6.0
+ # via -r requirements.in
+promise==2.3
+ # via tfds-nightly
+protobuf==3.20.3
+ # via
+ # googleapis-common-protos
+ # orbax-checkpoint
+ # seqio
+ # tensorboard
+ # tensorflow
+ # tensorflow-hub
+ # tensorflow-metadata
+ # tfds-nightly
+psutil==5.9.8
+ # via
+ # portpicker
+ # tfds-nightly
+pyasn1==0.5.1
+ # via
+ # pyasn1-modules
+ # rsa
+pyasn1-modules==0.3.0
+ # via google-auth
+pyglove==0.4.4
+ # via seqio
+pygments==2.17.2
+ # via rich
+pyyaml==6.0.1
+ # via
+ # flax
+ # ml-collections
+ # orbax-checkpoint
+requests==2.31.0
+ # via
+ # requests-oauthlib
+ # tensorboard
+ # tfds-nightly
+requests-oauthlib==1.3.1
+ # via google-auth-oauthlib
+rich==13.7.0
+ # via flax
+rsa==4.9
+ # via google-auth
+scipy==1.12.0
+ # via
+ # jax
+ # jaxlib
+sentencepiece==0.1.99
+ # via seqio
+seqio==0.0.19
+ # via -r requirements.in
+six==1.16.0
+ # via
+ # astunparse
+ # google-pasta
+ # ml-collections
+ # promise
+ # tensorflow
+tensorboard==2.13.0
+ # via tensorflow
+tensorboard-data-server==0.7.2
+ # via tensorboard
+tensorflow==2.13.1
+ # via tensorflow-text
+tensorflow-estimator==2.13.0
+ # via tensorflow
+tensorflow-hub==0.16.1
+ # via tensorflow-text
+tensorflow-io-gcs-filesystem==0.35.0
+ # via tensorflow
+tensorflow-metadata==1.14.0
+ # via tfds-nightly
+tensorflow-text==2.13.0
+ # via seqio
+tensorstore==0.1.52
+ # via
+ # flax
+ # orbax-checkpoint
+termcolor==2.4.0
+ # via
+ # tensorflow
+ # tfds-nightly
+tf-keras==2.15.0
+ # via tensorflow-hub
+tfds-nightly==4.9.2.dev202308090034
+ # via seqio
+toml==0.10.2
+ # via tfds-nightly
+toolz==0.12.1
+ # via chex
+tqdm==4.66.1
+ # via
+ # etils
+ # tfds-nightly
+typing-extensions==4.5.0
+ # via
+ # chex
+ # clu
+ # etils
+ # flax
+ # orbax-checkpoint
+ # tensorflow
+urllib3==2.2.0
+ # via requests
+werkzeug==3.0.1
+ # via tensorboard
+wheel==0.42.0
+ # via
+ # astunparse
+ # tensorboard
+wrapt==1.16.0
+ # via
+ # clu
+ # tensorflow
+ # tfds-nightly
+zipp==3.17.0
+ # via etils
+
+# The following packages are considered to be unsafe in a requirements file:
+# setuptools
diff --git a/maxtext-setup/jetstream/setup.py b/maxtext-setup/jetstream/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a7394222f00eceff7aa915308014d02bde8172a
--- /dev/null
+++ b/maxtext-setup/jetstream/setup.py
@@ -0,0 +1,45 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from setuptools import find_packages, setup
+
+
+def parse_requirements(filename):
+ """load requirements from a pip requirements file."""
+ with open(filename) as f:
+ lineiter = (line.strip() for line in f)
+ return [line for line in lineiter if line and not line.startswith('#')]
+
+
+setup(
+ name='google-jetstream',
+ version='0.1.1',
+ description=(
+ 'A throughput and memory optimized engine for LLM inference on TPU and'
+ ' GPU.'
+ ),
+ long_description=open('README.md').read(),
+ long_description_content_type='text/markdown',
+ author='Google LLC',
+ url='https://github.com/google/JetStream',
+ packages=find_packages(exclude='benchmarks'),
+ classifiers=[
+ 'Programming Language :: Python :: 3.10',
+ 'License :: OSI Approved :: Apache Software License',
+ 'Operating System :: OS Independent',
+ ],
+ python_requires='>=3.10',
+ install_requires=parse_requirements('requirements.in'),
+)
+