native_api.ipynb 12.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",
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",
Chayenne's avatar
Chayenne committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
    "\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,
34
   "metadata": {},
Chayenne's avatar
Chayenne committed
35
36
   "outputs": [],
   "source": [
Chayenne's avatar
Chayenne committed
37
    "import requests\n",
38
    "from sglang.test.test_utils import is_in_ci\n",
Chayenne's avatar
Chayenne committed
39
    "\n",
40
41
42
43
44
45
46
47
48
49
    "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",
    "    \"python -m sglang.launch_server --model-path meta-llama/Llama-3.2-1B-Instruct --host 0.0.0.0\"\n",
Chayenne's avatar
Chayenne committed
50
51
    ")\n",
    "\n",
52
    "wait_for_server(f\"http://localhost:{port}\")"
Chayenne's avatar
Chayenne committed
53
54
55
56
57
58
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Chayenne's avatar
Chayenne committed
59
    "## Generate (text generation model)\n",
60
    "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
61
62
63
64
65
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
66
   "metadata": {},
Chayenne's avatar
Chayenne committed
67
68
   "outputs": [],
   "source": [
69
    "url = f\"http://localhost:{port}/generate\"\n",
Chayenne's avatar
Chayenne committed
70
    "data = {\"text\": \"What is the capital of France?\"}\n",
Chayenne's avatar
Chayenne committed
71
72
    "\n",
    "response = requests.post(url, json=data)\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
73
    "print_highlight(response.json())"
Chayenne's avatar
Chayenne committed
74
75
   ]
  },
76
77
78
79
80
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
Chayenne's avatar
Chayenne committed
81
82
83
84
85
86
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Get Model Info\n",
    "\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
87
    "Get the information of the model.\n",
Chayenne's avatar
Chayenne committed
88
89
    "\n",
    "- `model_path`: The path/name of the model.\n",
Chayenne's avatar
Chayenne committed
90
91
    "- `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
92
93
94
95
96
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
97
   "metadata": {},
Chayenne's avatar
Chayenne committed
98
99
   "outputs": [],
   "source": [
100
    "url = f\"http://localhost:{port}/get_model_info\"\n",
Chayenne's avatar
Chayenne committed
101
102
103
104
105
    "\n",
    "response = requests.get(url)\n",
    "response_json = response.json()\n",
    "print_highlight(response_json)\n",
    "assert response_json[\"model_path\"] == \"meta-llama/Llama-3.2-1B-Instruct\"\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
106
    "assert response_json[\"is_generation\"] is True\n",
Chayenne's avatar
Chayenne committed
107
108
    "assert response_json[\"tokenizer_path\"] == \"meta-llama/Llama-3.2-1B-Instruct\"\n",
    "assert response_json.keys() == {\"model_path\", \"is_generation\", \"tokenizer_path\"}"
Chayenne's avatar
Chayenne committed
109
110
111
112
113
114
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
115
116
117
118
119
120
    "## 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
121
122
123
124
125
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
126
   "metadata": {},
Chayenne's avatar
Chayenne committed
127
128
   "outputs": [],
   "source": [
129
    "# get_server_info\n",
Chayenne's avatar
Chayenne committed
130
    "\n",
131
    "url = f\"http://localhost:{port}/get_server_info\"\n",
Chayenne's avatar
Chayenne committed
132
133
134
135
136
137
138
139
140
    "\n",
    "response = requests.get(url)\n",
    "print_highlight(response.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
141
142
143
    "## 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
144
145
146
147
148
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
149
   "metadata": {},
Chayenne's avatar
Chayenne committed
150
151
   "outputs": [],
   "source": [
152
    "url = f\"http://localhost:{port}/health_generate\"\n",
Chayenne's avatar
Chayenne committed
153
    "\n",
154
    "response = requests.get(url)\n",
Chayenne's avatar
Chayenne committed
155
156
157
158
159
160
    "print_highlight(response.text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
161
   "metadata": {},
Chayenne's avatar
Chayenne committed
162
163
   "outputs": [],
   "source": [
164
    "url = f\"http://localhost:{port}/health\"\n",
Chayenne's avatar
Chayenne committed
165
166
167
168
169
    "\n",
    "response = requests.get(url)\n",
    "print_highlight(response.text)"
   ]
  },
170
171
172
173
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
174
    "## Flush Cache\n",
175
    "\n",
176
    "Flush the radix cache. It will be automatically triggered when the model weights are updated by the `/update_weights` API."
177
178
179
180
181
182
183
184
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
185
    "# flush cache\n",
186
    "\n",
187
    "url = f\"http://localhost:{port}/flush_cache\"\n",
188
    "\n",
189
    "response = requests.post(url)\n",
190
191
192
    "print_highlight(response.text)"
   ]
  },
