native_api.ipynb 13.3 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",
Chayenne's avatar
Chayenne committed
9
    "Apart from the OpenAI compatible APIs, the SGLang Runtime also provides its native server APIs. We introduce these 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",
19
    "- `/classify`(reward model)\n",
20
21
22
    "- `/start_expert_distribution_record`\n",
    "- `/stop_expert_distribution_record`\n",
    "- `/dump_expert_distribution_record`\n",
Chayenne's avatar
Chayenne committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
    "\n",
    "We mainly use `requests` to test these APIs in the following examples. You can also use `curl`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Launch A Server"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
37
   "metadata": {},
Chayenne's avatar
Chayenne committed
38
39
   "outputs": [],
   "source": [
Chayenne's avatar
Chayenne committed
40
    "import requests\n",
41
    "from sglang.test.test_utils import is_in_ci\n",
Chayenne's avatar
Chayenne committed
42
    "\n",
43
44
45
46
47
48
49
50
51
    "if is_in_ci():\n",
    "    from patch import launch_server_cmd\n",
    "else:\n",
    "    from sglang.utils import launch_server_cmd\n",
    "\n",
    "from sglang.utils import wait_for_server, print_highlight, terminate_process\n",
    "\n",
    "\n",
    "server_process, port = launch_server_cmd(\n",
52
    "    \"python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct --host 0.0.0.0\"\n",
Chayenne's avatar
Chayenne committed
53
54
    ")\n",
    "\n",
55
    "wait_for_server(f\"http://localhost:{port}\")"
Chayenne's avatar
Chayenne committed
56
57
58
59
60
61
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Chayenne's avatar
Chayenne committed
62
    "## Generate (text generation model)\n",
63
    "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
64
65
66
67
68
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
69
   "metadata": {},
Chayenne's avatar
Chayenne committed
70
71
   "outputs": [],
   "source": [
72
    "url = f\"http://localhost:{port}/generate\"\n",
Chayenne's avatar
Chayenne committed
73
    "data = {\"text\": \"What is the capital of France?\"}\n",
Chayenne's avatar
Chayenne committed
74
75
    "\n",
    "response = requests.post(url, json=data)\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
76
    "print_highlight(response.json())"
Chayenne's avatar
Chayenne committed
77
78
   ]
  },
79
80
81
82
83
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
Chayenne's avatar
Chayenne committed
84
85
86
87
88
89
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Get Model Info\n",
    "\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
90
    "Get the information of the model.\n",
Chayenne's avatar
Chayenne committed
91
92
    "\n",
    "- `model_path`: The path/name of the model.\n",
Chayenne's avatar
Chayenne committed
93
94
    "- `is_generation`: Whether the model is used as generation model or embedding model.\n",
    "- `tokenizer_path`: The path/name of the tokenizer."
Chayenne's avatar
Chayenne committed
95
96
97
98
99
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
100
   "metadata": {},
Chayenne's avatar
Chayenne committed
101
102
   "outputs": [],
   "source": [
103
    "url = f\"http://localhost:{port}/get_model_info\"\n",
Chayenne's avatar
Chayenne committed
104
105
106
107
    "\n",
    "response = requests.get(url)\n",
    "response_json = response.json()\n",
    "print_highlight(response_json)\n",
108
    "assert response_json[\"model_path\"] == \"qwen/qwen2.5-0.5b-instruct\"\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
109
    "assert response_json[\"is_generation\"] is True\n",
110
    "assert response_json[\"tokenizer_path\"] == \"qwen/qwen2.5-0.5b-instruct\"\n",
Chayenne's avatar
Chayenne committed
111
    "assert response_json.keys() == {\"model_path\", \"is_generation\", \"tokenizer_path\"}"
Chayenne's avatar
Chayenne committed
112
113
114
115
116
117
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
118
119
120
121
122
123
    "## 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
124
125
126
127
128
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
129
   "metadata": {},
Chayenne's avatar
Chayenne committed
130
131
   "outputs": [],
   "source": [
132
    "# get_server_info\n",
Chayenne's avatar
Chayenne committed
133
    "\n",
134
    "url = f\"http://localhost:{port}/get_server_info\"\n",
Chayenne's avatar
Chayenne committed
135
136
137
138
139
140
141
142
143
    "\n",
    "response = requests.get(url)\n",
    "print_highlight(response.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
144
145
146
    "## 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
147
148
149
150
151
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
152
   "metadata": {},
Chayenne's avatar
Chayenne committed
153
154
   "outputs": [],
   "source": [
155
    "url = f\"http://localhost:{port}/health_generate\"\n",
Chayenne's avatar
Chayenne committed
156
    "\n",
157
    "response = requests.get(url)\n",
Chayenne's avatar
Chayenne committed
158
159
160
161
162
163
    "print_highlight(response.text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
164
   "metadata": {},
Chayenne's avatar
Chayenne committed
165
166
   "outputs": [],
   "source": [
167
    "url = f\"http://localhost:{port}/health\"\n",
Chayenne's avatar
Chayenne committed
168
169
170
171
172
    "\n",
    "response = requests.get(url)\n",
    "print_highlight(response.text)"
   ]
  },
173
174
175
176
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
177
    "## Flush Cache\n",
178
    "\n",
179
    "Flush the radix cache. It will be automatically triggered when the model weights are updated by the `/update_weights` API."
180
181
182
183
184
185
186
187
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
188
    "# flush cache\n",
189
    "\n",
190
    "url = f\"http://localhost:{port}/flush_cache\"\n",
191
    "\n",
192
    "response = requests.post(url)\n",
193
194
195
    "print_highlight(response.text)"
   ]
  },
