native_api.ipynb 14.8 KB
Newer Older
Chayenne's avatar
Chayenne committed
1
2
3
4
5
6
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
7
    "# SGLang Native APIs\n",
Chayenne's avatar
Chayenne committed
8
    "\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
9
    "Apart from the OpenAI compatible APIs, the SGLang Runtime also provides its native server APIs. We introduce the following APIs:\n",
Chayenne's avatar
Chayenne committed
10
    "\n",
Chayenne's avatar
Chayenne committed
11
    "- `/generate` (text generation model)\n",
Chayenne's avatar
Chayenne committed
12
    "- `/get_model_info`\n",
13
    "- `/get_server_info`\n",
Chayenne's avatar
Chayenne committed
14
15
16
    "- `/health`\n",
    "- `/health_generate`\n",
    "- `/flush_cache`\n",
Chayenne's avatar
Chayenne committed
17
    "- `/update_weights`\n",
Chayenne's avatar
Chayenne committed
18
    "- `/encode`(embedding model)\n",
woodx's avatar
woodx committed
19
    "- `/v1/rerank`(cross encoder rerank model)\n",
20
    "- `/classify`(reward model)\n",
21
22
23
    "- `/start_expert_distribution_record`\n",
    "- `/stop_expert_distribution_record`\n",
    "- `/dump_expert_distribution_record`\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
24
    "- A full list of these APIs can be found at [http_server.py](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/entrypoints/http_server.py)\n",
Chayenne's avatar
Chayenne committed
25
    "\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
26
    "We mainly use `requests` to test these APIs in the following examples. You can also use `curl`.\n"
Chayenne's avatar
Chayenne committed
27
28
29
30
31
32
33
34
35
36
37
38
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Launch A Server"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
39
   "metadata": {},