Chayenne's avatar
Chayenne committed
193
194
195
196
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Chayenne's avatar
Chayenne committed
197
    "## Update Weights From Disk\n",
Chayenne's avatar
Chayenne committed
198
    "\n",
Chayenne's avatar
Chayenne committed
199
200
201
    "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
202
203
204
205
206
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
207
   "metadata": {},
Chayenne's avatar
Chayenne committed
208
209
210
211
   "outputs": [],
   "source": [
    "# successful update with same architecture and size\n",
    "\n",
212
    "url = f\"http://localhost:{port}/update_weights_from_disk\"\n",
Chayenne's avatar
Chayenne committed
213
214
215
216
    "data = {\"model_path\": \"meta-llama/Llama-3.2-1B\"}\n",
    "\n",
    "response = requests.post(url, json=data)\n",
    "print_highlight(response.text)\n",
217
    "assert response.json()[\"success\"] is True\n",
218
    "assert response.json()[\"message\"] == \"Succeeded to update model weights.\""
Chayenne's avatar
Chayenne committed
219
220
221
222
223
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
224
   "metadata": {},
Chayenne's avatar
Chayenne committed
225
226
   "outputs": [],
   "source": [
227
    "# failed update with different parameter size or wrong name\n",
Chayenne's avatar
Chayenne committed
228
    "\n",
229
    "url = f\"http://localhost:{port}/update_weights_from_disk\"\n",
230
    "data = {\"model_path\": \"meta-llama/Llama-3.2-1B-wrong\"}\n",
Chayenne's avatar
Chayenne committed
231
232
233
234
    "\n",
    "response = requests.post(url, json=data)\n",
    "response_json = response.json()\n",
    "print_highlight(response_json)\n",
235
    "assert response_json[\"success\"] is False\n",
Chayenne's avatar
Chayenne committed
236
    "assert response_json[\"message\"] == (\n",
237
238
239
    "    \"Failed to get weights iterator: \"\n",
    "    \"meta-llama/Llama-3.2-1B-wrong\"\n",
    "    \" (repository not found).\"\n",
Chayenne's avatar
Chayenne committed
240
241
242
    ")"
   ]
  },
Chayenne's avatar
Chayenne committed
243
244
245
246
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Chayenne's avatar
Chayenne committed
247
    "## Encode (embedding model)\n",
Chayenne's avatar
Chayenne committed
248
    "\n",
Chayenne's avatar
Chayenne committed
249
250
    "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
251
252
253
254
255
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
256
   "metadata": {},
Chayenne's avatar
Chayenne committed
257
258
   "outputs": [],
   "source": [
259
    "terminate_process(server_process)\n",
Chayenne's avatar
Chayenne committed
260
    "\n",
261
    "embedding_process, port = launch_server_cmd(\n",
Chayenne's avatar
Chayenne committed
262
263
    "    \"\"\"\n",
    "python -m sglang.launch_server --model-path Alibaba-NLP/gte-Qwen2-7B-instruct \\\n",
264
    "    --host 0.0.0.0 --is-embedding\n",
Chayenne's avatar
Chayenne committed
265
266
267
    "\"\"\"\n",
    ")\n",
    "\n",
268
    "wait_for_server(f\"http://localhost:{port}\")"
Chayenne's avatar
Chayenne committed
269
270
271
272
273
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
274
   "metadata": {},
Chayenne's avatar
Chayenne committed
275
276
277
278
   "outputs": [],
   "source": [
    "# successful encode for embedding model\n",
    "\n",
279
    "url = f\"http://localhost:{port}/encode\"\n",
Chayenne's avatar
Chayenne committed
280
281
282
283
284
285
286
    "data = {\"model\": \"Alibaba-NLP/gte-Qwen2-7B-instruct\", \"text\": \"Once upon a time\"}\n",
    "\n",
    "response = requests.post(url, json=data)\n",
    "response_json = response.json()\n",
    "print_highlight(f\"Text embedding (first 10): {response_json['embedding'][:10]}\")"
   ]
  },