Chayenne's avatar
Chayenne committed
196
197
198
199
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Chayenne's avatar
Chayenne committed
200
    "## Update Weights From Disk\n",
Chayenne's avatar
Chayenne committed
201
    "\n",
Chayenne's avatar
Chayenne committed
202
203
204
    "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
205
206
207
208
209
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
210
   "metadata": {},
Chayenne's avatar
Chayenne committed
211
212
213
214
   "outputs": [],
   "source": [
    "# successful update with same architecture and size\n",
    "\n",
215
    "url = f\"http://localhost:{port}/update_weights_from_disk\"\n",
216
    "data = {\"model_path\": \"qwen/qwen2.5-0.5b-instruct\"}\n",
Chayenne's avatar
Chayenne committed
217
218
219
    "\n",
    "response = requests.post(url, json=data)\n",
    "print_highlight(response.text)\n",
220
    "assert response.json()[\"success\"] is True\n",
221
    "assert response.json()[\"message\"] == \"Succeeded to update model weights.\""
Chayenne's avatar
Chayenne committed
222
223
224
225
226
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
227
   "metadata": {},
Chayenne's avatar
Chayenne committed
228
229
   "outputs": [],
   "source": [
230
    "# failed update with different parameter size or wrong name\n",
Chayenne's avatar
Chayenne committed
231
    "\n",
232
    "url = f\"http://localhost:{port}/update_weights_from_disk\"\n",
233
    "data = {\"model_path\": \"qwen/qwen2.5-0.5b-instruct-wrong\"}\n",
Chayenne's avatar
Chayenne committed
234
235
236
237
    "\n",
    "response = requests.post(url, json=data)\n",
    "response_json = response.json()\n",
    "print_highlight(response_json)\n",
238
    "assert response_json[\"success\"] is False\n",
Chayenne's avatar
Chayenne committed
239
    "assert response_json[\"message\"] == (\n",
240
    "    \"Failed to get weights iterator: \"\n",
241
    "    \"qwen/qwen2.5-0.5b-instruct-wrong\"\n",
242
    "    \" (repository not found).\"\n",
Chayenne's avatar
Chayenne committed
243
244
245
    ")"
   ]
  },
246
247
248
249
250
251
252
253
254
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "terminate_process(server_process)"
   ]
  },
Chayenne's avatar
Chayenne committed
255
256
257
258
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Chayenne's avatar
Chayenne committed
259
    "## Encode (embedding model)\n",
Chayenne's avatar
Chayenne committed
260
    "\n",
Chayenne's avatar
Chayenne committed
261
262
    "Encode text into embeddings. Note that this API is only available for [embedding models](openai_api_embeddings.html#openai-apis-embedding) and will raise an error for generation models.\n",
    "Therefore, we launch a new server to server an embedding model."
Chayenne's avatar
Chayenne committed
263
264
265
266
267
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
268
   "metadata": {},
