launch_server.py 7.89 KB
Newer Older
Pan Zezhong's avatar
Pan Zezhong committed
1
2
from jiuge import JiugeForCauslLM
from libinfinicore_infer import DeviceType
Pan Zezhong's avatar
Pan Zezhong committed
3
4
from infer_task import InferTask
from kvcache_pool import KVCachePool
Pan Zezhong's avatar
Pan Zezhong committed
5

Pan Zezhong's avatar
Pan Zezhong committed
6
import queue
Pan Zezhong's avatar
Pan Zezhong committed
7
8
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse, JSONResponse
Pan Zezhong's avatar
Pan Zezhong committed
9
import contextlib
Pan Zezhong's avatar
Pan Zezhong committed
10
11
12
13
14
import uvicorn
import time
import uuid
import sys
import json
Pan Zezhong's avatar
Pan Zezhong committed
15
16
import threading
import janus
Pan Zezhong's avatar
Pan Zezhong committed
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

if len(sys.argv) < 3:
    print(
        "Usage: python launch_server.py [--cpu | --nvidia| --cambricon | --ascend | --metax | --moore] <path/to/model_dir> [n_device]"
    )
    sys.exit(1)
model_path = sys.argv[2]
device_type = DeviceType.DEVICE_TYPE_CPU
if sys.argv[1] == "--cpu":
    device_type = DeviceType.DEVICE_TYPE_CPU
elif sys.argv[1] == "--nvidia":
    device_type = DeviceType.DEVICE_TYPE_NVIDIA
elif sys.argv[1] == "--cambricon":
    device_type = DeviceType.DEVICE_TYPE_CAMBRICON
elif sys.argv[1] == "--ascend":
    device_type = DeviceType.DEVICE_TYPE_ASCEND
elif sys.argv[1] == "--metax":
    device_type = DeviceType.DEVICE_TYPE_METAX
elif sys.argv[1] == "--moore":
    device_type = DeviceType.DEVICE_TYPE_MOORE
else:
    print(
        "Usage: python launch_server.py [--cpu | --nvidia| --cambricon | --ascend | --metax | --moore] <path/to/model_dir> [n_device]"
    )
    sys.exit(1)
ndev = int(sys.argv[3]) if len(sys.argv) > 3 else 1

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

def chunk_json(id_, content=None, role=None, finish_reason=None):
    delta = {}
    if content:
        delta["content"] = content
    if role:
        delta["role"] = role
    return {
        "id": id_,
        "object": "chat.completion.chunk",
        "created": int(time.time()),
        "model": "jiuge",
        "system_fingerprint": None,
        "choices": [
            {
                "index": 0,
                "delta": delta,
                "logprobs": None,
                "finish_reason": finish_reason,
            }
        ],
    }

Pan Zezhong's avatar
Pan Zezhong committed
67

Pan Zezhong's avatar
Pan Zezhong committed
68
MAX_BATCH = 3
Pan Zezhong's avatar
Pan Zezhong committed
69
70
71
print(
    f"Using MAX_BATCH={MAX_BATCH}. Try reduce this value if out of memory error occurs."
)
Pan Zezhong's avatar
Pan Zezhong committed
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


@contextlib.asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    app.state.model = JiugeForCauslLM(model_path, device_type, ndev)
    app.state.kv_cache_pool = KVCachePool(app.state.model, MAX_BATCH)
    app.state.request_queue = janus.Queue()
    worker_thread = threading.Thread(target=worker_loop, args=(app,), daemon=True)
    worker_thread.start()

    try:
        yield  # The app runs here
    finally:
        # Shutdown
        app.state.request_queue.sync_q.put(None)
        worker_thread.join()
        app.state.request_queue.shutdown()

        app.state.kv_cache_pool.finalize()
        app.state.model.destroy_model_instance()


App = FastAPI(lifespan=lifespan)


# App loop: take requests from the queue, do inference, and put unfinished requests back into the queue.
def worker_loop(app):
    while True:
        try:
            task = app.state.request_queue.sync_q.get(timeout=0.01)
        except queue.Empty:
            continue

        if task is None:
            return

        batch = [task]
        while len(batch) < MAX_BATCH:
            try:
                req = app.state.request_queue.sync_q.get_nowait()
                if req is not None:
                    batch.append(req)
            except queue.Empty:
                break
        output_tokens = app.state.model.batch_infer_one_round(batch)
        for task, token in zip(batch, output_tokens):
            task.output(token)
            if task.finish_reason is None:
                app.state.request_queue.sync_q.put(task)
            else:
                print(f"[INFO] Task {task.id} finished infer.")
                app.state.kv_cache_pool.release_sync(task)


def build_task(id_, request_data, request: Request):
    messages = request_data.get("messages", [])
    input_content = request.app.state.model.tokenizer.apply_chat_template(
        conversation=messages,
        add_generation_prompt=True,
        tokenize=False,
    )
    tokens = request.app.state.model.tokenizer.encode(input_content)
    return InferTask(
        id_,
        tokens,
        request_data.get("max_tokens", request.app.state.model.max_context_len()),
        request_data.get("temperature", 1.0),
        request_data.get("top_k", 1),
        request_data.get("top_p", 1.0),
        request.app.state.model.eos_token_id,
    )