Chayenne's avatar
Chayenne committed
40
41
   "outputs": [],
   "source": [
Lianmin Zheng's avatar
Lianmin Zheng committed
42
    "from sglang.test.doc_patch import launch_server_cmd\n",
43
44
45
    "from sglang.utils import wait_for_server, print_highlight, terminate_process\n",
    "\n",
    "server_process, port = launch_server_cmd(\n",
46
    "    \"python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct --host 0.0.0.0\"\n",
Chayenne's avatar
Chayenne committed
47
48
    ")\n",
    "\n",
49
    "wait_for_server(f\"http://localhost:{port}\")"
Chayenne's avatar
Chayenne committed
50
51
52
53
54
55
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Chayenne's avatar
Chayenne committed
56
    "## Generate (text generation model)\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
57
    "Generate completions. This is similar to the `/v1/completions` in OpenAI API. Detailed parameters can be found in the [sampling parameters](sampling_params.md)."
Chayenne's avatar
Chayenne committed
58
59
60
61
62
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
63
   "metadata": {},
Chayenne's avatar
Chayenne committed
64
65
   "outputs": [],
   "source": [
Lianmin Zheng's avatar
Lianmin Zheng committed
66
67
    "import requests\n",
    "\n",
68
    "url = f\"http://localhost:{port}/generate\"\n",
Chayenne's avatar
Chayenne committed
69
    "data = {\"text\": \"What is the capital of France?\"}\n",
Chayenne's avatar
Chayenne committed
70
71
    "\n",
    "response = requests.post(url, json=data)\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
72
    "print_highlight(response.json())"
Chayenne's avatar
Chayenne committed
73
74
75
76
77
78
79
80
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Get Model Info\n",
    "\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
81
    "Get the information of the model.\n",
Chayenne's avatar
Chayenne committed
82
83
    "\n",
    "- `model_path`: The path/name of the model.\n",
Chayenne's avatar
Chayenne committed
84
    "- `is_generation`: Whether the model is used as generation model or embedding model.\n",
85
86
    "- `tokenizer_path`: The path/name of the tokenizer.\n",
    "- `preferred_sampling_params`: The default sampling params specified via `--preferred-sampling-params`. `None` is returned in this example as we did not explicitly configure it in server args."
Chayenne's avatar
Chayenne committed
87
88
89
90
91
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
92
   "metadata": {},
Chayenne's avatar
Chayenne committed
93
94
   "outputs": [],
   "source": [
95
    "url = f\"http://localhost:{port}/get_model_info\"\n",
Chayenne's avatar
Chayenne committed
96
97
98
99
    "\n",
    "response = requests.get(url)\n",
    "response_json = response.json()\n",
    "print_highlight(response_json)\n",
100
    "assert response_json[\"model_path\"] == \"qwen/qwen2.5-0.5b-instruct\"\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
101
    "assert response_json[\"is_generation\"] is True\n",
102
    "assert response_json[\"tokenizer_path\"] == \"qwen/qwen2.5-0.5b-instruct\"\n",
103
    "assert response_json[\"preferred_sampling_params\"] is None\n",
104
105
106
107
108
109
    "assert response_json.keys() == {\n",
    "    \"model_path\",\n",
    "    \"is_generation\",\n",
    "    \"tokenizer_path\",\n",
    "    \"preferred_sampling_params\",\n",
    "}"
Chayenne's avatar
Chayenne committed
110
111
112
113
114
115
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
116
117
118
119
120
121
    "## Get Server Info\n",
    "Gets the server information including CLI arguments, token limits, and memory pool sizes.\n",
    "- Note: `get_server_info` merges the following deprecated endpoints:\n",
    "  - `get_server_args`\n",
    "  - `get_memory_pool_size` \n",
    "  - `get_max_total_num_tokens`"
Chayenne's avatar
Chayenne committed
122
123
124
125
126
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
127
   "metadata": {},
Chayenne's avatar
Chayenne committed
128
129
   "outputs": [],
   "source": [
130
    "url = f\"http://localhost:{port}/get_server_info\"\n",
Chayenne's avatar
Chayenne committed
131
132
133
134
135
136
137
138
139
    "\n",
    "response = requests.get(url)\n",
    "print_highlight(response.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
140
141
142
    "## Health Check\n",
    "- `/health`: Check the health of the server.\n",
    "- `/health_generate`: Check the health of the server by generating one token."
Chayenne's avatar
Chayenne committed
143
144
145
146
147
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
148
   "metadata": {},
Chayenne's avatar
Chayenne committed
149
150
   "outputs": [],
   "source": [
151
    "url = f\"http://localhost:{port}/health_generate\"\n",
Chayenne's avatar
Chayenne committed
152
    "\n",
153
    "response = requests.get(url)\n",
Chayenne's avatar
Chayenne committed
154
155
156
157
158
159
    "print_highlight(response.text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
160
   "metadata": {},
Chayenne's avatar
Chayenne committed
161
162
   "outputs": [],
   "source": [
163
    "url = f\"http://localhost:{port}/health\"\n",
Chayenne's avatar
Chayenne committed
164
165
166
167
168
    "\n",
    "response = requests.get(url)\n",
    "print_highlight(response.text)"
   ]
  },
169
170
171
172
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
173
    "## Flush Cache\n",
174
    "\n",
175
    "Flush the radix cache. It will be automatically triggered when the model weights are updated by the `/update_weights` API."
176
177
178
179
180
181
182
183
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
184
    "url = f\"http://localhost:{port}/flush_cache\"\n",
185
    "\n",
186
    "response = requests.post(url)\n",
187
188
189
    "print_highlight(response.text)"
   ]
  },
Chayenne's avatar
Chayenne committed
190
191
192
193
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Chayenne's avatar
Chayenne committed
194
    "## Update Weights From Disk\n",
Chayenne's avatar
Chayenne committed
195
    "\n",
Chayenne's avatar
Chayenne committed
196
197
198
    "Update model weights from disk without restarting the server. Only applicable for models with the same architecture and parameter size.\n",
    "\n",
    "SGLang support `update_weights_from_disk` API for continuous evaluation during training (save checkpoint to disk and update weights from disk).\n"
Chayenne's avatar
Chayenne committed
199
200
201
202
203
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
204
   "metadata": {},
Chayenne's avatar
Chayenne committed
205
206
207
208
   "outputs": [],
   "source": [
    "# successful update with same architecture and size\n",
    "\n",
209
    "url = f\"http://localhost:{port}/update_weights_from_disk\"\n",
210
    "data = {\"model_path\": \"qwen/qwen2.5-0.5b-instruct\"}\n",
Chayenne's avatar
Chayenne committed
211
212
213
    "\n",
    "response = requests.post(url, json=data)\n",
    "print_highlight(response.text)\n",
214
    "assert response.json()[\"success\"] is True\n",
215
    "assert response.json()[\"message\"] == \"Succeeded to update model weights.\""
Chayenne's avatar
Chayenne committed
216
217
218
219
220
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
221
   "metadata": {},
Chayenne's avatar
Chayenne committed
222
223
   "outputs": [],
   "source": [
224
    "# failed update with different parameter size or wrong name\n",
Chayenne's avatar
Chayenne committed
225
    "\n",
226
    "url = f\"http://localhost:{port}/update_weights_from_disk\"\n",
227
    "data = {\"model_path\": \"qwen/qwen2.5-0.5b-instruct-wrong\"}\n",
Chayenne's avatar
Chayenne committed
228
229
230
231
    "\n",
    "response = requests.post(url, json=data)\n",
    "response_json = response.json()\n",
    "print_highlight(response_json)\n",
232
    "assert response_json[\"success\"] is False\n",
Chayenne's avatar
Chayenne committed
233
    "assert response_json[\"message\"] == (\n",
234
    "    \"Failed to get weights iterator: \"\n",
235
    "    \"qwen/qwen2.5-0.5b-instruct-wrong\"\n",
236
    "    \" (repository not found).\"\n",
Chayenne's avatar
Chayenne committed
237
238
239
    ")"
   ]
  },
240
241
242
243
244
245
246
247
248
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "terminate_process(server_process)"
   ]
  },