Chayenne's avatar
Chayenne committed
269
270
   "outputs": [],
   "source": [
271
    "embedding_process, port = launch_server_cmd(\n",
Chayenne's avatar
Chayenne committed
272
    "    \"\"\"\n",
273
    "python3 -m sglang.launch_server --model-path Alibaba-NLP/gte-Qwen2-1.5B-instruct \\\n",
274
    "    --host 0.0.0.0 --is-embedding\n",
Chayenne's avatar
Chayenne committed
275
276
277
    "\"\"\"\n",
    ")\n",
    "\n",
278
    "wait_for_server(f\"http://localhost:{port}\")"
Chayenne's avatar
Chayenne committed
279
280
281
282
283
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
284
   "metadata": {},
Chayenne's avatar
Chayenne committed
285
286
287
288
   "outputs": [],
   "source": [
    "# successful encode for embedding model\n",
    "\n",
289
    "url = f\"http://localhost:{port}/encode\"\n",
290
    "data = {\"model\": \"Alibaba-NLP/gte-Qwen2-1.5B-instruct\", \"text\": \"Once upon a time\"}\n",
Chayenne's avatar
Chayenne committed
291
292
293
294
295
296
    "\n",
    "response = requests.post(url, json=data)\n",
    "response_json = response.json()\n",
    "print_highlight(f\"Text embedding (first 10): {response_json['embedding'][:10]}\")"
   ]
  },
297
298
299
300
301
302
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
303
    "terminate_process(embedding_process)"
304
305
   ]
  },
Chayenne's avatar
Chayenne committed
306
307
308
309
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
310
    "## Classify (reward model)\n",
Chayenne's avatar
Chayenne committed
311
    "\n",
312
    "SGLang Runtime also supports reward models. Here we use a reward model to classify the quality of pairwise generations."
Chayenne's avatar
Chayenne committed
313
314
315
316
317
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
318
   "metadata": {},
Chayenne's avatar
Chayenne committed
319
320
   "outputs": [],
   "source": [
321
    "terminate_process(embedding_process)\n",
Chayenne's avatar
Chayenne committed
322
323
324
325
    "\n",
    "# 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",
326
    "reward_process, port = launch_server_cmd(\n",
Chayenne's avatar
Chayenne committed
327
    "    \"\"\"\n",
328
    "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
329
330
331
    "\"\"\"\n",
    ")\n",
    "\n",
332
    "wait_for_server(f\"http://localhost:{port}\")"
Chayenne's avatar
Chayenne committed
333
334
335
336
337
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
338
   "metadata": {},
Chayenne's avatar
Chayenne committed
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
   "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",
358
    "url = f\"http://localhost:{port}/classify\"\n",
Chayenne's avatar
Chayenne committed
359
    "data = {\"model\": \"Skywork/Skywork-Reward-Llama-3.1-8B-v0.2\", \"text\": prompts}\n",
Chayenne's avatar
Chayenne committed
360
361
362
363
364
365
    "\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
366
367
  {
   "cell_type": "code",
368
369
   "execution_count": null,
   "metadata": {},
Chayenne's avatar
Chayenne committed
370
371
   "outputs": [],
   "source": [
372
    "terminate_process(reward_process)"
Chayenne's avatar
Chayenne committed
373
   ]
374
  },
375
376
377
378
379
380
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Capture expert selection distribution in MoE models\n",
    "\n",
381
382
383
    "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.*"
384
385
386
387
388
389
390
391
392
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "expert_record_server_process, port = launch_server_cmd(\n",
393
    "    \"python3 -m sglang.launch_server --model-path Qwen/Qwen1.5-MoE-A2.7B --host 0.0.0.0\"\n",
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
    ")\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",
    "print_highlight(response)\n",
    "\n",
    "import glob\n",
    "\n",
    "output_file = glob.glob(\"expert_distribution_*.csv\")[0]\n",
    "with open(output_file, \"r\") as f:\n",
424
425
426
427
428
429
430
    "    print_highlight(\"\\n| Layer ID | Expert ID | Count |\")\n",
    "    print_highlight(\"|----------|-----------|--------|\")\n",
    "    next(f)\n",
    "    for i, line in enumerate(f):\n",
    "        if i < 9:\n",
    "            layer_id, expert_id, count = line.strip().split(\",\")\n",
    "            print_highlight(f\"| {layer_id:8} | {expert_id:9} | {count:6} |\")"
431
432
433
434
435
436
437
438
439
440
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "terminate_process(expert_record_server_process)"
   ]
Chayenne's avatar
Chayenne committed
441
442
443
444
445
446
447
448
449
450
451
452
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
453
   "pygments_lexer": "ipython3"
Chayenne's avatar
Chayenne committed
454
455
456
457
458
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}