Pan Zezhong's avatar
Pan Zezhong committed
146
147
async def chat_stream(id_, request_data, request: Request):
    try:
Pan Zezhong's avatar
Pan Zezhong committed
148
149
150
151
        infer_task = build_task(id_, request_data, request)
        await request.app.state.kv_cache_pool.acquire(infer_task)

        # Initial empty content
Pan Zezhong's avatar
Pan Zezhong committed
152
        chunk = json.dumps(
Pan Zezhong's avatar
Pan Zezhong committed
153
            chunk_json(id_, content="", role="assistant"), ensure_ascii=False
Pan Zezhong's avatar
Pan Zezhong committed
154
155
156
        )
        yield f"{chunk}\n\n"

Pan Zezhong's avatar
Pan Zezhong committed
157
158
159
        request.app.state.request_queue.sync_q.put(infer_task)

        while True:
Pan Zezhong's avatar
Pan Zezhong committed
160
161
162
            if await request.is_disconnected():
                print("Client disconnected. Aborting stream.")
                break
Pan Zezhong's avatar
Pan Zezhong committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
            if (
                infer_task.finish_reason is not None
                and infer_task.output_queue.async_q.empty()
            ):
                chunk = json.dumps(
                    chunk_json(id_, finish_reason=infer_task.finish_reason),
                    ensure_ascii=False,
                )
                yield f"{chunk}\n\n"
                break

            token = await infer_task.output_queue.async_q.get()
            content = (
                request.app.state.model.tokenizer._tokenizer.id_to_token(token)
                .replace("▁", " ")
                .replace("<0x0A>", "\n")
Pan Zezhong's avatar
Pan Zezhong committed
179
            )
Pan Zezhong's avatar
Pan Zezhong committed
180
            chunk = json.dumps(chunk_json(id_, content=content), ensure_ascii=False)
Pan Zezhong's avatar
Pan Zezhong committed
181
182
            yield f"{chunk}\n\n"

Pan Zezhong's avatar
Pan Zezhong committed
183
184
    except Exception as e:
        print(f"[Error] ID : {id_} Exception: {e}")
Pan Zezhong's avatar
Pan Zezhong committed
185
186
187
    finally:
        if infer_task.finish_reason is None:
            infer_task.finish_reason = "cancel"
Pan Zezhong's avatar
Pan Zezhong committed
188

Pan Zezhong's avatar
Pan Zezhong committed
189

Pan Zezhong's avatar
Pan Zezhong committed
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
async def chat(id_, request_data, request: Request):
    try:
        infer_task = build_task(id_, request_data, request)
        await request.app.state.kv_cache_pool.acquire(infer_task)
        request.app.state.request_queue.sync_q.put(infer_task)
        output = []
        while True:
            if (
                infer_task.finish_reason is not None
                and infer_task.output_queue.async_q.empty()
            ):
                break

            token = await infer_task.output_queue.async_q.get()
            content = (
                request.app.state.model.tokenizer._tokenizer.id_to_token(token)
                .replace("▁", " ")
                .replace("<0x0A>", "\n")
            )
            output.append(content)

        output_text = "".join(output).strip()
        response = chunk_json(
            id_,
            content=output_text,
            role="assistant",
            finish_reason=infer_task.finish_reason or "stop",
        )
        return response

    except Exception as e:
        print(f"[Error] ID: {id_} Exception: {e}")
        return JSONResponse(content={"error": str(e)}, status_code=500)
Pan Zezhong's avatar
Pan Zezhong committed
223
224
225
    finally:
        if infer_task.finish_reason is None:
            infer_task.finish_reason = "cancel"
Pan Zezhong's avatar
Pan Zezhong committed
226
227


Pan Zezhong's avatar
Pan Zezhong committed
228
@App.post("/chat/completions")
Pan Zezhong's avatar
Pan Zezhong committed
229
230
231
232
233
234
235
236
237
238
239
240
241
async def chat_completions(request: Request):
    data = await request.json()

    if not data.get("messages"):
        return JSONResponse(content={"error": "No message provided"}, status_code=400)

    stream = data.get("stream", False)
    id_ = f"cmpl-{uuid.uuid4().hex}"
    if stream:
        return StreamingResponse(
            chat_stream(id_, data, request), media_type="text/event-stream"
        )
    else:
Pan Zezhong's avatar
Pan Zezhong committed
242
        return JSONResponse(chat(id_, data))
Pan Zezhong's avatar
Pan Zezhong committed
243
244
245


if __name__ == "__main__":
Pan Zezhong's avatar
Pan Zezhong committed
246
    uvicorn.run(App, host="0.0.0.0", port=8000)
Pan Zezhong's avatar
Pan Zezhong committed
247
248
249

"""
curl -N -H "Content-Type: application/json" \
Pan Zezhong's avatar
Pan Zezhong committed
250
     -X POST http://127.0.0.1:8000/chat/completions \
Pan Zezhong's avatar
Pan Zezhong committed
251
252
253
254
255
256
257
258
259
260
261
262
     -d '{
       "model": "jiuge",
       "messages": [
         {"role": "user", "content": "山东最高的山是?"}
       ],
       "temperature": 1.0,
       "top_k": 50,
       "top_p": 0.8,
       "max_tokens": 512,
       "stream": true
     }'
"""