Chayenne's avatar
Chayenne committed
249
250
251
252
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Chayenne's avatar
Chayenne committed
253
    "## Encode (embedding model)\n",
Chayenne's avatar
Chayenne committed
254
    "\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
255
    "Encode text into embeddings. Note that this API is only available for [embedding models](openai_api_embeddings.ipynb) and will raise an error for generation models.\n",
Chayenne's avatar
Chayenne committed
256
    "Therefore, we launch a new server to server an embedding model."
Chayenne's avatar
Chayenne committed
257
258
259
260
261
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
262
   "metadata": {},
Chayenne's avatar
Chayenne committed
263
264
   "outputs": [],
   "source": [
265
    "embedding_process, port = launch_server_cmd(\n",
Chayenne's avatar
Chayenne committed
266
    "    \"\"\"\n",
267
    "python3 -m sglang.launch_server --model-path Alibaba-NLP/gte-Qwen2-1.5B-instruct \\\n",
268
    "    --host 0.0.0.0 --is-embedding\n",
Chayenne's avatar
Chayenne committed
269
270
271
    "\"\"\"\n",
    ")\n",
    "\n",
272
    "wait_for_server(f\"http://localhost:{port}\")"
Chayenne's avatar
Chayenne committed
273
274
275
276
277
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
278
   "metadata": {},
Chayenne's avatar
Chayenne committed
279
280
281
282
   "outputs": [],
   "source": [
    "# successful encode for embedding model\n",
    "\n",
283
    "url = f\"http://localhost:{port}/encode\"\n",
284
    "data = {\"model\": \"Alibaba-NLP/gte-Qwen2-1.5B-instruct\", \"text\": \"Once upon a time\"}\n",
Chayenne's avatar
Chayenne committed
285
286
287
288
289
290
    "\n",
    "response = requests.post(url, json=data)\n",
    "response_json = response.json()\n",
    "print_highlight(f\"Text embedding (first 10): {response_json['embedding'][:10]}\")"
   ]
  },
291
292
293
294
295
296
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
297
    "terminate_process(embedding_process)"
298
299
   ]
  },
woodx's avatar
woodx committed
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
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## v1/rerank (cross encoder rerank model)\n",
    "Rerank a list of documents given a query using a cross-encoder model. Note that this API is only available for cross encoder model like [BAAI/bge-reranker-v2-m3](https://huggingface.co/BAAI/bge-reranker-v2-m3) with `attention-backend` `triton` and `torch_native`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "reranker_process, port = launch_server_cmd(\n",
    "    \"\"\"\n",
    "python3 -m sglang.launch_server --model-path BAAI/bge-reranker-v2-m3 \\\n",
    "    --host 0.0.0.0 --disable-radix-cache --chunked-prefill-size -1 --attention-backend triton --is-embedding\n",
    "\"\"\"\n",
    ")\n",
    "\n",
    "wait_for_server(f\"http://localhost:{port}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# compute rerank scores for query and documents\n",
    "\n",
    "url = f\"http://localhost:{port}/v1/rerank\"\n",
    "data = {\n",
    "    \"model\": \"BAAI/bge-reranker-v2-m3\",\n",
    "    \"query\": \"what is panda?\",\n",
    "    \"documents\": [\n",
    "        \"hi\",\n",
    "        \"The giant panda (Ailuropoda melanoleuca), sometimes called a panda bear or simply panda, is a bear species endemic to China.\",\n",
    "    ],\n",
    "}\n",
    "\n",
    "response = requests.post(url, json=data)\n",
    "response_json = response.json()\n",
    "for item in response_json:\n",
    "    print_highlight(f\"Score: {item['score']:.2f} - Document: '{item['document']}'\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "terminate_process(reranker_process)"
   ]
  },
Chayenne's avatar
Chayenne committed
357
358
359
360
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
361
    "## Classify (reward model)\n",
Chayenne's avatar
Chayenne committed
362
    "\n",
363
    "SGLang Runtime also supports reward models. Here we use a reward model to classify the quality of pairwise generations."