287
288
289
290
291
292
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
293
    "terminate_process(embedding_process)"
294
295
   ]
  },
Chayenne's avatar
Chayenne committed
296
297
298
299
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
300
    "## Classify (reward model)\n",
Chayenne's avatar
Chayenne committed
301
    "\n",
302
    "SGLang Runtime also supports reward models. Here we use a reward model to classify the quality of pairwise generations."
Chayenne's avatar
Chayenne committed
303
304
305
306
307
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
308
   "metadata": {},
Chayenne's avatar
Chayenne committed
309
310
   "outputs": [],
   "source": [
311
    "terminate_process(embedding_process)\n",
Chayenne's avatar
Chayenne committed
312
313
314
315
    "\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",
316
    "reward_process, port = launch_server_cmd(\n",
Chayenne's avatar
Chayenne committed
317
    "    \"\"\"\n",
318
    "python -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
319
320
321
    "\"\"\"\n",
    ")\n",
    "\n",
322
    "wait_for_server(f\"http://localhost:{port}\")"
Chayenne's avatar
Chayenne committed
323
324
325
326
327
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
328
   "metadata": {},
Chayenne's avatar
Chayenne committed
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
   "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",
348
    "url = f\"http://localhost:{port}/classify\"\n",
Chayenne's avatar
Chayenne committed
349
    "data = {\"model\": \"Skywork/Skywork-Reward-Llama-3.1-8B-v0.2\", \"text\": prompts}\n",
Chayenne's avatar
Chayenne committed
350
351
352
353
354
355
    "\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
356
357
  {
   "cell_type": "code",
358
359
   "execution_count": null,
   "metadata": {},
Chayenne's avatar
Chayenne committed
360
361
   "outputs": [],
   "source": [
362
    "terminate_process(reward_process)"
Chayenne's avatar
Chayenne committed
363
   ]
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Skip Tokenizer and Detokenizer\n",
    "\n",
    "SGLang Runtime also supports skip tokenizer and detokenizer. This is useful in cases like integrating with RLHF workflow."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
380
    "tokenizer_free_server_process, port = launch_server_cmd(\n",
381
    "    \"\"\"\n",
382
    "python3 -m sglang.launch_server --model-path meta-llama/Llama-3.2-1B-Instruct --skip-tokenizer-init\n",
383
384
385
    "\"\"\"\n",
    ")\n",
    "\n",
386
    "wait_for_server(f\"http://localhost:{port}\")"
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"meta-llama/Llama-3.2-1B-Instruct\")\n",
    "\n",
    "input_text = \"What is the capital of France?\"\n",
    "\n",
    "input_tokens = tokenizer.encode(input_text)\n",
    "print_highlight(f\"Input Text: {input_text}\")\n",
    "print_highlight(f\"Tokenized Input: {input_tokens}\")\n",
    "\n",
    "response = requests.post(\n",
406
    "    f\"http://localhost:{port}/generate\",\n",
407
408
409
410
411
412
413
414
415
416
417
    "    json={\n",
    "        \"input_ids\": input_tokens,\n",
    "        \"sampling_params\": {\n",
    "            \"temperature\": 0,\n",
    "            \"max_new_tokens\": 256,\n",
    "            \"stop_token_ids\": [tokenizer.eos_token_id],\n",
    "        },\n",
    "        \"stream\": False,\n",
    "    },\n",
    ")\n",
    "output = response.json()\n",
418
    "output_tokens = output[\"output_ids\"]\n",
419
420
421
422
423
424
425
426
427
428
429
430
431
    "\n",
    "output_text = tokenizer.decode(output_tokens, skip_special_tokens=False)\n",
    "print_highlight(f\"Tokenized Output: {output_tokens}\")\n",
    "print_highlight(f\"Decoded Output: {output_text}\")\n",
    "print_highlight(f\"Output Text: {output['meta_info']['finish_reason']}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
432
    "terminate_process(tokenizer_free_server_process)"
433
   ]
Chayenne's avatar
Chayenne committed
434
435
436
437
438
439
440
441
442
443
444
445
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
446
   "pygments_lexer": "ipython3"
Chayenne's avatar
Chayenne committed
447
448
449
450
451
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}