forked from tenstorrent/tt-inference-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbatch_processor.py
286 lines (252 loc) · 10.1 KB
/
batch_processor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# SPDX-License-Identifier: Apache-2.0
#
# SPDX-FileCopyrightText: © 2024 Tenstorrent AI ULC
import threading
import logging
import json
import time
from pathlib import Path
from typing import List, Union
from concurrent.futures import ThreadPoolExecutor, as_completed
import numpy as np
from transformers import AutoTokenizer
from utils.prompt_configs import BatchConfig
from utils.prompt_client import PromptClient
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class BatchProcessor:
def __init__(self, prompt_client: PromptClient, batch_config: BatchConfig):
self.prompt_client = prompt_client
self.batch_config = batch_config
self.responses_lock = threading.Lock()
def _calculate_max_concurrents(self, num_prompts: int) -> List[int]:
if self.batch_config.vary_max_concurrent:
mean_workers = self.batch_config.max_concurrent / 2
std_dev = self.batch_config.max_concurrent / 4
max_concurrents = []
remaining = num_prompts
while remaining > 0:
size = int(
np.clip(
np.random.normal(mean_workers, std_dev),
1,
self.batch_config.max_concurrent,
)
)
if size > remaining:
size = remaining
max_concurrents.append(size)
remaining -= size
return max_concurrents
return [self.batch_config.max_concurrent] * (
num_prompts // self.batch_config.max_concurrent
)
def process_batch(
self,
prompts: List[str],
images: List[List[str]],
input_seq_lengths: List[int],
tokenizer: AutoTokenizer,
output_path: Union[Path, str] = None,
) -> List[dict]:
total_prompts = len(prompts) * self.batch_config.num_full_iterations
response_counter = 0
all_responses = []
if output_path:
with open(output_path, "a") as f:
f.write("[\n")
if self.batch_config.max_concurrent == 1:
all_responses = self._process_single_thread(
prompts,
images,
input_seq_lengths,
tokenizer,
output_path,
total_prompts,
response_counter,
)
else:
all_responses = self._process_multi_thread(
prompts,
images,
input_seq_lengths,
tokenizer,
output_path,
total_prompts,
response_counter,
)
if output_path:
with open(output_path, "a") as f:
f.write("\n]")
return all_responses
def _process_single_thread(
self,
prompts: List[str],
images: List[List[str]],
input_seq_lengths: List[int],
tokenizer: AutoTokenizer,
output_path: Union[Path, str],
total_prompts: int,
response_counter: int,
) -> List[dict]:
all_responses = []
for iter_num in range(self.batch_config.num_full_iterations):
for i, (prompt, img, isl) in enumerate(
zip(prompts, images, input_seq_lengths)
):
if self.batch_config.inter_batch_delay > 0:
time.sleep(self.batch_config.inter_batch_delay)
response_idx = iter_num * len(prompts) + i
response_data = self.prompt_client.call_inference(
prompt=prompt,
images=img,
response_idx=response_idx,
prompt_len=isl,
max_tokens=self.batch_config.output_seq_lens[i],
stream=self.batch_config.stream,
vll_model=self.prompt_client.env_config.vllm_model,
tokenizer=tokenizer,
use_chat_api=self.batch_config.use_chat_api,
)
self._save_response(
response_data, all_responses, output_path, response_counter
)
response_counter += 1
self._log_progress(response_counter, total_prompts, response_data)
return all_responses
def _process_multi_thread(
self,
prompts: List[str],
images: List[List[str]],
input_seq_lengths: List[int],
tokenizer: AutoTokenizer,
output_path: Union[Path, str],
total_prompts: int,
response_counter: int,
) -> List[dict]:
all_responses = []
if self.batch_config.vary_max_concurrent:
max_concurrents = self._calculate_max_concurrents(len(prompts))
for iter_num in range(self.batch_config.num_full_iterations):
batch_start = 0
for maxcon in max_concurrents:
batch_end = min(batch_start + maxcon, len(prompts))
self._process_batch_chunk(
prompts[batch_start:batch_end],
input_seq_lengths[batch_start:batch_end],
images[batch_start:batch_end],
iter_num,
maxcon,
tokenizer,
all_responses,
output_path,
total_prompts,
response_counter,
)
batch_start = batch_end
else:
with ThreadPoolExecutor(
max_workers=self.batch_config.max_concurrent
) as executor:
futures = []
for iter_num in range(self.batch_config.num_full_iterations):
for i, (prompt, img, isl) in enumerate(
zip(prompts, images, input_seq_lengths)
):
response_idx = iter_num * len(prompts) + i
future = executor.submit(
self.prompt_client.call_inference,
prompt=prompt,
images=img,
response_idx=response_idx,
prompt_len=isl,
max_tokens=self.batch_config.output_seq_lens[i],
stream=self.batch_config.stream,
vll_model=self.prompt_client.env_config.vllm_model,
tokenizer=tokenizer,
use_chat_api=self.batch_config.use_chat_api,
)
futures.append(future)
for future in as_completed(futures):
try:
response_data = future.result()
self._save_response(
response_data, all_responses, output_path, response_counter
)
response_counter += 1
self._log_progress(
response_counter, total_prompts, response_data
)
except Exception as e:
logger.error(f"Error processing response: {e}")
return all_responses
def _process_batch_chunk(
self,
batch_prompts: List[str],
batch_images: List[List[str]],
batch_input_seq_lengths: List[int],
iter_num: int,
max_concurrent: int,
tokenizer: AutoTokenizer,
all_responses: List[dict],
output_path: Union[Path, str],
total_prompts: int,
response_counter: int,
):
if self.batch_config.inter_batch_delay > 0:
time.sleep(self.batch_config.inter_batch_delay)
with ThreadPoolExecutor(max_workers=max_concurrent) as executor:
futures = []
for i, (prompt, images, isl) in enumerate(
zip(batch_prompts, batch_images, batch_input_seq_lengths)
):
response_idx = iter_num * len(batch_prompts) + i
future = executor.submit(
self.prompt_client.call_inference,
prompt=prompt,
images=images,
response_idx=response_idx,
prompt_len=isl,
max_tokens=self.batch_config.output_seq_lens[i],
stream=self.batch_config.stream,
vll_model=self.prompt_client.env_config.vllm_model,
tokenizer=tokenizer,
)
futures.append(future)
for future in as_completed(futures):
try:
response_data = future.result()
self._save_response(
response_data, all_responses, output_path, response_counter
)
response_counter += 1
self._log_progress(response_counter, total_prompts, response_data)
except Exception as e:
logger.error(f"Error processing response: {e}")
def _save_response(
self,
response_data: dict,
all_responses: List[dict],
output_path: Union[Path, str],
response_counter: int,
):
with self.responses_lock:
all_responses.append(response_data)
if output_path:
with open(output_path, "a") as f:
if response_counter > 0:
f.write(",")
json.dump(response_data, f, indent=4)
def _log_progress(
self, response_counter: int, total_prompts: int, response_data: dict
):
logger.info(
f"Processed {response_counter}/{total_prompts} responses. "
f"TPOT: {response_data['tpot_ms']:.4f}, "
f"TTFT: {response_data['ttft_ms']:.4f}, "
f"input_seq_len: {response_data['input_seq_len']}, "
f"output_seq_len: {response_data['output_seq_len']}"
)