Chayenne's avatar
Chayenne committed
364
365
366
367
368
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
369
   "metadata": {},
Chayenne's avatar
Chayenne committed
370
371
372
373
374
   "outputs": [],
   "source": [
    "# Note that SGLang now treats embedding models and reward models as the same type of models.\n",
    "# This will be updated in the future.\n",
    "\n",
375
    "reward_process, port = launch_server_cmd(\n",
Chayenne's avatar
Chayenne committed
376
    "    \"\"\"\n",
377
    "python3 -m sglang.launch_server --model-path Skywork/Skywork-Reward-Llama-3.1-8B-v0.2 --host 0.0.0.0 --is-embedding\n",
Chayenne's avatar
Chayenne committed
378
379
380
    "\"\"\"\n",
    ")\n",
    "\n",
381
    "wait_for_server(f\"http://localhost:{port}\")"
Chayenne's avatar
Chayenne committed
382
383
384
385
386
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
387
   "metadata": {},
Chayenne's avatar
Chayenne committed
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer\n",
    "\n",
    "PROMPT = (\n",
    "    \"What is the range of the numeric output of a sigmoid node in a neural network?\"\n",
    ")\n",
    "\n",
    "RESPONSE1 = \"The output of a sigmoid node is bounded between -1 and 1.\"\n",
    "RESPONSE2 = \"The output of a sigmoid node is bounded between 0 and 1.\"\n",
    "\n",
    "CONVS = [\n",
    "    [{\"role\": \"user\", \"content\": PROMPT}, {\"role\": \"assistant\", \"content\": RESPONSE1}],\n",
    "    [{\"role\": \"user\", \"content\": PROMPT}, {\"role\": \"assistant\", \"content\": RESPONSE2}],\n",
    "]\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"Skywork/Skywork-Reward-Llama-3.1-8B-v0.2\")\n",
    "prompts = tokenizer.apply_chat_template(CONVS, tokenize=False)\n",
    "\n",
407
    "url = f\"http://localhost:{port}/classify\"\n",
Chayenne's avatar
Chayenne committed
408
    "data = {\"model\": \"Skywork/Skywork-Reward-Llama-3.1-8B-v0.2\", \"text\": prompts}\n",
Chayenne's avatar
Chayenne committed
409
410
411
412
413
414
    "\n",
    "responses = requests.post(url, json=data).json()\n",
    "for response in responses:\n",
    "    print_highlight(f\"reward: {response['embedding'][0]}\")"
   ]
  },
Chayenne's avatar
Chayenne committed
415
416
  {
   "cell_type": "code",
417
418
   "execution_count": null,
   "metadata": {},
Chayenne's avatar
Chayenne committed
419
420
   "outputs": [],
   "source": [
421
    "terminate_process(reward_process)"
Chayenne's avatar
Chayenne committed
422
   ]
423
  },
424
425
426
427
428
429
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Capture expert selection distribution in MoE models\n",
    "\n",
430
431
432
    "SGLang Runtime supports recording the number of times an expert is selected in a MoE model run for each expert in the model. This is useful when analyzing the throughput of the model and plan for optimization.\n",
    "\n",
    "*Note: We only print out the first 10 lines of the csv below for better readability. Please adjust accordingly if you want to analyze the results more deeply.*"
433
434
435
436
437
438
439
440
441
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "expert_record_server_process, port = launch_server_cmd(\n",
442
    "    \"python3 -m sglang.launch_server --model-path Qwen/Qwen1.5-MoE-A2.7B --host 0.0.0.0 --expert-distribution-recorder-mode stat\"\n",
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
    ")\n",
    "\n",
    "wait_for_server(f\"http://localhost:{port}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response = requests.post(f\"http://localhost:{port}/start_expert_distribution_record\")\n",
    "print_highlight(response)\n",
    "\n",
    "url = f\"http://localhost:{port}/generate\"\n",
    "data = {\"text\": \"What is the capital of France?\"}\n",
    "\n",
    "response = requests.post(url, json=data)\n",
    "print_highlight(response.json())\n",
    "\n",
    "response = requests.post(f\"http://localhost:{port}/stop_expert_distribution_record\")\n",
    "print_highlight(response)\n",
    "\n",
    "response = requests.post(f\"http://localhost:{port}/dump_expert_distribution_record\")\n",
467
    "print_highlight(response)"
468
469
470
471
472
473
474
475
476
477
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "terminate_process(expert_record_server_process)"
   ]
Chayenne's avatar
Chayenne committed
478
479
480
481
482
483
484
485
486
487
488
489
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
490
   "pygments_lexer": "ipython3"
Chayenne's avatar
Chayenne committed
491
492
493
494
495
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}