File size: 11,856 Bytes
6268841
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# Query VLM with Offline Engine\n",
    "\n",
    "This tutorial demonstrates how to use SGLang's **offline Engine API** to query VLMs. We will demonstrate usage with Qwen2.5-VL and Llama 4. This section demonstrates three different calling approaches:\n",
    "\n",
    "1. **Basic Call**: Directly pass images and text.\n",
    "2. **Processor Output**: Use HuggingFace processor for data preprocessing.\n",
    "3. **Precomputed Embeddings**: Pre-calculate image features to improve inference efficiency."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1",
   "metadata": {},
   "source": [
    "## Understanding the Three Input Formats\n",
    "\n",
    "SGLang supports three ways to pass visual data, each optimized for different scenarios:\n",
    "\n",
    "### 1. **Raw Images** - Simplest approach\n",
    "- Pass PIL Images, file paths, URLs, or base64 strings directly\n",
    "- SGLang handles all preprocessing automatically\n",
    "- Best for: Quick prototyping, simple applications\n",
    "\n",
    "### 2. **Processor Output** - For custom preprocessing\n",
    "- Pre-process images with HuggingFace processor\n",
    "- Pass the complete processor output dict with `format: \"processor_output\"`\n",
    "- Best for: Custom image transformations, integration with existing pipelines\n",
    "- Requirement: Must use `input_ids` instead of text prompt\n",
    "\n",
    "### 3. **Precomputed Embeddings** - For maximum performance\n",
    "- Pre-calculate visual embeddings using the vision encoder\n",
    "- Pass embeddings with `format: \"precomputed_embedding\"`\n",
    "- Best for: Repeated queries on same images, caching, high-throughput serving\n",
    "- Performance gain: Avoids redundant vision encoder computation (30-50% speedup)\n",
    "\n",
    "**Key Rule**: Within a single request, use only one format for all images. Don't mix formats.\n",
    "\n",
    "The examples below demonstrate all three approaches with both Qwen2.5-VL and Llama 4 models."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2",
   "metadata": {},
   "source": [
    "## Querying Qwen2.5-VL Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import nest_asyncio\n",
    "\n",
    "nest_asyncio.apply()\n",
    "\n",
    "model_path = \"Qwen/Qwen2.5-VL-3B-Instruct\"\n",
    "chat_template = \"qwen2-vl\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4",
   "metadata": {},
   "outputs": [],
   "source": [
    "from io import BytesIO\n",
    "import requests\n",
    "from PIL import Image\n",
    "\n",
    "from sglang.srt.parser.conversation import chat_templates\n",
    "\n",
    "image = Image.open(\n",
    "    BytesIO(\n",
    "        requests.get(\n",
    "            \"https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true\"\n",
    "        ).content\n",
    "    )\n",
    ")\n",
    "\n",
    "conv = chat_templates[chat_template].copy()\n",
    "conv.append_message(conv.roles[0], f\"What's shown here: {conv.image_token}?\")\n",
    "conv.append_message(conv.roles[1], \"\")\n",
    "conv.image_data = [image]\n",
    "\n",
    "print(\"Generated prompt text:\")\n",
    "print(conv.get_prompt())\n",
    "print(f\"\\nImage size: {image.size}\")\n",
    "image"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5",
   "metadata": {},
   "source": [
    "### Basic Offline Engine API Call"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sglang import Engine\n",
    "\n",
    "llm = Engine(model_path=model_path, chat_template=chat_template, log_level=\"warning\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7",
   "metadata": {},
   "outputs": [],
   "source": [
    "out = llm.generate(prompt=conv.get_prompt(), image_data=[image])\n",
    "print(\"Model response:\")\n",
    "print(out[\"text\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {},
   "source": [
    "### Call with Processor Output\n",
    "\n",
    "Using a HuggingFace processor to preprocess text and images, and passing the `processor_output` directly into `Engine.generate`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoProcessor\n",
    "\n",
    "processor = AutoProcessor.from_pretrained(model_path, use_fast=True)\n",
    "processor_output = processor(\n",
    "    images=[image], text=conv.get_prompt(), return_tensors=\"pt\"\n",
    ")\n",
    "\n",
    "out = llm.generate(\n",
    "    input_ids=processor_output[\"input_ids\"][0].detach().cpu().tolist(),\n",
    "    image_data=[dict(processor_output, format=\"processor_output\")],\n",
    ")\n",
    "print(\"Response using processor output:\")\n",
    "print(out[\"text\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10",
   "metadata": {},
   "source": [
    "### Call with Precomputed Embeddings\n",
    "\n",
    "You can pre-calculate image features to avoid repeated visual encoding processes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoProcessor\n",
    "from transformers import Qwen2_5_VLForConditionalGeneration\n",
    "\n",
    "processor = AutoProcessor.from_pretrained(model_path, use_fast=True)\n",
    "vision = (\n",
    "    Qwen2_5_VLForConditionalGeneration.from_pretrained(model_path).eval().visual.cuda()\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12",
   "metadata": {},
   "outputs": [],
   "source": [
    "processor_output = processor(\n",
    "    images=[image], text=conv.get_prompt(), return_tensors=\"pt\"\n",
    ")\n",
    "\n",
    "input_ids = processor_output[\"input_ids\"][0].detach().cpu().tolist()\n",
    "\n",
    "precomputed_embeddings = vision(\n",
    "    processor_output[\"pixel_values\"].cuda(), processor_output[\"image_grid_thw\"].cuda()\n",
    ")\n",
    "\n",
    "multi_modal_item = dict(\n",
    "    processor_output,\n",
    "    format=\"precomputed_embedding\",\n",
    "    feature=precomputed_embeddings,\n",
    ")\n",
    "\n",
    "out = llm.generate(input_ids=input_ids, image_data=[multi_modal_item])\n",
    "print(\"Response using precomputed embeddings:\")\n",
    "print(out[\"text\"])\n",
    "\n",
    "llm.shutdown()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13",
   "metadata": {},
   "source": [
    "## Querying Llama 4 Vision Model\n",
    "\n",
    "```python\n",
    "model_path = \"meta-llama/Llama-4-Scout-17B-16E-Instruct\"\n",
    "chat_template = \"llama-4\"\n",
    "\n",
    "from io import BytesIO\n",
    "import requests\n",
    "from PIL import Image\n",
    "\n",
    "from sglang.srt.parser.conversation import chat_templates\n",
    "\n",
    "# Download the same example image\n",
    "image = Image.open(\n",
    "    BytesIO(\n",
    "        requests.get(\n",
    "            \"https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true\"\n",
    "        ).content\n",
    "    )\n",
    ")\n",
    "\n",
    "conv = chat_templates[chat_template].copy()\n",
    "conv.append_message(conv.roles[0], f\"What's shown here: {conv.image_token}?\")\n",
    "conv.append_message(conv.roles[1], \"\")\n",
    "conv.image_data = [image]\n",
    "\n",
    "print(\"Llama 4 generated prompt text:\")\n",
    "print(conv.get_prompt())\n",
    "print(f\"Image size: {image.size}\")\n",
    "\n",
    "image\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14",
   "metadata": {},
   "source": [
    "### Llama 4 Basic Call\n",
    "\n",
    "Llama 4 requires more computational resources, so it's configured with multi-GPU parallelism (tp_size=4) and larger context length.\n",
    "\n",
    "```python\n",
    "llm = Engine(\n",
    "    model_path=model_path,\n",
    "    enable_multimodal=True,\n",
    "    attention_backend=\"fa3\",\n",
    "    tp_size=4,\n",
    "    context_length=65536,\n",
    ")\n",
    "\n",
    "out = llm.generate(prompt=conv.get_prompt(), image_data=[image])\n",
    "print(\"Llama 4 response:\")\n",
    "print(out[\"text\"])\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15",
   "metadata": {},
   "source": [
    "### Call with Processor Output\n",
    "\n",
    "Using HuggingFace processor to preprocess data can reduce computational overhead during inference.\n",
    "\n",
    "```python\n",
    "from transformers import AutoProcessor\n",
    "\n",
    "processor = AutoProcessor.from_pretrained(model_path, use_fast=True)\n",
    "processor_output = processor(\n",
    "    images=[image], text=conv.get_prompt(), return_tensors=\"pt\"\n",
    ")\n",
    "\n",
    "out = llm.generate(\n",
    "    input_ids=processor_output[\"input_ids\"][0].detach().cpu().tolist(),\n",
    "    image_data=[dict(processor_output, format=\"processor_output\")],\n",
    ")\n",
    "print(\"Response using processor output:\")\n",
    "print(out)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16",
   "metadata": {},
   "source": [
    "### Call with Precomputed Embeddings\n",
    "\n",
    "```python\n",
    "from transformers import AutoProcessor\n",
    "from transformers import Llama4ForConditionalGeneration\n",
    "\n",
    "processor = AutoProcessor.from_pretrained(model_path, use_fast=True)\n",
    "model = Llama4ForConditionalGeneration.from_pretrained(\n",
    "    model_path, torch_dtype=\"auto\"\n",
    ").eval()\n",
    "\n",
    "vision = model.vision_model.cuda()\n",
    "multi_modal_projector = model.multi_modal_projector.cuda()\n",
    "\n",
    "print(f'Image pixel values shape: {processor_output[\"pixel_values\"].shape}')\n",
    "input_ids = processor_output[\"input_ids\"][0].detach().cpu().tolist()\n",
    "\n",
    "# Process image through vision encoder\n",
    "image_outputs = vision(\n",
    "    processor_output[\"pixel_values\"].to(\"cuda\"), \n",
    "    aspect_ratio_ids=processor_output[\"aspect_ratio_ids\"].to(\"cuda\"),\n",
    "    aspect_ratio_mask=processor_output[\"aspect_ratio_mask\"].to(\"cuda\"),\n",
    "    output_hidden_states=False\n",
    ")\n",
    "image_features = image_outputs.last_hidden_state\n",
    "\n",
    "# Flatten image features and pass through multimodal projector\n",
    "vision_flat = image_features.view(-1, image_features.size(-1))\n",
    "precomputed_embeddings = multi_modal_projector(vision_flat)\n",
    "\n",
    "# Build precomputed embedding data item\n",
    "mm_item = dict(\n",
    "    processor_output, \n",
    "    format=\"precomputed_embedding\", \n",
    "    feature=precomputed_embeddings\n",
    ")\n",
    "\n",
    "# Use precomputed embeddings for efficient inference\n",
    "out = llm.generate(input_ids=input_ids, image_data=[mm_item])\n",
    "print(\"Llama 4 precomputed embedding response:\")\n",
    "print(out[\"text\"])\n",
    "```"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "custom_cell_magics": "kql",
   "encoding": "# -*- coding: utf-8 -*-",
   "text_representation": {
    "extension": ".py",
    "format_name": "light",
    "format_version": "1.5",
    "jupytext_version": "1.16.1"
   }
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}