-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathmodel_worker.py
542 lines (477 loc) · 17 KB
/
model_worker.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
"""
A model worker that executes the model.
"""
import argparse
import asyncio
import dataclasses
import logging
import json
import os
import time
from typing import List
import threading
import uuid
from fastapi import FastAPI, Request, BackgroundTasks
from fastapi.responses import StreamingResponse, JSONResponse
import requests
try:
from transformers import (
AutoTokenizer,
AutoModelForCausalLM,
LlamaTokenizer,
AutoModel,
)
except ImportError:
from transformers import (
AutoTokenizer,
AutoModelForCausalLM,
LLaMATokenizer,
AutoModel,
)
import torch
import torch.nn.functional as F
import uvicorn
from fastchat.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
from fastchat.model.model_adapter import (
load_model,
add_model_args,
get_conversation_template,
get_generate_stream_function,
)
from fastchat.modules.gptq import GptqConfig
from fastchat.utils import build_logger, pretty_print_semaphore, get_context_length
from sot.models.batch_inference import batch_generate_stream
from sot.schedulers.naive_scheduler import NaiveScheduler
from sot.schedulers.outline_batch_scheduler import OutlineBatchScheduler
from sot.schedulers.router_outline_batch_scheduler import RouterOutlineBatchScheduler
from sot.models.fastchat_model import FastChatModel
worker_id = str(uuid.uuid4())[:8]
logger = build_logger("model_worker", f"model_worker_{worker_id}.log")
app = FastAPI()
def heart_beat_worker(obj):
while True:
time.sleep(WORKER_HEART_BEAT_INTERVAL)
obj.send_heart_beat()
class BaseModelWorker:
def __init__(
self,
controller_addr: str,
worker_addr: str,
worker_id: str,
model_path: str,
model_names: List[str],
limit_worker_concurrency: int,
):
self.controller_addr = controller_addr
self.worker_addr = worker_addr
self.worker_id = worker_id
if model_path.endswith("/"):
model_path = model_path[:-1]
self.model_names = model_names or [model_path.split("/")[-1]]
self.limit_worker_concurrency = limit_worker_concurrency
self.conv = get_conversation_template(model_path)
self.conv.sep_style = int(self.conv.sep_style)
self.tokenizer = None
self.context_len = None
self.call_ct = 0
self.semaphore = None
self.heart_beat_thread = None
def init_heart_beat(self):
self.register_to_controller()
self.heart_beat_thread = threading.Thread(
target=heart_beat_worker, args=(self,)
)
self.heart_beat_thread.start()
def register_to_controller(self):
logger.info("Register to controller")
url = self.controller_addr + "/register_worker"
data = {
"worker_name": self.worker_addr,
"check_heart_beat": True,
"worker_status": self.get_status(),
}
r = requests.post(url, json=data)
assert r.status_code == 200
def send_heart_beat(self):
logger.info(
f"Send heart beat. Models: {self.model_names}. "
f"Semaphore: {pretty_print_semaphore(self.semaphore)}. "
f"call_ct: {self.call_ct}. "
f"worker_id: {self.worker_id}. "
)
url = self.controller_addr + "/receive_heart_beat"
while True:
try:
ret = requests.post(
url,
json={
"worker_name": self.worker_addr,
"queue_length": self.get_queue_length(),
},
timeout=5,
)
exist = ret.json()["exist"]
break
except requests.exceptions.RequestException as e:
logger.error(f"heart beat error: {e}")
time.sleep(5)
if not exist:
self.register_to_controller()
def get_queue_length(self):
if (
self.semaphore is None
or self.semaphore._value is None
or self.semaphore._waiters is None
):
return 0
else:
return (
self.limit_worker_concurrency
- self.semaphore._value
+ len(self.semaphore._waiters)
)
def get_status(self):
return {
"model_names": self.model_names,
"speed": 1,
"queue_length": self.get_queue_length(),
}
def count_token(self, params):
prompt = params["prompt"]
input_ids = self.tokenizer(prompt).input_ids
input_echo_len = len(input_ids)
ret = {
"count": input_echo_len,
"error_code": 0,
}
return ret
def get_conv_template(self):
return {"conv": self.conv}
class ModelWorker(BaseModelWorker):
def __init__(
self,
controller_addr: str,
worker_addr: str,
worker_id: str,
model_path: str,
model_names: List[str],
limit_worker_concurrency: int,
no_register: bool,
device: str,
num_gpus: int,
max_gpu_memory: str,
load_8bit: bool = False,
cpu_offloading: bool = False,
gptq_ckpt: str = None,
gptq_wbits: int = None,
gptq_groupsize: int = None,
gptq_act_order: bool = None,
awq_ckpt: str = None,
awq_wbits: int = None,
awq_groupsize: int = None,
revision: str = None,
stream_interval: int = 2,
conv_template: str = None,
temperature: float = 0.7,
repetition_penalty: float = 1.0,
max_new_tokens: int = 512,
prompt_file: str = None,
router_file: str = None,
):
super().__init__(
controller_addr,
worker_addr,
worker_id,
model_path,
model_names,
limit_worker_concurrency,
)
logger.info(f"Loading the model {self.model_names} on worker {worker_id} ...")
self._model = FastChatModel(
model_path=model_path,
device=device,
gpus=None,
num_gpus=num_gpus,
max_gpu_memory=max_gpu_memory,
load_8bit=load_8bit,
cpu_offloading=cpu_offloading,
gptq_ckpt=gptq_ckpt,
gptq_wbits=gptq_wbits,
gptq_groupsize=gptq_groupsize,
gptq_act_order=gptq_act_order,
awq_ckpt=awq_ckpt,
awq_wbits=awq_wbits,
awq_groupsize=awq_groupsize,
conv_template=conv_template,
temperature=temperature,
repetition_penalty=repetition_penalty,
max_new_tokens=max_new_tokens,
revision=revision,
)
self.tokenizer = self._model.tokenizer
logger.info("Loading Scheduler...")
if router_file is not None:
# SoT-R
self.model_names = [
model_name + " (SoT-R)" for model_name in self.model_names
]
self.scheduler = RouterOutlineBatchScheduler(
model=self._model,
router_name_or_path=router_file,
naive_prompt_file=None,
outline_prompt_file=prompt_file,
)
elif prompt_file is not None:
# SoT
self.model_names = [
model_name + " (SoT)" for model_name in self.model_names
]
self.scheduler = OutlineBatchScheduler(
prompt_file=prompt_file, model=self._model
)
else:
# Normal
self.model_names = [
model_name + " (Normal)" for model_name in self.model_names
]
self.scheduler = NaiveScheduler(model=self._model)
if not no_register:
self.init_heart_beat()
def generate_stream_gate(self, params):
self.call_ct += 1
request = params["prompt"]
self._model.set_params(
params["temperature"],
params["repetition_penalty"],
params["max_new_tokens"],
)
self.scheduler.set_model(self._model)
starter, ender = torch.cuda.Event(enable_timing=True), torch.cuda.Event(
enable_timing=True
)
starter.record()
torch.cuda.reset_peak_memory_stats()
try:
for output in self.scheduler.get_response(request, stream=True):
ret = {
"text": output["text"],
"error_code": 0,
}
if "usage" in output:
ret["usage"] = output["usage"]
if "finish_reason" in output:
ret["finish_reason"] = output["finish_reason"]
if "logprobs" in output:
ret["logprobs"] = output["logprobs"]
yield json.dumps(ret).encode() + b"\0"
except torch.cuda.OutOfMemoryError as e:
ret = {
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
}
yield json.dumps(ret).encode() + b"\0"
except (ValueError, RuntimeError) as e:
ret = {
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
"error_code": ErrorCode.INTERNAL_ERROR,
}
yield json.dumps(ret).encode() + b"\0"
ender.record()
torch.cuda.synchronize()
tim = starter.elapsed_time(ender)
mem = torch.cuda.max_memory_allocated()
token_size = self.count_token({"prompt": ret["text"]})["count"]
ret["meta_info"] = (
"Generation Time: {:.2f}s".format(tim / 1000)
+ "\n"
+ "Memory Usage: {:.1f} GB".format(mem / 1.0 / 1024**3)
+ "\n"
+ "Token Size: {}".format(token_size)
)
yield json.dumps(ret).encode() + b"\0"
def generate_gate(self, params):
for x in self.generate_stream_gate(params):
pass
return json.loads(x[:-1].decode())
@torch.inference_mode()
def get_embeddings(self, params):
self.call_ct += 1
try:
tokenizer = self.tokenizer
is_llama = "llama" in str(
type(self.model)
) # llama supports batch inference
is_chatglm = "chatglm" in str(type(self.model))
is_t5 = "t5" in str(type(self.model))
if is_llama:
encoding = tokenizer.batch_encode_plus(
params["input"], padding=True, return_tensors="pt"
)
input_ids = encoding["input_ids"].to(self.device)
attention_mask = encoding["attention_mask"].to(self.device)
model_output = self.model(
input_ids, attention_mask, output_hidden_states=True
)
data = model_output.hidden_states[-1]
mask = attention_mask.unsqueeze(-1).expand(data.size()).float()
masked_embeddings = data * mask
sum_embeddings = torch.sum(masked_embeddings, dim=1)
seq_length = torch.sum(mask, dim=1)
embedding = sum_embeddings / seq_length
normalized_embeddings = F.normalize(embedding, p=2, dim=1)
ret = {
"embedding": normalized_embeddings.tolist(),
"token_num": torch.sum(attention_mask).item(),
}
else:
embedding = []
token_num = 0
for text in params["input"]:
input_ids = tokenizer.encode(text, return_tensors="pt").to(
self.device
)
if is_t5:
model_output = self.model(
input_ids, decoder_input_ids=input_ids
)
else:
model_output = self.model(input_ids, output_hidden_states=True)
if is_chatglm:
data = (model_output.hidden_states[-1].transpose(0, 1))[0]
elif is_t5:
data = model_output.encoder_last_hidden_state[0]
else:
data = model_output.hidden_states[-1][0]
data = F.normalize(torch.mean(data, dim=0), p=2, dim=0)
embedding.append(data.tolist())
token_num += len(input_ids[0])
ret = {
"embedding": embedding,
"token_num": token_num,
}
except torch.cuda.OutOfMemoryError as e:
ret = {
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
}
except (ValueError, RuntimeError) as e:
ret = {
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
"error_code": ErrorCode.INTERNAL_ERROR,
}
return ret
def release_worker_semaphore():
worker.semaphore.release()
def acquire_worker_semaphore():
if worker.semaphore is None:
worker.semaphore = asyncio.Semaphore(worker.limit_worker_concurrency)
return worker.semaphore.acquire()
def create_background_tasks():
background_tasks = BackgroundTasks()
background_tasks.add_task(release_worker_semaphore)
return background_tasks
@app.post("/worker_generate_stream")
async def api_generate_stream(request: Request):
params = await request.json()
await acquire_worker_semaphore()
generator = worker.generate_stream_gate(params)
background_tasks = create_background_tasks()
return StreamingResponse(generator, background=background_tasks)
@app.post("/worker_generate")
async def api_generate(request: Request):
params = await request.json()
await acquire_worker_semaphore()
output = worker.generate_gate(params)
release_worker_semaphore()
return JSONResponse(output)
@app.post("/worker_get_embeddings")
async def api_get_embeddings(request: Request):
params = await request.json()
await acquire_worker_semaphore()
embedding = worker.get_embeddings(params)
release_worker_semaphore()
return JSONResponse(content=embedding)
@app.post("/worker_get_status")
async def api_get_status(request: Request):
return worker.get_status()
@app.post("/count_token")
async def api_count_token(request: Request):
params = await request.json()
return worker.count_token(params)
@app.post("/worker_get_conv_template")
async def api_get_conv(request: Request):
return worker.get_conv_template()
@app.post("/model_details")
async def api_model_details(request: Request):
return {"context_length": worker.context_len}
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--host", type=str, default="0.0.0.0")
parser.add_argument("--port", type=int, default=21002)
parser.add_argument("--worker-address", type=str, default="http://0.0.0.0:21002")
parser.add_argument(
"--controller-address", type=str, default="http://0.0.0.0:21001"
)
add_model_args(parser)
parser.add_argument(
"--model-names",
type=lambda s: s.split(","),
help="Optional display comma separated names",
)
parser.add_argument(
"--limit-worker-concurrency",
type=int,
default=5,
help="Limit the model concurrency to prevent OOM.",
)
parser.add_argument("--stream-interval", type=int, default=2)
parser.add_argument("--no-register", action="store_true")
parser.add_argument(
"--sot",
default=None,
help=(
"The SoT prompt file path. Default to None, meaning the normal decoding"
" mode."
),
)
parser.add_argument(
"--sotr",
default=None,
help=(
"The SoT-R router file path. Default to None, meaning not to use the router"
),
)
args = parser.parse_args()
logger.info(f"args: {args}")
if args.gpus:
if len(args.gpus.split(",")) < args.num_gpus:
raise ValueError(
f"Larger --num-gpus ({args.num_gpus}) than --gpus {args.gpus}!"
)
os.environ["CUDA_VISIBLE_DEVICES"] = args.gpus
worker = ModelWorker(
args.controller_address,
args.worker_address,
worker_id,
args.model_path,
args.model_names,
args.limit_worker_concurrency,
no_register=args.no_register,
device=args.device,
num_gpus=args.num_gpus,
max_gpu_memory=args.max_gpu_memory,
load_8bit=args.load_8bit,
cpu_offloading=args.cpu_offloading,
gptq_ckpt=args.gptq_ckpt,
gptq_wbits=args.gptq_wbits,
gptq_groupsize=args.gptq_groupsize,
gptq_act_order=args.gptq_act_order,
awq_ckpt=args.awq_ckpt,
awq_wbits=args.awq_wbits,
awq_groupsize=args.awq_groupsize,
revision=args.revision,
stream_interval=args.stream_interval,
prompt_file=args.sot,
router_file=args.sotr,
)
uvicorn.run(app, host=args.host, port=args.port, log_level="info")