Safetensors
glm5_next

Add deployment guide and vLLM 0.33.0 patch; sync tokenizer and processor code

#1
by HuayuSha - opened
deployment_guide.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Sage-S2.1-Flash Deployment Guide
2
+
3
+ The Sage-S2.1-Flash release is a 320B-A18B multimodal MoE model stored in bfloat16 weight format (about 645 GB). The vLLM and SGLang examples below use 8× H200 GPUs. This guide provides basic serving examples for LMDeploy, vLLM and SGLang.
4
+
5
+ > NOTE: The commands below are reference configurations. Inference frameworks are under active development, so use the latest framework documentation and your local validation results when tuning production deployments.
6
+
7
+ - Pass `--trust-remote-code` to every engine. The repository's tokenizer encodes control-token spellings that appear in message content (for example `<tool_call>` or `</think>` in a user message or a tool result) as ordinary text. Without the flag, the engines silently load the stock tokenizer, which encodes them as control tokens.
8
+ - On Hopper GPUs (H100, H200), keep the default BF16 KV cache: FP8 KV cache is not supported for this model there.
9
+
10
+ ## LMDeploy
11
+
12
+ Use LMDeploy built from the main branch with `transformers>=5.17,<5.19`, and install [FlashMLA](https://github.com/deepseek-ai/FlashMLA). transformers 5.19 and later rename the layer type `deepseek_sparse_attention` to `indexed_attention`, which LMDeploy does not accept yet.
13
+
14
+ ```bash
15
+ pip install "transformers>=5.17,<5.19"
16
+ lmdeploy serve api_server \
17
+ internlm/Sage-S2.1-Flash \
18
+ --trust-remote-code \
19
+ --backend pytorch \
20
+ --tp 8 \
21
+ --reasoning-parser default \
22
+ --tool-call-parser glm47
23
+ ```
24
+
25
+ ## vLLM
26
+
27
+ Use vLLM 0.33.0 with the patch in [`vllm_patch/`](./vllm_patch/README.md). It replaces one file, `vllm/renderers/hf.py`, so that images in tool results are paired with the right results when they come back out of call order. `vllm serve` does not download this folder, so fetch it first (this downloads only the patch, not the weights):
28
+
29
+ ```bash
30
+ hf download internlm/Sage-S2.1-Flash --include "vllm_patch/*" --local-dir /path/to/Sage-S2.1-Flash
31
+ ```
32
+
33
+ Apply the patch to your vLLM installation as described in `/path/to/Sage-S2.1-Flash/vllm_patch/README.md`, then start the server. With `--trust-remote-code`, `vllm serve` downloads the weights and the repository's tokenizer and processor code:
34
+
35
+ ```bash
36
+ vllm serve internlm/Sage-S2.1-Flash \
37
+ --trust-remote-code \
38
+ --tensor-parallel-size 8 \
39
+ --enable-auto-tool-choice \
40
+ --tool-call-parser glm47 \
41
+ --reasoning-parser glm47
42
+ ```
43
+
44
+ These commands use vLLM's default Python frontend. The Rust frontend (`VLLM_USE_RUST_FRONTEND=1 --tokenizer-mode glm5_next`) does not accept image or video input yet.
45
+
46
+ ## SGLang
47
+
48
+ Use SGLang 0.5.20 or later. Pass the repository's chat template explicitly: by default SGLang installs its built-in template for this architecture, which does not go through the repository's tokenizer. `--chat-template` takes a local file:
49
+
50
+ ```bash
51
+ hf download internlm/Sage-S2.1-Flash chat_template.jinja --local-dir /path/to/Sage-S2.1-Flash
52
+ ```
53
+
54
+ Then pass the downloaded file to `--chat-template`. The server downloads the weights itself:
55
+
56
+ ```bash
57
+ python3 -m sglang.launch_server \
58
+ --model-path internlm/Sage-S2.1-Flash \
59
+ --trust-remote-code \
60
+ --chat-template /path/to/Sage-S2.1-Flash/chat_template.jinja \
61
+ --tp-size 8 \
62
+ --reasoning-parser glm45 \
63
+ --tool-call-parser glm47
64
+ ```
processing_glm5.py CHANGED
@@ -1,6 +1,6 @@
1
  # coding=utf-8
2
  # Copyright 2026 The Intern team and Shanghai AI Lab team. All rights reserved.
3
- """GLM-5.3-Flash processor whose ``apply_chat_template`` keeps control-token
4
  spellings in content literal, as ``Glm5Tokenizer.apply_chat_template`` does.
5
 
6
  ``ProcessorMixin.apply_chat_template`` renders the chat template itself and then
@@ -29,7 +29,7 @@ runs, each tool block is therefore laid out the way the template emits it: one
29
  message per result, in ``tool_calls`` order when ``can_sort`` holds. The
30
  template renders that layout byte for byte as the original, and the parent's
31
  collection order becomes the placeholder order (the rule of xtuner's
32
- ``sort_tool_messages`` / ``glm53_media_messages`` in GLM-5.3 training).
33
  """
34
  from __future__ import annotations
35
 
@@ -126,7 +126,7 @@ def _results_in_rendered_order(conversation):
126
 
127
 
128
  class Glm5Processor(Glm5NextProcessor):
129
- """Stock GLM-5.3-Flash processor with literal-safe ``apply_chat_template``."""
130
 
131
  def _rendering_template(self, chat_template):
132
  """The template the parent will render, resolved the way it resolves it."""
@@ -149,7 +149,7 @@ class Glm5Processor(Glm5NextProcessor):
149
  bound = inspect.signature(parent).bind(conversation, *args, **kwargs)
150
  template = self._rendering_template(bound.arguments.get('chat_template'))
151
  if isinstance(template, str) and 'is_list_of_outputs' in template and 'can_sort' in template:
152
- # The GLM-5.3 template's tool-block rules; a custom template renders as given.
153
  conversation = bound.arguments['conversation']
154
  if isinstance(conversation, list) and conversation and isinstance(conversation[0], list):
155
  bound.arguments['conversation'] = [_results_in_rendered_order(c) for c in conversation]
 
1
  # coding=utf-8
2
  # Copyright 2026 The Intern team and Shanghai AI Lab team. All rights reserved.
3
+ """Sage-S2.1-Flash processor whose ``apply_chat_template`` keeps control-token
4
  spellings in content literal, as ``Glm5Tokenizer.apply_chat_template`` does.
5
 
6
  ``ProcessorMixin.apply_chat_template`` renders the chat template itself and then
 
29
  message per result, in ``tool_calls`` order when ``can_sort`` holds. The
30
  template renders that layout byte for byte as the original, and the parent's
31
  collection order becomes the placeholder order (the rule of xtuner's
32
+ ``sort_tool_messages`` / ``glm53_media_messages`` in Sage-S2.1-Flash training).
33
  """
34
  from __future__ import annotations
35
 
 
126
 
127
 
128
  class Glm5Processor(Glm5NextProcessor):
129
+ """Stock Sage-S2.1-Flash processor with literal-safe ``apply_chat_template``."""
130
 
131
  def _rendering_template(self, chat_template):
132
  """The template the parent will render, resolved the way it resolves it."""
 
149
  bound = inspect.signature(parent).bind(conversation, *args, **kwargs)
150
  template = self._rendering_template(bound.arguments.get('chat_template'))
151
  if isinstance(template, str) and 'is_list_of_outputs' in template and 'can_sort' in template:
152
+ # The Sage-S2.1-Flash template's tool-block rules; a custom template renders as given.
153
  conversation = bound.arguments['conversation']
154
  if isinstance(conversation, list) and conversation and isinstance(conversation[0], list):
155
  bound.arguments['conversation'] = [_results_in_rendered_order(c) for c in conversation]
tokenization_glm5.py CHANGED
@@ -1,6 +1,6 @@
1
  # coding=utf-8
2
  # Copyright 2026 The Intern team and Shanghai AI Lab team. All rights reserved.
3
- """GLM-5.3-Flash tokenizer that keeps control-token spellings in content literal.
4
 
5
  Shipped inside the model directory and loaded through ``auto_map`` with
6
  ``trust_remote_code=True``; no inference-engine change is required. The config
@@ -107,7 +107,7 @@ def _marked_backend_of(backend: Tokenizer) -> Tokenizer:
107
 
108
 
109
  class Glm5Tokenizer(PreTrainedTokenizerFast):
110
- """Stock GLM-5.3-Flash fast tokenizer with literal-safe chat encoding."""
111
 
112
  # No ``__init__`` override: transformers 5.x rebuilds the backend from bare
113
  # vocab/merges (dropping the tokenizer.json pre-tokenizer) for subclasses
 
1
  # coding=utf-8
2
  # Copyright 2026 The Intern team and Shanghai AI Lab team. All rights reserved.
3
+ """Sage-S2.1-Flash tokenizer that keeps control-token spellings in content literal.
4
 
5
  Shipped inside the model directory and loaded through ``auto_map`` with
6
  ``trust_remote_code=True``; no inference-engine change is required. The config
 
107
 
108
 
109
  class Glm5Tokenizer(PreTrainedTokenizerFast):
110
+ """Stock Sage-S2.1-Flash fast tokenizer with literal-safe chat encoding."""
111
 
112
  # No ``__init__`` override: transformers 5.x rebuilds the backend from bare
113
  # vocab/merges (dropping the tokenizer.json pre-tokenizer) for subclasses
vllm_patch/README.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # vLLM 0.33.0 patch: tool-result image order (Sage-S2.1-Flash)
2
+
3
+ [English](README.md) | [中文](README_zh.md)
4
+
5
+ ## What it fixes
6
+
7
+ Sage-S2.1-Flash's chat template renders a block of tool results in the order of the assistant's
8
+ `tool_calls`, but vLLM collects their images in message order. When results come back out of
9
+ call order, each image is silently paired with the wrong result.
10
+
11
+ ## What the patch changes
12
+
13
+ One file, `vllm/renderers/hf.py`:
14
+
15
+ - Adds `_glm5_next_tool_media_order()`, which sorts a block of tool results into `tool_calls`
16
+ order under the template's own rule, only when the block contains images or videos.
17
+ - Calls it right before `parse_chat_messages` in `HfRenderer.render_messages` and
18
+ `render_messages_async`.
19
+ - Only `model_type == "glm5_next"` is affected. The rendered prompt text does not change.
20
+
21
+ ## Files
22
+
23
+ | File | Use |
24
+ |---|---|
25
+ | `vllm-0.33.0/vllm/renderers/hf.py` | Patched file for vLLM 0.33.0, copied over the installed one |
26
+ | `vllm-0.33.0-glm5-tool-media-order.patch` | The same change as a git diff, for review or other versions |
27
+ | `check_tool_media_order.py` | CPU check (no weights) |
28
+
29
+ ## Apply (vLLM 0.33.0)
30
+
31
+ ```bash
32
+ PATCH=<model dir>/vllm_patch
33
+ VLLM_DIR=$(python -c "import vllm, os; print(os.path.dirname(vllm.__file__))")
34
+ sha256sum $VLLM_DIR/renderers/hf.py
35
+ # must be 3c84c86b348b539fc741085327b165f4b6bf958cc6c0e19fb5dc0f54430432d2 (stock 0.33.0)
36
+ cp $VLLM_DIR/renderers/hf.py $VLLM_DIR/renderers/hf.py.bak
37
+ cp $PATCH/vllm-0.33.0/vllm/renderers/hf.py $VLLM_DIR/renderers/hf.py
38
+ sha256sum $VLLM_DIR/renderers/hf.py
39
+ # 1ce7ab5909848579e37174d6ad2af3fa48b797198376e9e7757bc26af575eda7
40
+ ```
41
+
42
+ If the first checksum differs, the file is not stock 0.33.0: do not overwrite it. To revert,
43
+ copy `hf.py.bak` back.
44
+
45
+ ## Check
46
+
47
+ ```bash
48
+ python -c "import vllm.renderers.hf as h; print(hasattr(h, '_glm5_next_tool_media_order'))" # True
49
+ python $PATCH/check_tool_media_order.py <model dir> # all OK
50
+ ```
51
+
52
+ Then start `vllm serve` as usual.
53
+
54
+ ## Other versions
55
+
56
+ The diff also applies to 0.30.0, 0.31.0, 0.32.0 and nightly 0.34.0rc1.dev397. Run it in
57
+ `site-packages`:
58
+
59
+ ```bash
60
+ git apply --check $PATCH/vllm-0.33.0-glm5-tool-media-order.patch
61
+ git apply $PATCH/vllm-0.33.0-glm5-tool-media-order.patch # or: patch -p1 -b < ...
62
+ ```
63
+
64
+ Not needed before 0.30.0 (no `glm5_next` support), nor with vLLM's Rust frontend
65
+ (`VLLM_USE_RUST_FRONTEND=1 --tokenizer-mode glm5_next`).
66
+
67
+ ## Verification
68
+
69
+ - CPU (`check_tool_media_order.py`): 7 cases on 0.30.0 to 0.33.0 and nightly. Before the patch,
70
+ the reversed cases are mispaired. After it, all 7 match the template.
71
+ - GPU (0.33.0, 4xH200): with reversed tool results, the model answered the wrong image's color
72
+ before the patch and the right one after it.
73
+
74
+ Upstream: vllm-project/vllm#67108 (draft) adds a similar, model-agnostic reordering.
vllm_patch/README_zh.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # vLLM 0.33.0 补丁:工具结果的图片顺序(Sage-S2.1-Flash)
2
+
3
+ [English](README.md) | [中文](README_zh.md)
4
+
5
+ ## 修什么
6
+
7
+ Sage-S2.1-Flash 的 chat 模板按 assistant 的 `tool_calls` 顺序渲染一段工具结果,vLLM 却按消息顺序
8
+ 收集其中的图片。结果返回顺序和调用顺序不一致时,图片会静默配给错误的结果。
9
+
10
+ ## 补丁改了什么
11
+
12
+ 只改一个文件 `vllm/renderers/hf.py`:
13
+
14
+ - 新增 `_glm5_next_tool_media_order()`:按模板自己的规则,把一段工具结果排成 `tool_calls`
15
+ 顺序;只在这段结果里有图片或视频时才排。
16
+ - 在 `HfRenderer.render_messages` 和 `render_messages_async` 里,调用 `parse_chat_messages`
17
+ 之前先调用它。
18
+ - 只对 `model_type == "glm5_next"` 生效,渲染出的 prompt 文本不变。
19
+
20
+ ## 文件
21
+
22
+ | 文件 | 用途 |
23
+ |---|---|
24
+ | `vllm-0.33.0/vllm/renderers/hf.py` | 打好补丁的 vLLM 0.33.0 文件,直接覆盖安装目录里的同名文件 |
25
+ | `vllm-0.33.0-glm5-tool-media-order.patch` | 同一改动的 git diff,供审阅或其他版本使用 |
26
+ | `check_tool_media_order.py` | CPU 检查脚本(不需要权重) |
27
+
28
+ ## 打补丁(vLLM 0.33.0)
29
+
30
+ ```bash
31
+ PATCH=<权重目录>/vllm_patch
32
+ VLLM_DIR=$(python -c "import vllm, os; print(os.path.dirname(vllm.__file__))")
33
+ sha256sum $VLLM_DIR/renderers/hf.py
34
+ # 必须是 3c84c86b348b539fc741085327b165f4b6bf958cc6c0e19fb5dc0f54430432d2(官方 0.33.0)
35
+ cp $VLLM_DIR/renderers/hf.py $VLLM_DIR/renderers/hf.py.bak
36
+ cp $PATCH/vllm-0.33.0/vllm/renderers/hf.py $VLLM_DIR/renderers/hf.py
37
+ sha256sum $VLLM_DIR/renderers/hf.py
38
+ # 1ce7ab5909848579e37174d6ad2af3fa48b797198376e9e7757bc26af575eda7
39
+ ```
40
+
41
+ 第一个 sha256 对不上,说明不是官方 0.33.0 的原文件,不要覆盖。还原时把 `hf.py.bak` 拷回去。
42
+
43
+ ## 检查
44
+
45
+ ```bash
46
+ python -c "import vllm.renderers.hf as h; print(hasattr(h, '_glm5_next_tool_media_order'))" # True
47
+ python $PATCH/check_tool_media_order.py <权重目录> # 全部 OK
48
+ ```
49
+
50
+ 之后照常启动 `vllm serve`。
51
+
52
+ ## 其他版本
53
+
54
+ 这个 diff 也能打到 0.30.0、0.31.0、0.32.0 和 nightly 0.34.0rc1.dev397 上,在 `site-packages`
55
+ 下执行:
56
+
57
+ ```bash
58
+ git apply --check $PATCH/vllm-0.33.0-glm5-tool-media-order.patch
59
+ git apply $PATCH/vllm-0.33.0-glm5-tool-media-order.patch # 或者 patch -p1 -b < ...
60
+ ```
61
+
62
+ 0.30.0 之前的版本不支持 `glm5_next` 架构,用 vLLM 的 Rust 前端
63
+ (`VLLM_USE_RUST_FRONTEND=1 --tokenizer-mode glm5_next`)时也不需要。
64
+
65
+ ## 验证
66
+
67
+ - CPU(`check_tool_media_order.py`):在 0.30.0 到 0.33.0 和 nightly 上跑 7 种情形。补丁前倒序
68
+ 情形配错,补丁后 7 种全部与模板一致。
69
+ - GPU(0.33.0,4×H200):工具结果倒序时,补丁前模型答成另一张图的颜色,补丁后答对。
70
+
71
+ 上游:vllm-project/vllm#67108(草稿)做了不区分模型的同类排序。
vllm_patch/check_tool_media_order.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2026 The Intern team and Shanghai AI Lab team. All rights reserved.
3
+ """vLLM HfRenderer.render_messages (the server's chat path) on tool results with images:
4
+ image order fed to the multimodal processor vs the template's placeholder order (CPU, no
5
+ weights; image sizes identify the order).
6
+
7
+ python vllm_patch/check_tool_media_order.py <Sage-S2.1-Flash model dir>
8
+
9
+ Run it before and after applying the patch: stock vLLM 0.33.0 prints BAD for the reversed
10
+ cases, the patched one OK for all.
11
+ """
12
+ import base64
13
+ import io
14
+ import json
15
+ import sys
16
+
17
+ from PIL import Image
18
+
19
+ import vllm
20
+ from vllm.config import ModelConfig, ParallelConfig
21
+ from vllm.multimodal import MULTIMODAL_REGISTRY
22
+ from vllm.multimodal.processing.context import TimingContext
23
+ from vllm.multimodal.processing.inputs import ProcessorInputs
24
+ from vllm.renderers.params import ChatParams
25
+ import types
26
+
27
+ from vllm.renderers.hf import HfRenderer
28
+ from vllm.tokenizers.registry import cached_tokenizer_from_config
29
+
30
+ MODEL = sys.argv[1]
31
+ SIDES = {0: 224, 1: 252, 2: 280, 3: 308}
32
+
33
+
34
+ def url(k):
35
+ buf = io.BytesIO()
36
+ Image.new('RGB', (SIDES[k], SIDES[k]), (40 * k, 0, 0)).save(buf, format='PNG')
37
+ return {'type': 'image_url', 'image_url': {'url': 'data:image/png;base64,' + base64.b64encode(buf.getvalue()).decode()}}
38
+
39
+
40
+ def calls(*ids):
41
+ return {'role': 'assistant', 'content': '', 'tool_calls': [
42
+ {'id': i, 'type': 'function', 'function': {'name': 'get_weather', 'arguments': '{"city": "x"}'}} for i in ids]}
43
+
44
+
45
+ def tool(i, *parts, key='tool_call_id'):
46
+ return {'role': 'tool', key: i, 'content': list(parts)}
47
+
48
+
49
+ TEXT = lambda t: {'type': 'text', 'text': t} # noqa: E731
50
+ TOOLS = [{'type': 'function', 'function': {'name': 'get_weather', 'parameters': {
51
+ 'type': 'object', 'properties': {'city': {'type': 'string'}}}}}]
52
+ USER = {'role': 'user', 'content': [url(0), TEXT('maps?')]}
53
+ CASES = {
54
+ 'reversed': ([USER, calls('c1', 'c2'), tool('c2', url(1), TEXT('R2')), tool('c1', url(2), TEXT('R1'))], [0, 2, 1]),
55
+ 'in_order': ([USER, calls('c1', 'c2'), tool('c1', url(1), TEXT('R1')), tool('c2', url(2), TEXT('R2'))], [0, 1, 2]),
56
+ 'three_reversed': ([USER, calls('a', 'b', 'c'), tool('c', url(3)), tool('b', url(2)), tool('a', url(1))], [0, 1, 2, 3]),
57
+ 'unknown_id_kept': ([USER, calls('c1', 'c2'), tool('c2', url(1)), tool('zz', url(2))], [0, 1, 2]),
58
+ 'duplicate_id_kept': ([USER, calls('c1', 'c2'), tool('c2', url(1)), tool('c2', url(2))], [0, 1, 2]),
59
+ 'no_tool_calls_kept': ([USER, {'role': 'assistant', 'content': 'ok'}, tool('c2', url(1)), tool('c1', url(2))], [0, 1, 2]),
60
+ 'text_only_results': ([USER, calls('c1', 'c2'), {'role': 'tool', 'tool_call_id': 'c2', 'content': 'R2'},
61
+ {'role': 'tool', 'tool_call_id': 'c1', 'content': 'R1'}], [0]),
62
+ }
63
+
64
+
65
+ def order(grids):
66
+ side = {round(s / 28) * 2: k for k, s in SIDES.items()}
67
+ return [side.get(int(g[1]), '?') for g in grids]
68
+
69
+
70
+ config = ModelConfig(model=MODEL, tokenizer=MODEL, trust_remote_code=True, max_model_len=8192)
71
+ class _Config(types.SimpleNamespace):
72
+ """VllmConfig stand-in (no device on this box): unset ``xxx_config`` fields get the default
73
+ instance of vllm.config.XxxConfig."""
74
+
75
+ def __getattr__(self, name):
76
+ import vllm.config as vc
77
+
78
+ cls = getattr(vc, ''.join(part.capitalize() for part in name.split('_')), None)
79
+ if cls is None:
80
+ raise AttributeError(name)
81
+ value = cls()
82
+ setattr(self, name, value)
83
+ return value
84
+
85
+
86
+ renderer = HfRenderer(_Config(model_config=config, renderer_num_workers=1, mm_ipc_gpu_memory_gb=0,
87
+ parallel_config=ParallelConfig()),
88
+ cached_tokenizer_from_config(config))
89
+ mm = MULTIMODAL_REGISTRY.create_processor(config)
90
+ patched = hasattr(sys.modules['vllm.renderers.hf'], '_glm5_next_tool_media_order')
91
+ print('vllm', vllm.__version__, 'patched' if patched else 'stock', type(renderer).__name__)
92
+ for name, (messages, expected) in CASES.items():
93
+ params = ChatParams(chat_template_kwargs={'tools': TOOLS, 'add_generation_prompt': True})
94
+ _, prompt = renderer.render_messages(json.loads(json.dumps(messages)), params)
95
+ items = mm.data_parser.parse_mm_data(prompt['multi_modal_data'])
96
+ out = mm.apply(ProcessorInputs(prompt=prompt['prompt_token_ids'], mm_data_items=items), TimingContext())
97
+ got = order(out['mm_kwargs'].get_data()['image_grid_thw'])
98
+ print(f"{'OK ' if got == expected else 'BAD'} {name:20s} placeholder order {expected} images fed {got}")
vllm_patch/vllm-0.33.0-glm5-tool-media-order.patch ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/vllm/renderers/hf.py b/vllm/renderers/hf.py
2
+ index fa8a1db..17f0741 100644
3
+ --- a/vllm/renderers/hf.py
4
+ +++ b/vllm/renderers/hf.py
5
+ @@ -80,6 +80,75 @@ if TYPE_CHECKING:
6
+ logger = init_logger(__name__)
7
+
8
+
9
+ +# Sage-S2.1-Flash tool-result media order (patch for vLLM 0.33.0, see
10
+ +# vllm_patch/README.md in the model directory). The Sage-S2.1-Flash chat
11
+ +# template renders a contiguous block of tool results in the preceding
12
+ +# assistant's ``tool_calls`` order when its ``can_sort`` rule holds, while
13
+ +# ``parse_chat_messages`` collects media in message order; the multimodal
14
+ +# processor pairs the i-th placeholder with the i-th item, so results returned
15
+ +# out of call order got each other's images. Sorting such a block up front makes
16
+ +# the collection order the rendered placeholder order; the template renders the
17
+ +# sorted block the same way.
18
+ +def _glm5_next_tool_media_order(
19
+ + messages: list[ChatCompletionMessageParam], model_config: ModelConfig
20
+ +) -> list[ChatCompletionMessageParam]:
21
+ + if getattr(model_config.hf_config, "model_type", None) != "glm5_next":
22
+ + return messages
23
+ +
24
+ + def id_of(obj: Any) -> str:
25
+ + # The template's id_of: tool_call_id, else id, rendered as text.
26
+ + if not isinstance(obj, dict):
27
+ + return ""
28
+ + for key in ("tool_call_id", "id"):
29
+ + if obj.get(key):
30
+ + return str(obj[key])
31
+ + return ""
32
+ +
33
+ + def has_media(message: Any) -> bool:
34
+ + content = message.get("content") if isinstance(message, dict) else None
35
+ + return isinstance(content, list) and any(
36
+ + isinstance(part, dict) and part.get("type") not in (None, "text", "tool_reference")
37
+ + for part in content
38
+ + )
39
+ +
40
+ + ordered = list(messages)
41
+ + start = 0
42
+ + while start < len(ordered):
43
+ + if not isinstance(ordered[start], dict) or ordered[start].get("role") != "tool":
44
+ + start += 1
45
+ + continue
46
+ + end = start
47
+ + while (
48
+ + end + 1 < len(ordered)
49
+ + and isinstance(ordered[end + 1], dict)
50
+ + and ordered[end + 1].get("role") == "tool"
51
+ + ):
52
+ + end += 1
53
+ + block = ordered[start : end + 1]
54
+ + previous = ordered[start - 1] if start else None
55
+ + calls = (
56
+ + previous.get("tool_calls")
57
+ + if isinstance(previous, dict) and previous.get("role") == "assistant"
58
+ + else None
59
+ + ) or []
60
+ + result_ids = [id_of(m) for m in block]
61
+ + call_ids = [id_of(c) for c in calls]
62
+ + if (
63
+ + len(block) > 1
64
+ + and any(has_media(m) for m in block)
65
+ + and call_ids
66
+ + and all(result_ids)
67
+ + and len(set(result_ids)) == len(result_ids)
68
+ + and all(call_ids)
69
+ + and len(set(call_ids)) == len(call_ids)
70
+ + and set(result_ids) <= set(call_ids)
71
+ + ):
72
+ + position = {call_id: i for i, call_id in enumerate(call_ids)}
73
+ + ordered[start : end + 1] = sorted(block, key=lambda m: position[id_of(m)])
74
+ + start = end + 1
75
+ + return ordered
76
+ +
77
+ +
78
+ # Cache of `tokenizer -> prompt_embeds placeholder token ID`. Keyed by the
79
+ # tokenizer object (not `id(tokenizer)`) so a fresh tokenizer landing at a
80
+ # recycled memory address can't pick up a stale tid. Entries evict atomically
81
+ @@ -1115,6 +1184,7 @@ class HfRenderer(BaseRenderer[HfTokenizer]):
82
+ _ensure_prompt_embeds_placeholder_token(tokenizer)
83
+ )
84
+
85
+ + messages = _glm5_next_tool_media_order(messages, model_config)
86
+ conversation, mm_data, mm_uuids = parse_chat_messages(
87
+ messages,
88
+ model_config,
89
+ @@ -1238,6 +1308,7 @@ class HfRenderer(BaseRenderer[HfTokenizer]):
90
+ _ensure_prompt_embeds_placeholder_token(tokenizer)
91
+ )
92
+
93
+ + messages = _glm5_next_tool_media_order(messages, model_config)
94
+ conversation, mm_data, mm_uuids = await parse_chat_messages_async(
95
+ messages,
96
+ model_config,
vllm_patch/vllm-0.33.0/vllm/renderers/hf.py ADDED
@@ -0,0 +1,1582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import copy
7
+ import inspect
8
+ import itertools
9
+ import weakref
10
+ from collections import defaultdict, deque
11
+ from collections.abc import Sequence
12
+ from functools import lru_cache
13
+ from typing import TYPE_CHECKING, Any, Final, Literal, cast, overload
14
+
15
+ import jinja2
16
+ import jinja2.ext
17
+ import jinja2.meta
18
+ import jinja2.nodes
19
+ import jinja2.parser
20
+ import jinja2.sandbox
21
+ import torch
22
+ from typing_extensions import override
23
+
24
+ from vllm import envs
25
+ from vllm.exceptions import ChatTemplateResolutionError, VLLMValidationError
26
+ from vllm.inputs import EmbedsPrompt
27
+ from vllm.inputs.engine import MultiModalInput
28
+ from vllm.logger import init_logger
29
+ from vllm.multimodal.hasher import MultiModalHasher
30
+ from vllm.multimodal.inputs import (
31
+ MultiModalFieldElem,
32
+ MultiModalKwargsItem,
33
+ MultiModalKwargsItems,
34
+ MultiModalSharedField,
35
+ PlaceholderRange,
36
+ )
37
+ from vllm.multimodal.processing.processor import (
38
+ PromptReplacement,
39
+ apply_token_matches,
40
+ find_mm_placeholders,
41
+ )
42
+ from vllm.renderers.chat_utils import (
43
+ PROMPT_EMBEDS_PLACEHOLDER_TOKEN,
44
+ load_chat_template,
45
+ parse_chat_messages,
46
+ parse_chat_messages_async,
47
+ )
48
+ from vllm.renderers.chat_utils.content_parser import (
49
+ PROMPT_EMBEDS_PLACEHOLDER_ID_PREFIX,
50
+ )
51
+ from vllm.tokenizers.hf import HfTokenizer, maybe_make_thread_pool
52
+ from vllm.transformers_utils.chat_templates import get_chat_template_fallback_path
53
+ from vllm.transformers_utils.processor import cached_get_processor
54
+ from vllm.utils.async_utils import make_async
55
+ from vllm.utils.func_utils import supports_kw
56
+
57
+ from .base import BaseRenderer
58
+ from .inputs.preprocess import parse_dec_only_prompt
59
+
60
+ if TYPE_CHECKING:
61
+ from collections.abc import Set
62
+
63
+ from vllm.config import ModelConfig, VllmConfig
64
+ from vllm.inputs import MultiModalDataDict, MultiModalUUIDDict, TokensPrompt
65
+ from vllm.inputs.engine import TokensInput
66
+ from vllm.multimodal.processing.processor import (
67
+ MultiModalPromptUpdates,
68
+ ResolvedPromptUpdate,
69
+ )
70
+ from vllm.renderers.chat_utils import (
71
+ ChatCompletionMessageParam,
72
+ ChatTemplateContentFormat,
73
+ ChatTemplateContentFormatOption,
74
+ ConversationMessage,
75
+ )
76
+
77
+ from .inputs import DictPrompt
78
+ from .params import ChatParams
79
+
80
+ logger = init_logger(__name__)
81
+
82
+
83
+ # Sage-S2.1-Flash tool-result media order (patch for vLLM 0.33.0, see
84
+ # vllm_patch/README.md in the model directory). The Sage-S2.1-Flash chat
85
+ # template renders a contiguous block of tool results in the preceding
86
+ # assistant's ``tool_calls`` order when its ``can_sort`` rule holds, while
87
+ # ``parse_chat_messages`` collects media in message order; the multimodal
88
+ # processor pairs the i-th placeholder with the i-th item, so results returned
89
+ # out of call order got each other's images. Sorting such a block up front makes
90
+ # the collection order the rendered placeholder order; the template renders the
91
+ # sorted block the same way.
92
+ def _glm5_next_tool_media_order(
93
+ messages: list[ChatCompletionMessageParam], model_config: ModelConfig
94
+ ) -> list[ChatCompletionMessageParam]:
95
+ if getattr(model_config.hf_config, "model_type", None) != "glm5_next":
96
+ return messages
97
+
98
+ def id_of(obj: Any) -> str:
99
+ # The template's id_of: tool_call_id, else id, rendered as text.
100
+ if not isinstance(obj, dict):
101
+ return ""
102
+ for key in ("tool_call_id", "id"):
103
+ if obj.get(key):
104
+ return str(obj[key])
105
+ return ""
106
+
107
+ def has_media(message: Any) -> bool:
108
+ content = message.get("content") if isinstance(message, dict) else None
109
+ return isinstance(content, list) and any(
110
+ isinstance(part, dict) and part.get("type") not in (None, "text", "tool_reference")
111
+ for part in content
112
+ )
113
+
114
+ ordered = list(messages)
115
+ start = 0
116
+ while start < len(ordered):
117
+ if not isinstance(ordered[start], dict) or ordered[start].get("role") != "tool":
118
+ start += 1
119
+ continue
120
+ end = start
121
+ while (
122
+ end + 1 < len(ordered)
123
+ and isinstance(ordered[end + 1], dict)
124
+ and ordered[end + 1].get("role") == "tool"
125
+ ):
126
+ end += 1
127
+ block = ordered[start : end + 1]
128
+ previous = ordered[start - 1] if start else None
129
+ calls = (
130
+ previous.get("tool_calls")
131
+ if isinstance(previous, dict) and previous.get("role") == "assistant"
132
+ else None
133
+ ) or []
134
+ result_ids = [id_of(m) for m in block]
135
+ call_ids = [id_of(c) for c in calls]
136
+ if (
137
+ len(block) > 1
138
+ and any(has_media(m) for m in block)
139
+ and call_ids
140
+ and all(result_ids)
141
+ and len(set(result_ids)) == len(result_ids)
142
+ and all(call_ids)
143
+ and len(set(call_ids)) == len(call_ids)
144
+ and set(result_ids) <= set(call_ids)
145
+ ):
146
+ position = {call_id: i for i, call_id in enumerate(call_ids)}
147
+ ordered[start : end + 1] = sorted(block, key=lambda m: position[id_of(m)])
148
+ start = end + 1
149
+ return ordered
150
+
151
+
152
+ # Cache of `tokenizer -> prompt_embeds placeholder token ID`. Keyed by the
153
+ # tokenizer object (not `id(tokenizer)`) so a fresh tokenizer landing at a
154
+ # recycled memory address can't pick up a stale tid. Entries evict atomically
155
+ # with the tokenizer's garbage-collection.
156
+ _PROMPT_EMBEDS_PLACEHOLDER_TOKEN_ID_CACHE: Final[
157
+ weakref.WeakKeyDictionary[HfTokenizer, int]
158
+ ] = weakref.WeakKeyDictionary()
159
+ _PROMPT_EMBEDS_PLACEHOLDER_TOKEN_ID_ERROR: Final[str] = (
160
+ "Expected {token!r} to tokenize to exactly 1 token, got {num_ids} ({ids!r})."
161
+ )
162
+ _PROMPT_EMBEDS_PLACEHOLDER_SPAN_MISMATCH_ERROR: Final[str] = (
163
+ "Expected {expected} prompt_embeds placeholder spans in the "
164
+ "tokenized prompt, found {actual}."
165
+ )
166
+ _MISSING_PROMPT_TOKEN_IDS_ERROR: Final[str] = (
167
+ "Expected prompt_token_ids in rendered prompt when prompt_embeds "
168
+ "are present. This indicates the chat template was invoked with "
169
+ "tokenize=False."
170
+ )
171
+ _TOKENIZE_OVERRIDE_WARNING: Final[str] = (
172
+ "Overriding `tokenize=False` to `True` because `prompt_embeds` "
173
+ "post-processing requires tokenized IDs."
174
+ )
175
+
176
+
177
+ def _filter_prompt_embeds_by_template(
178
+ conversation: list[ConversationMessage],
179
+ prompt_embeds_tensors: list[torch.Tensor],
180
+ rendered: str,
181
+ ) -> tuple[list[torch.Tensor], list[ConversationMessage]]:
182
+ """Drop embeddings whose placeholders are omitted by the chat template."""
183
+ markers = [
184
+ f"{PROMPT_EMBEDS_PLACEHOLDER_ID_PREFIX}{index}__"
185
+ for index in range(len(prompt_embeds_tensors))
186
+ ]
187
+
188
+ def normalize_placeholders(value: Any) -> Any:
189
+ if isinstance(value, str):
190
+ for marker in markers:
191
+ value = value.replace(marker, PROMPT_EMBEDS_PLACEHOLDER_TOKEN)
192
+ return value
193
+ if isinstance(value, list):
194
+ return [normalize_placeholders(item) for item in value]
195
+ if isinstance(value, dict):
196
+ return {key: normalize_placeholders(item) for key, item in value.items()}
197
+ return value
198
+
199
+ visible_markers: list[tuple[int, torch.Tensor]] = []
200
+ for marker, tensor in zip(markers, prompt_embeds_tensors, strict=True):
201
+ occurrences = rendered.count(marker)
202
+ if occurrences > 1:
203
+ raise ValueError(
204
+ f"Chat template rendered prompt_embeds placeholder {marker!r} "
205
+ f"{occurrences} times; each placeholder must appear at most once."
206
+ )
207
+ if occurrences == 1:
208
+ visible_markers.append((rendered.index(marker), tensor))
209
+ visible_tensors = [
210
+ tensor for _, tensor in sorted(visible_markers, key=lambda item: item[0])
211
+ ]
212
+ normalized_conversation = normalize_placeholders(copy.deepcopy(conversation))
213
+ return visible_tensors, normalized_conversation
214
+
215
+
216
+ def _ensure_prompt_embeds_placeholder_token(tokenizer: HfTokenizer) -> int:
217
+ """Register `PROMPT_EMBEDS_PLACEHOLDER_TOKEN` as a special token and return
218
+ its token ID."""
219
+ cached = _PROMPT_EMBEDS_PLACEHOLDER_TOKEN_ID_CACHE.get(tokenizer)
220
+ if cached is not None:
221
+ return cached
222
+
223
+ tokenizer.add_special_tokens(
224
+ {"additional_special_tokens": [PROMPT_EMBEDS_PLACEHOLDER_TOKEN]}
225
+ )
226
+
227
+ ids = tokenizer.encode(PROMPT_EMBEDS_PLACEHOLDER_TOKEN, add_special_tokens=False)
228
+ if len(ids) != 1:
229
+ raise RuntimeError(
230
+ _PROMPT_EMBEDS_PLACEHOLDER_TOKEN_ID_ERROR.format(
231
+ token=PROMPT_EMBEDS_PLACEHOLDER_TOKEN,
232
+ num_ids=len(ids),
233
+ ids=ids,
234
+ )
235
+ )
236
+
237
+ token_id = ids[0]
238
+ _PROMPT_EMBEDS_PLACEHOLDER_TOKEN_ID_CACHE[tokenizer] = token_id
239
+ return token_id
240
+
241
+
242
+ def _build_prompt_embeds_updates(
243
+ prompt_embeds_tensors: Sequence[torch.Tensor],
244
+ placeholder_token_id: int,
245
+ ) -> MultiModalPromptUpdates:
246
+ """Build `MultiModalPromptUpdates` for `prompt_embeds` expansion.
247
+
248
+ Each tensor produces a `PromptReplacement` that maps
249
+ `[placeholder_token_id]` -> `[placeholder_token_id] x N`
250
+ (where `N = tensor.shape[0]`).
251
+ """
252
+ updates: list[Sequence[ResolvedPromptUpdate]] = []
253
+ for i, tensor in enumerate(prompt_embeds_tensors):
254
+ update = PromptReplacement(
255
+ modality="prompt_embeds",
256
+ target=[placeholder_token_id],
257
+ replacement=[placeholder_token_id] * tensor.shape[0],
258
+ )
259
+ updates.append([update.resolve(item_idx=i)])
260
+ return {"prompt_embeds": updates}
261
+
262
+
263
+ def _expand_prompt_embeds_placeholders(
264
+ token_ids: list[int],
265
+ mm_prompt_updates: MultiModalPromptUpdates,
266
+ ) -> list[int]:
267
+ """Expand each 1-token `prompt_embeds` sentinel into an N-token span.
268
+
269
+ Uses `apply_token_matches`. Each single placeholder token in
270
+ `token_ids` is replaced with a consecutive span of
271
+ `tensor.shape[0]` copies, following tensors in order.
272
+ """
273
+ expanded, _ = apply_token_matches(token_ids, mm_prompt_updates)
274
+ return expanded
275
+
276
+
277
+ def _build_prompt_embeds_positions(
278
+ token_ids: list[int],
279
+ num_tensors: int,
280
+ mm_prompt_updates: MultiModalPromptUpdates,
281
+ ) -> list[tuple[int, int]]:
282
+ """Locate each prompt_embeds placeholder span in `token_ids`.
283
+
284
+ Expects `token_ids` to already contain expanded N-token spans.
285
+ Returns `[(start_idx, length), ...]` aligned with the tensors.
286
+ """
287
+ placeholders = find_mm_placeholders(token_ids, mm_prompt_updates)
288
+ features = placeholders.get("prompt_embeds", [])
289
+
290
+ if len(features) != num_tensors:
291
+ raise ValueError(
292
+ _PROMPT_EMBEDS_PLACEHOLDER_SPAN_MISMATCH_ERROR.format(
293
+ expected=num_tensors,
294
+ actual=len(features),
295
+ )
296
+ )
297
+
298
+ return [(f.start_idx, f.length) for f in features]
299
+
300
+
301
+ def _build_mixed_prompt_embeds(
302
+ token_ids: list[int],
303
+ prompt_embeds_tensors: Sequence[torch.Tensor],
304
+ positions: list[tuple[int, int]],
305
+ ) -> tuple[torch.Tensor, list[bool]]:
306
+ """Build the full-length `prompt_embeds` tensor and the `is_token_ids`
307
+ mask aligned to `token_ids`."""
308
+ total_len = len(token_ids)
309
+ hidden_size = prompt_embeds_tensors[0].shape[1]
310
+ dtype = prompt_embeds_tensors[0].dtype
311
+
312
+ full_embeds = torch.zeros(total_len, hidden_size, dtype=dtype)
313
+ is_token_ids = torch.ones(total_len, dtype=torch.bool)
314
+
315
+ for (start, length), tensor in zip(positions, prompt_embeds_tensors, strict=True):
316
+ full_embeds[start : start + length] = tensor
317
+ is_token_ids[start : start + length] = False
318
+
319
+ return full_embeds, is_token_ids.tolist()
320
+
321
+
322
+ _PROCESSOR_CHAT_TEMPLATES = dict[tuple[str, str | None, str | None, bool], str | None]()
323
+ """
324
+ Used in `_try_get_processor_chat_template` to avoid calling
325
+ `cached_get_processor` again if the processor fails to be loaded.
326
+
327
+ This is needed because `lru_cache` does not cache when an exception happens.
328
+ """
329
+
330
+
331
+ def _try_get_processor_chat_template(
332
+ tokenizer: HfTokenizer,
333
+ *,
334
+ revision: str | None,
335
+ code_revision: str | None,
336
+ trust_remote_code: bool,
337
+ ) -> str | None:
338
+ cache_key = (
339
+ tokenizer.name_or_path,
340
+ revision,
341
+ code_revision,
342
+ trust_remote_code,
343
+ )
344
+ if cache_key in _PROCESSOR_CHAT_TEMPLATES:
345
+ return _PROCESSOR_CHAT_TEMPLATES[cache_key]
346
+
347
+ from transformers import ProcessorMixin, PythonBackend, TokenizersBackend
348
+
349
+ try:
350
+ processor = cached_get_processor(
351
+ tokenizer.name_or_path,
352
+ processor_cls=(PythonBackend, TokenizersBackend, ProcessorMixin),
353
+ revision=revision,
354
+ code_revision=code_revision,
355
+ trust_remote_code=trust_remote_code,
356
+ )
357
+ if (
358
+ isinstance(processor, ProcessorMixin)
359
+ and hasattr(processor, "chat_template")
360
+ and (chat_template := processor.chat_template) is not None
361
+ ):
362
+ _PROCESSOR_CHAT_TEMPLATES[cache_key] = chat_template
363
+ return chat_template
364
+ except Exception:
365
+ logger.debug(
366
+ "Failed to load AutoProcessor chat template for %s",
367
+ tokenizer.name_or_path,
368
+ exc_info=True,
369
+ )
370
+
371
+ _PROCESSOR_CHAT_TEMPLATES[cache_key] = None
372
+ return None
373
+
374
+
375
+ def resolve_chat_template(
376
+ tokenizer: HfTokenizer,
377
+ chat_template: str | None,
378
+ tools: list[dict[str, Any]] | None,
379
+ *,
380
+ model_config: ModelConfig,
381
+ ) -> str | None:
382
+ # 1st priority: The given chat template
383
+ if chat_template is not None:
384
+ # Resolve template names (e.g. "tool_use") to actual Jinja content
385
+ # so that downstream kwargs detection can parse template variables.
386
+ return tokenizer.get_chat_template(chat_template, tools=tools)
387
+
388
+ # 2nd priority: AutoProcessor chat template, unless tool calling is enabled
389
+ if tools is None:
390
+ chat_template = _try_get_processor_chat_template(
391
+ tokenizer,
392
+ revision=model_config.tokenizer_revision,
393
+ code_revision=(
394
+ model_config.code_revision
395
+ if model_config.tokenizer == model_config.model
396
+ else None
397
+ ),
398
+ trust_remote_code=model_config.trust_remote_code,
399
+ )
400
+ if chat_template is not None:
401
+ return chat_template
402
+
403
+ # 3rd priority: AutoTokenizer chat template
404
+ try:
405
+ return tokenizer.get_chat_template(chat_template, tools=tools)
406
+ except Exception:
407
+ logger.debug(
408
+ "Failed to load AutoTokenizer chat template for %s",
409
+ tokenizer.name_or_path,
410
+ exc_info=True,
411
+ )
412
+
413
+ # 4th priority: Predefined fallbacks
414
+ path = get_chat_template_fallback_path(
415
+ model_type=model_config.hf_config.model_type,
416
+ tokenizer_name_or_path=tokenizer.name_or_path,
417
+ )
418
+ if path is not None:
419
+ logger.info_once(
420
+ "Loading chat template fallback for %s as there isn't one "
421
+ "defined on HF Hub.",
422
+ tokenizer.name_or_path,
423
+ )
424
+ chat_template = load_chat_template(path)
425
+ else:
426
+ logger.debug_once(
427
+ "There is no chat template fallback for %s", tokenizer.name_or_path
428
+ )
429
+
430
+ return chat_template
431
+
432
+
433
+ def _is_var_access(node: jinja2.nodes.Node, varname: str) -> bool:
434
+ if isinstance(node, jinja2.nodes.Name):
435
+ return node.ctx == "load" and node.name == varname
436
+
437
+ # `ns.rest` matches the dotted alias "ns.rest".
438
+ if isinstance(node, jinja2.nodes.Getattr) and "." in varname:
439
+ base, _, attr = varname.rpartition(".")
440
+ return node.attr == attr and _is_var_access(node.node, base)
441
+
442
+ return False
443
+
444
+
445
+ def _is_attr_access(node: jinja2.nodes.Node, varname: str, key: str) -> bool:
446
+ if isinstance(node, jinja2.nodes.Getitem):
447
+ return (
448
+ _is_var_access(node.node, varname)
449
+ and isinstance(node.arg, jinja2.nodes.Const)
450
+ and node.arg.value == key
451
+ )
452
+
453
+ if isinstance(node, jinja2.nodes.Getattr):
454
+ return _is_var_access(node.node, varname) and node.attr == key
455
+
456
+ return False
457
+
458
+
459
+ def _is_var_or_elems_access(
460
+ node: jinja2.nodes.Node,
461
+ varname: str,
462
+ key: str | None = None,
463
+ ) -> bool:
464
+ if isinstance(node, jinja2.nodes.Filter):
465
+ return node.node is not None and _is_var_or_elems_access(
466
+ node.node, varname, key
467
+ )
468
+ if isinstance(node, jinja2.nodes.Test):
469
+ return _is_var_or_elems_access(node.node, varname, key)
470
+
471
+ if isinstance(node, jinja2.nodes.Getitem) and isinstance(
472
+ node.arg, jinja2.nodes.Slice
473
+ ):
474
+ return _is_var_or_elems_access(node.node, varname, key)
475
+
476
+ return _is_attr_access(node, varname, key) if key else _is_var_access(node, varname)
477
+
478
+
479
+ def _attr_dotted_name(node: jinja2.nodes.Node) -> str | None:
480
+ """Render an attribute-assignment target like ``ns.rest`` as a dotted name."""
481
+ if isinstance(node, jinja2.nodes.NSRef):
482
+ return f"{node.name}.{node.attr}"
483
+ parts = []
484
+ while isinstance(node, jinja2.nodes.Getattr):
485
+ parts.append(node.attr)
486
+ node = node.node
487
+ if isinstance(node, jinja2.nodes.Name):
488
+ parts.append(node.name)
489
+ return ".".join(reversed(parts))
490
+ return None
491
+
492
+
493
+ def _iter_nodes_assign_var_or_elems(root: jinja2.nodes.Node, varname: str):
494
+ # Global variable that is implicitly defined at the root
495
+ yield root, varname
496
+
497
+ # Iterative BFS
498
+ seen = {varname}
499
+ related_varnames = deque([varname])
500
+ while related_varnames:
501
+ related_varname = related_varnames.popleft()
502
+
503
+ for assign_ast in root.find_all(jinja2.nodes.Assign):
504
+ lhs = assign_ast.target
505
+ rhs = assign_ast.node
506
+
507
+ if isinstance(lhs, jinja2.nodes.Name) and _is_var_or_elems_access(
508
+ rhs, related_varname
509
+ ):
510
+ yield assign_ast, lhs.name
511
+
512
+ # Avoid infinite looping for self-assignment
513
+ if lhs.name != related_varname and lhs.name not in seen:
514
+ seen.add(lhs.name)
515
+ related_varnames.append(lhs.name)
516
+
517
+ # Namespace aliases: `namespace(rest=messages)` or `ns.rest = messages`.
518
+ aliases: list[str] = []
519
+ if (
520
+ isinstance(lhs, jinja2.nodes.Name)
521
+ and isinstance(rhs, jinja2.nodes.Call)
522
+ and isinstance(rhs.node, jinja2.nodes.Name)
523
+ and rhs.node.name == "namespace"
524
+ ):
525
+ aliases = [
526
+ f"{lhs.name}.{kwarg.key}"
527
+ for kwarg in rhs.kwargs
528
+ if _is_var_or_elems_access(kwarg.value, related_varname)
529
+ ]
530
+ elif isinstance(
531
+ lhs, (jinja2.nodes.Getattr, jinja2.nodes.NSRef)
532
+ ) and _is_var_or_elems_access(rhs, related_varname):
533
+ dotted = _attr_dotted_name(lhs)
534
+ aliases = [dotted] if dotted is not None else []
535
+
536
+ for alias in aliases:
537
+ yield assign_ast, alias
538
+ if alias != related_varname and alias not in seen:
539
+ seen.add(alias)
540
+ related_varnames.append(alias)
541
+
542
+
543
+ # NOTE: The proper way to handle this is to build a CFG so that we can handle
544
+ # the scope in which each variable is defined, but that is too complicated
545
+ def _iter_nodes_assign_messages_item(root: jinja2.nodes.Node):
546
+ messages_varnames = [
547
+ varname for _, varname in _iter_nodes_assign_var_or_elems(root, "messages")
548
+ ]
549
+
550
+ # Search for {%- for message in messages -%} loops
551
+ for loop_ast in root.find_all(jinja2.nodes.For):
552
+ loop_iter = loop_ast.iter
553
+ loop_target = loop_ast.target
554
+
555
+ for varname in messages_varnames:
556
+ if _is_var_or_elems_access(loop_iter, varname):
557
+ assert isinstance(loop_target, jinja2.nodes.Name)
558
+ yield loop_ast, loop_target.name
559
+ break
560
+
561
+
562
+ def _iter_nodes_assign_content_item(root: jinja2.nodes.Node):
563
+ """Yield loops that iterate over message content or macro-bound content."""
564
+ message_varnames = [
565
+ varname for _, varname in _iter_nodes_assign_messages_item(root)
566
+ ]
567
+
568
+ # Track macro parameters that receive message.content as an argument.
569
+ # Some templates pass message.content through a macro parameter whose
570
+ # name is not literally "content".
571
+ macro_content_params_by_loop: dict[int, set[str]] = {}
572
+ loops_in_macros: set[int] = set()
573
+ for macro_node in root.find_all(jinja2.nodes.Macro):
574
+ macro_param_names = {arg.name for arg in macro_node.args}
575
+ macro_content_params: set[str] = set()
576
+ for call_node in root.find_all(jinja2.nodes.Call):
577
+ if (
578
+ isinstance(call_node.node, jinja2.nodes.Name)
579
+ and call_node.node.name == macro_node.name
580
+ ):
581
+ for i, arg in enumerate(call_node.args):
582
+ if i < len(macro_node.args) and any(
583
+ _is_var_or_elems_access(arg, varname, "content")
584
+ for varname in message_varnames
585
+ ):
586
+ macro_content_params.add(macro_node.args[i].name)
587
+ for kwarg in call_node.kwargs:
588
+ if (
589
+ isinstance(kwarg, jinja2.nodes.Keyword)
590
+ and kwarg.key in macro_param_names
591
+ and any(
592
+ _is_var_or_elems_access(kwarg.value, varname, "content")
593
+ for varname in message_varnames
594
+ )
595
+ ):
596
+ macro_content_params.add(kwarg.key)
597
+
598
+ for loop_ast in macro_node.find_all(jinja2.nodes.For):
599
+ loops_in_macros.add(id(loop_ast))
600
+ if macro_content_params:
601
+ macro_content_params_by_loop[id(loop_ast)] = macro_content_params
602
+
603
+ # Search for {%- for content in message['content'] -%} loops
604
+ # or {%- for item in content -%} loops
605
+ for loop_ast in root.find_all(jinja2.nodes.For):
606
+ loop_iter = loop_ast.iter
607
+ loop_target = loop_ast.target
608
+
609
+ for varname in message_varnames:
610
+ if _is_var_or_elems_access(loop_iter, varname, "content"):
611
+ assert isinstance(loop_target, jinja2.nodes.Name)
612
+ yield loop_ast, loop_target.name
613
+ break
614
+ else:
615
+ macro_content_params_for_loop = macro_content_params_by_loop.get(
616
+ id(loop_ast)
617
+ )
618
+ if (
619
+ isinstance(loop_iter, jinja2.nodes.Name)
620
+ and macro_content_params_for_loop is not None
621
+ and loop_iter.name in macro_content_params_for_loop
622
+ ):
623
+ assert isinstance(loop_target, jinja2.nodes.Name)
624
+ yield loop_ast, loop_target.name
625
+ continue
626
+
627
+ if (
628
+ id(loop_ast) not in loops_in_macros
629
+ and isinstance(loop_iter, jinja2.nodes.Name)
630
+ and loop_iter.name == "content"
631
+ ):
632
+ assert isinstance(loop_target, jinja2.nodes.Name)
633
+ yield loop_ast, loop_target.name
634
+
635
+
636
+ def _try_extract_ast(chat_template: str) -> jinja2.nodes.Template | None:
637
+ import transformers.utils.chat_template_utils as hf_chat_utils
638
+
639
+ try:
640
+ jinja_compiled = hf_chat_utils._compile_jinja_template(chat_template)
641
+ return jinja_compiled.environment.parse(chat_template)
642
+ except Exception:
643
+ logger.exception("Error when compiling Jinja template")
644
+ return None
645
+
646
+
647
+ @lru_cache(maxsize=32)
648
+ def _detect_content_format(
649
+ chat_template: str,
650
+ *,
651
+ default: ChatTemplateContentFormat,
652
+ ) -> ChatTemplateContentFormat:
653
+ jinja_ast = _try_extract_ast(chat_template)
654
+ if jinja_ast is None:
655
+ return default
656
+
657
+ try:
658
+ next(_iter_nodes_assign_content_item(jinja_ast))
659
+ except StopIteration:
660
+ return "string"
661
+ except Exception:
662
+ logger.exception("Error when parsing AST of Jinja template")
663
+ return default
664
+ else:
665
+ return "openai"
666
+
667
+
668
+ @lru_cache(maxsize=32)
669
+ def _detect_developer_role_support(chat_template: str) -> bool:
670
+ return '"developer"' in chat_template or "'developer'" in chat_template
671
+
672
+
673
+ def _convert_developer_to_system(
674
+ conversation: list[ConversationMessage],
675
+ ) -> list[ConversationMessage]:
676
+ converted: list[ConversationMessage] = []
677
+ for msg in conversation:
678
+ if msg["role"] == "developer":
679
+ new_msg = dict(msg)
680
+ new_msg["role"] = "system"
681
+ new_msg.pop("tools", None)
682
+ converted.append(new_msg) # type: ignore[arg-type]
683
+ else:
684
+ converted.append(msg)
685
+ return converted
686
+
687
+
688
+ def _consolidate_system_messages(
689
+ conversation: list[ConversationMessage],
690
+ ) -> list[ConversationMessage]:
691
+ """Merge all system messages into one at position 0.
692
+
693
+ Some chat templates (e.g. Qwen 3.6) require the system message to be the
694
+ very first message. After developer-to-system conversion, system messages
695
+ may appear at non-first positions; this merges them into a single message.
696
+ """
697
+ system_contents: list[str] = []
698
+ non_system: list[ConversationMessage] = []
699
+ needs_consolidation = False
700
+ for i, msg in enumerate(conversation):
701
+ if msg["role"] == "system":
702
+ if i > 0 or system_contents:
703
+ needs_consolidation = True
704
+ content = msg.get("content", "")
705
+ if isinstance(content, list):
706
+ parts = []
707
+ for part in content:
708
+ if isinstance(part, dict) and "text" in part:
709
+ parts.append(part["text"])
710
+ elif isinstance(part, str):
711
+ parts.append(part)
712
+ content = "\n".join(parts)
713
+ if content:
714
+ system_contents.append(content)
715
+ else:
716
+ non_system.append(msg)
717
+
718
+ if not needs_consolidation:
719
+ return conversation
720
+
721
+ merged: ConversationMessage = {
722
+ "role": "system",
723
+ "content": "\n\n".join(system_contents),
724
+ }
725
+ return [merged, *non_system]
726
+
727
+
728
+ _CONTENT_FORMATS_MAXSIZE = 32
729
+ _CONTENT_FORMATS = dict[
730
+ tuple[str | None, bool, str, str | None, str | None, bool],
731
+ "ChatTemplateContentFormat",
732
+ ]()
733
+ """
734
+ Used in `_resolve_chat_template_content_format` to avoid resolving and parsing
735
+ the chat template on every request.
736
+
737
+ `lru_cache` cannot be used because `tools` is a list and `ModelConfig` defines
738
+ `__eq__` without `__hash__`, so the key holds the fields `resolve_chat_template`
739
+ selects the template by. Only the presence of `tools` is part of it: it decides
740
+ whether the processor template is tried, and its contents never reach the AST.
741
+ """
742
+
743
+
744
+ def _resolve_chat_template_content_format(
745
+ chat_template: str | None,
746
+ tools: list[dict[str, Any]] | None,
747
+ tokenizer: HfTokenizer,
748
+ *,
749
+ model_config: ModelConfig,
750
+ ) -> ChatTemplateContentFormat:
751
+ cache_key = (
752
+ chat_template,
753
+ tools is None,
754
+ tokenizer.name_or_path,
755
+ model_config.revision,
756
+ model_config.code_revision,
757
+ model_config.trust_remote_code,
758
+ )
759
+ if (cached_format := _CONTENT_FORMATS.get(cache_key)) is not None:
760
+ return cached_format
761
+
762
+ resolved_chat_template = resolve_chat_template(
763
+ tokenizer,
764
+ chat_template=chat_template,
765
+ tools=tools,
766
+ model_config=model_config,
767
+ )
768
+
769
+ jinja_text = (
770
+ resolved_chat_template
771
+ if isinstance(resolved_chat_template, str)
772
+ else load_chat_template(chat_template, is_literal=True)
773
+ )
774
+
775
+ detected_format = (
776
+ "string"
777
+ if jinja_text is None
778
+ else _detect_content_format(jinja_text, default="string")
779
+ )
780
+
781
+ # Requests may carry their own chat template, so bound the cache.
782
+ if len(_CONTENT_FORMATS) >= _CONTENT_FORMATS_MAXSIZE:
783
+ _CONTENT_FORMATS.clear()
784
+ _CONTENT_FORMATS[cache_key] = detected_format
785
+
786
+ return detected_format
787
+
788
+
789
+ def resolve_chat_template_content_format(
790
+ chat_template: str | None,
791
+ tools: list[dict[str, Any]] | None,
792
+ given_format: ChatTemplateContentFormatOption,
793
+ tokenizer: HfTokenizer,
794
+ *,
795
+ model_config: ModelConfig,
796
+ ) -> ChatTemplateContentFormat:
797
+ detected_format = _resolve_chat_template_content_format(
798
+ chat_template,
799
+ tools,
800
+ tokenizer,
801
+ model_config=model_config,
802
+ )
803
+
804
+ if given_format == "auto":
805
+ logger.info_once(
806
+ "Detected the chat template content format to be '%s'. "
807
+ "You can set `--chat-template-content-format` to override this.",
808
+ detected_format,
809
+ )
810
+ elif given_format != detected_format:
811
+ logger.warning_once(
812
+ "You specified `--chat-template-content-format %s` "
813
+ "which is different from the detected format '%s'. "
814
+ "If our automatic detection is incorrect, please consider "
815
+ "opening a GitHub issue so that we can improve it: "
816
+ "https://github.com/vllm-project/vllm/issues/new/choose",
817
+ given_format,
818
+ detected_format,
819
+ )
820
+
821
+ return detected_format if given_format == "auto" else given_format
822
+
823
+
824
+ # adapted from https://github.com/huggingface/transformers/blob/v4.56.2/src/transformers/utils/chat_template_utils.py#L398-L412
825
+ # only preserve the parse function used to resolve chat template kwargs
826
+ class AssistantTracker(jinja2.ext.Extension):
827
+ tags = {"generation"}
828
+
829
+ def parse(self, parser: jinja2.parser.Parser) -> jinja2.nodes.Node:
830
+ lineno = next(parser.stream).lineno
831
+ body = parser.parse_statements(("name:endgeneration",), drop_needle=True)
832
+ call = self.call_method("_generation_support")
833
+ call_block = jinja2.nodes.CallBlock(call, [], [], body)
834
+ return call_block.set_lineno(lineno)
835
+
836
+
837
+ def _resolve_chat_template_kwargs(chat_template: str) -> Set[str]:
838
+ env = jinja2.sandbox.ImmutableSandboxedEnvironment(
839
+ trim_blocks=True,
840
+ lstrip_blocks=True,
841
+ extensions=[AssistantTracker, jinja2.ext.loopcontrols],
842
+ )
843
+ parsed_content = env.parse(chat_template)
844
+ template_vars = jinja2.meta.find_undeclared_variables(parsed_content)
845
+ return template_vars
846
+
847
+
848
+ _cached_resolve_chat_template_kwargs = lru_cache(_resolve_chat_template_kwargs)
849
+
850
+
851
+ @lru_cache
852
+ def _get_hf_base_chat_template_params() -> frozenset[str]:
853
+ from transformers import PythonBackend
854
+
855
+ # Get standard parameters from HuggingFace's base tokenizer class.
856
+ # This dynamically extracts parameters from PythonBackend's
857
+ # apply_chat_template method, ensuring compatibility with tokenizers
858
+ # that use **kwargs to receive standard parameters.
859
+
860
+ # Read signature from HF's base class - the single source of truth
861
+ base_sig = inspect.signature(PythonBackend.apply_chat_template)
862
+
863
+ # Exclude VAR_KEYWORD (**kwargs) and VAR_POSITIONAL (*args) placeholders
864
+ return frozenset(
865
+ p.name
866
+ for p in base_sig.parameters.values()
867
+ if p.kind
868
+ not in (inspect.Parameter.VAR_KEYWORD, inspect.Parameter.VAR_POSITIONAL)
869
+ )
870
+
871
+
872
+ def resolve_chat_template_kwargs(
873
+ tokenizer: HfTokenizer,
874
+ chat_template: str,
875
+ chat_template_kwargs: dict[str, Any],
876
+ raise_on_unexpected: bool = True,
877
+ ) -> dict[str, Any]:
878
+ # We exclude chat_template from kwargs here, because
879
+ # chat template has been already resolved at this stage
880
+ unexpected_vars = {"chat_template", "tokenize"}
881
+ if raise_on_unexpected and (
882
+ unexpected_in_kwargs := unexpected_vars & chat_template_kwargs.keys()
883
+ ):
884
+ raise ValueError(
885
+ "Found unexpected chat template kwargs from request: "
886
+ f"{unexpected_in_kwargs}"
887
+ )
888
+
889
+ fn_kw = {
890
+ k
891
+ for k in chat_template_kwargs
892
+ if supports_kw(tokenizer.apply_chat_template, k, allow_var_kwargs=False)
893
+ }
894
+ template_vars = _cached_resolve_chat_template_kwargs(chat_template)
895
+
896
+ # Allow standard HF parameters even if tokenizer uses **kwargs to receive them
897
+ hf_base_params = _get_hf_base_chat_template_params()
898
+
899
+ accept_vars = (fn_kw | template_vars | hf_base_params) - unexpected_vars
900
+ return {k: v for k, v in chat_template_kwargs.items() if k in accept_vars}
901
+
902
+
903
+ def _template_error_reason(exc: BaseException) -> str:
904
+ # Extract the most specific reason from a chat template error chain.
905
+ seen: set[int] = set()
906
+ current: BaseException | None = exc
907
+ while current is not None and id(current) not in seen:
908
+ seen.add(id(current))
909
+ if isinstance(current, jinja2.TemplateError):
910
+ return str(current)
911
+ current = current.__cause__ or current.__context__
912
+ return str(exc)
913
+
914
+
915
+ @overload
916
+ def safe_apply_chat_template(
917
+ model_config: ModelConfig,
918
+ tokenizer: HfTokenizer,
919
+ conversation: list[ConversationMessage],
920
+ *,
921
+ tools: list[dict[str, Any]] | None = ...,
922
+ chat_template: str | None = ...,
923
+ tokenize: Literal[True] = ...,
924
+ **kwargs,
925
+ ) -> list[int]: ...
926
+ @overload
927
+ def safe_apply_chat_template(
928
+ model_config: ModelConfig,
929
+ tokenizer: HfTokenizer,
930
+ conversation: list[ConversationMessage],
931
+ *,
932
+ tools: list[dict[str, Any]] | None = ...,
933
+ chat_template: str | None = ...,
934
+ tokenize: Literal[False] = ...,
935
+ **kwargs,
936
+ ) -> str: ...
937
+ def safe_apply_chat_template(
938
+ model_config: ModelConfig,
939
+ tokenizer: HfTokenizer,
940
+ conversation: list[ConversationMessage],
941
+ *,
942
+ tools: list[dict[str, Any]] | None = None,
943
+ chat_template: str | None = None,
944
+ tokenize: bool = True,
945
+ **kwargs,
946
+ ) -> str | list[int]:
947
+ chat_template = resolve_chat_template(
948
+ tokenizer,
949
+ chat_template=chat_template,
950
+ tools=tools,
951
+ model_config=model_config,
952
+ )
953
+ if chat_template is None:
954
+ raise ChatTemplateResolutionError(
955
+ "As of transformers v4.44, default chat template is no longer "
956
+ "allowed, so you must provide a chat template if the tokenizer "
957
+ "does not define one."
958
+ )
959
+ if any(
960
+ msg["role"] == "developer" for msg in conversation
961
+ ) and not _detect_developer_role_support(chat_template):
962
+ conversation = _convert_developer_to_system(conversation)
963
+ conversation = _consolidate_system_messages(conversation)
964
+ logger.info_once(
965
+ "Chat template does not support the 'developer' message role. "
966
+ "Converting developer messages to 'system' role.",
967
+ )
968
+ resolved_kwargs = resolve_chat_template_kwargs(
969
+ tokenizer=tokenizer,
970
+ chat_template=chat_template,
971
+ chat_template_kwargs=kwargs,
972
+ )
973
+
974
+ # transformers v5 changed the default of `return_dict` to True, which
975
+ # makes `apply_chat_template(tokenize=True)` return a `BatchEncoding`
976
+ # instead of `list[int]`. Force `return_dict=False` so downstream code
977
+ # that expects a flat token list (e.g. `parse_dec_only_prompt`) works
978
+ # consistently across v4 and v5.
979
+ if tokenize and "return_dict" not in resolved_kwargs:
980
+ resolved_kwargs["return_dict"] = False
981
+
982
+ try:
983
+ plain = tokenizer.apply_chat_template(
984
+ conversation=conversation, # type: ignore[arg-type]
985
+ tools=tools, # type: ignore[arg-type]
986
+ chat_template=chat_template,
987
+ tokenize=tokenize,
988
+ **resolved_kwargs,
989
+ )
990
+ except Exception as e:
991
+ # Chat templates reject invalid user input (e.g. an unsupported
992
+ # `reasoning_effort` value) by raising from within the template.
993
+ # Surface those as a 400 Bad Request carrying the template's own
994
+ # reason (which typically lists the supported values) instead of a
995
+ # 500 or any generic upstream wrapper message.
996
+ logger.warning("Chat template rejected the request: %s", e)
997
+ raise VLLMValidationError(_template_error_reason(e)) from e
998
+
999
+ return plain
1000
+
1001
+
1002
+ def rebuild_mm_uuids_from_mm_data(
1003
+ mm_uuids: MultiModalUUIDDict,
1004
+ mm_data: MultiModalDataDict,
1005
+ ) -> MultiModalUUIDDict:
1006
+ """Rebuild mm_uuids after vision_chunk processing.
1007
+
1008
+ When videos are split into chunks, the original UUIDs need to be updated
1009
+ to reflect the new UUIDs generated for each chunk.
1010
+
1011
+ Args:
1012
+ mm_uuids: Original UUIDs dictionary
1013
+ mm_data: Processed multimodal data with vision_chunk items
1014
+
1015
+ Returns:
1016
+ Updated UUIDs dictionary with chunk UUIDs
1017
+
1018
+ """
1019
+ vision_chunks = mm_data.get("vision_chunk")
1020
+ if vision_chunks is None:
1021
+ return mm_uuids
1022
+
1023
+ assert all(isinstance(item, dict) for item in vision_chunks), (
1024
+ "Expected all vision_chunk items to be dicts"
1025
+ )
1026
+ vision_chunks = cast(list[dict[str, Any]], vision_chunks)
1027
+ vision_chunk_uuids = [
1028
+ uuid_val for item in vision_chunks if (uuid_val := item.get("uuid")) is not None
1029
+ ]
1030
+
1031
+ if vision_chunk_uuids:
1032
+ mm_uuids = dict(mm_uuids)
1033
+ mm_uuids["vision_chunk"] = vision_chunk_uuids
1034
+
1035
+ return mm_uuids
1036
+
1037
+
1038
+ def build_video_prompts_from_mm_data(
1039
+ mm_data: MultiModalDataDict,
1040
+ ) -> list[str]:
1041
+ """Build video prompts from vision_chunk data.
1042
+
1043
+ Collects prompts from video chunks and groups them by video_idx.
1044
+
1045
+ Args:
1046
+ mm_data: Processed multimodal data with vision_chunk items
1047
+
1048
+ Returns:
1049
+ List of video prompts, one per video.
1050
+
1051
+ """
1052
+ vision_chunks = mm_data.get("vision_chunk")
1053
+ if vision_chunks is None:
1054
+ return []
1055
+
1056
+ # Group chunks by video_idx
1057
+ video_prompts_dict: dict[int, list[str]] = defaultdict(list)
1058
+
1059
+ for item in vision_chunks:
1060
+ # vision_chunk items are always dicts (VisionChunkImage/VisionChunkVideo)
1061
+ assert isinstance(item, dict)
1062
+ if item.get("type") == "video_chunk":
1063
+ video_idx = item.get("video_idx", 0)
1064
+ prompt = item.get("prompt", "")
1065
+ video_prompts_dict[video_idx].append(prompt)
1066
+
1067
+ # Build prompts in video order
1068
+ video_prompts = [
1069
+ "".join(video_prompts_dict[video_idx])
1070
+ for video_idx in sorted(video_prompts_dict.keys())
1071
+ ]
1072
+
1073
+ return video_prompts
1074
+
1075
+
1076
+ def replace_vision_chunk_video_placeholder(
1077
+ prompt_raw: str | list[int],
1078
+ mm_data: MultiModalDataDict,
1079
+ video_placeholder: str | None,
1080
+ ) -> str | list[int]:
1081
+ # get video placeholder, replace it with runtime video-chunk prompts
1082
+ if video_placeholder and isinstance(prompt_raw, str):
1083
+ video_prompts = build_video_prompts_from_mm_data(mm_data)
1084
+
1085
+ # replace in order
1086
+ prompt_raw_parts = prompt_raw.split(video_placeholder)
1087
+ if len(prompt_raw_parts) == len(video_prompts) + 1:
1088
+ prompt_raw = "".join(
1089
+ itertools.chain.from_iterable(zip(prompt_raw_parts, video_prompts))
1090
+ )
1091
+ prompt_raw += prompt_raw_parts[-1]
1092
+ else:
1093
+ logger.warning(
1094
+ "Number of video placeholders (%d) does not match "
1095
+ "number of videos (%d) in the request.",
1096
+ len(prompt_raw_parts) - 1,
1097
+ len(video_prompts),
1098
+ )
1099
+ return prompt_raw
1100
+
1101
+
1102
+ class HfRenderer(BaseRenderer[HfTokenizer]):
1103
+ def __init__(
1104
+ self,
1105
+ config: VllmConfig,
1106
+ tokenizer: HfTokenizer | None,
1107
+ ) -> None:
1108
+ # Ensure the og tokenizer is never modified by maybe_make_thread_pool
1109
+ tokenizer = copy.copy(tokenizer)
1110
+ if (
1111
+ # Skip for mock configs and tokenizers
1112
+ getattr(config.model_config, "enable_prompt_embeds", False)
1113
+ and isinstance(tokenizer, HfTokenizer)
1114
+ ):
1115
+ _ensure_prompt_embeds_placeholder_token(tokenizer)
1116
+ super().__init__(config, tokenizer)
1117
+
1118
+ self.use_unified_vision_chunk = getattr(
1119
+ config.model_config.hf_config, "use_unified_vision_chunk", False
1120
+ )
1121
+
1122
+ self._apply_chat_template_async = make_async(
1123
+ safe_apply_chat_template, executor=self._executor
1124
+ )
1125
+
1126
+ if self.tokenizer is not None:
1127
+ maybe_make_thread_pool(
1128
+ self.tokenizer, config.model_config.renderer_num_workers + 1
1129
+ )
1130
+
1131
+ def _replace_executor(self) -> None:
1132
+ """Replace the inner render pool after a stuck worker.
1133
+
1134
+ Called after a render timeout so that the stuck thread (which CPython
1135
+ cannot interrupt) does not permanently block all subsequent renders.
1136
+ The executor *object* is kept so ``make_async`` wrappers bound at
1137
+ init (tokenize, decode, pooling, derender) keep submitting work.
1138
+ The old inner pool is abandoned with wait=False — its thread will
1139
+ eventually finish or be reaped on process exit.
1140
+ """
1141
+ self._executor.replace_inner()
1142
+ logger.warning(
1143
+ "Chat template render timed out — executor pool replaced "
1144
+ "(%d worker(s)). The stuck thread may continue consuming "
1145
+ "CPU until the process exits.",
1146
+ self.model_config.renderer_num_workers,
1147
+ )
1148
+
1149
+ async def _render_with_timeout(self, coro):
1150
+ """Run a template-rendering coroutine with a timeout.
1151
+
1152
+ On timeout, replaces the executor so subsequent renders are not
1153
+ permanently blocked by the stuck thread.
1154
+ """
1155
+ timeout = envs.VLLM_CHAT_TEMPLATE_RENDER_TIMEOUT
1156
+ if timeout <= 0:
1157
+ return await coro
1158
+ try:
1159
+ return await asyncio.wait_for(coro, timeout=timeout)
1160
+ except TimeoutError:
1161
+ self._replace_executor()
1162
+ raise TimeoutError(
1163
+ f"Chat template rendering timed out after "
1164
+ f"{timeout}s. This may indicate a malicious or "
1165
+ f"excessively complex template. Adjust "
1166
+ f"VLLM_CHAT_TEMPLATE_RENDER_TIMEOUT to override."
1167
+ ) from None
1168
+
1169
+ def _can_produce_offsets(self) -> bool:
1170
+ # Only fast tokenizers expose offset_mapping.
1171
+ return self.tokenizer is not None and self.tokenizer.is_fast
1172
+
1173
+ def render_messages(
1174
+ self,
1175
+ messages: list[ChatCompletionMessageParam],
1176
+ params: ChatParams,
1177
+ ) -> tuple[list[ConversationMessage], DictPrompt]:
1178
+ model_config = self.model_config
1179
+ tokenizer = self.get_tokenizer()
1180
+
1181
+ prompt_embeds_placeholder_token_id: int | None = None
1182
+ if model_config.enable_prompt_embeds:
1183
+ prompt_embeds_placeholder_token_id = (
1184
+ _ensure_prompt_embeds_placeholder_token(tokenizer)
1185
+ )
1186
+
1187
+ messages = _glm5_next_tool_media_order(messages, model_config)
1188
+ conversation, mm_data, mm_uuids = parse_chat_messages(
1189
+ messages,
1190
+ model_config,
1191
+ content_format=resolve_chat_template_content_format(
1192
+ chat_template=params.chat_template,
1193
+ tools=params.chat_template_kwargs.get("tools"),
1194
+ given_format=params.chat_template_content_format,
1195
+ tokenizer=tokenizer,
1196
+ model_config=model_config,
1197
+ ),
1198
+ media_io_kwargs=params.media_io_kwargs,
1199
+ mm_processor_kwargs=params.mm_processor_kwargs,
1200
+ )
1201
+
1202
+ # prompt_embeds tensors are carried by the tracker through mm_data,
1203
+ # but they must NOT be fed to the MM processor (which would reject
1204
+ # the unknown key). Extract them here.
1205
+ prompt_embeds_tensors: list[torch.Tensor] | None = None
1206
+ if mm_data is not None and "prompt_embeds" in mm_data:
1207
+ prompt_embeds_tensors = list(
1208
+ cast(Sequence[torch.Tensor], mm_data["prompt_embeds"])
1209
+ )
1210
+ mm_data = {k: v for k, v in mm_data.items() if k != "prompt_embeds"}
1211
+ if not mm_data:
1212
+ mm_data = None
1213
+
1214
+ chat_template_kwargs = params.get_apply_chat_template_kwargs()
1215
+ if prompt_embeds_tensors:
1216
+ visibility_check_kwargs = chat_template_kwargs.copy()
1217
+ visibility_check_kwargs["tokenize"] = False
1218
+ rendered = safe_apply_chat_template(
1219
+ model_config,
1220
+ tokenizer,
1221
+ conversation,
1222
+ **visibility_check_kwargs,
1223
+ )
1224
+ assert isinstance(rendered, str)
1225
+ prompt_embeds_tensors, conversation = _filter_prompt_embeds_by_template(
1226
+ conversation,
1227
+ prompt_embeds_tensors,
1228
+ rendered,
1229
+ )
1230
+
1231
+ if prompt_embeds_tensors:
1232
+ # prompt_embeds post-processing requires prompt_token_ids.
1233
+ if chat_template_kwargs.get("tokenize") is False:
1234
+ logger.warning_once(_TOKENIZE_OVERRIDE_WARNING)
1235
+ chat_template_kwargs["tokenize"] = True
1236
+
1237
+ prompt_raw = safe_apply_chat_template(
1238
+ model_config,
1239
+ tokenizer,
1240
+ conversation,
1241
+ **chat_template_kwargs,
1242
+ )
1243
+
1244
+ # NOTE: use_unified_vision_chunk is currently specific to Kimi-K2.5
1245
+ # model which uses unified vision chunks for both images and videos.
1246
+ if (
1247
+ self.use_unified_vision_chunk
1248
+ and mm_uuids is not None
1249
+ and mm_data is not None
1250
+ ):
1251
+ mm_uuids = rebuild_mm_uuids_from_mm_data(mm_uuids, mm_data)
1252
+
1253
+ # get video placeholder, replace it with runtime video-chunk prompts
1254
+ video_placeholder = getattr(
1255
+ model_config.hf_config, "video_placeholder", None
1256
+ )
1257
+ prompt_raw = cast(
1258
+ list[int],
1259
+ replace_vision_chunk_video_placeholder(
1260
+ prompt_raw,
1261
+ mm_data,
1262
+ video_placeholder,
1263
+ ),
1264
+ )
1265
+
1266
+ prompt = parse_dec_only_prompt(prompt_raw)
1267
+
1268
+ # When `prompt_embeds` is mixed with other modality data,
1269
+ # `_process_tokens` runs `_process_multimodal` first (expanding
1270
+ # `<|AUDIO|>` / `<|IMAGE|>` placeholders) and then
1271
+ # `_apply_prompt_embeds_to_engine_input` augments the result.
1272
+ # Stash the tensors and placeholder ID for that override to consume.
1273
+ if prompt_embeds_tensors and mm_data:
1274
+ assert prompt_embeds_placeholder_token_id is not None
1275
+ cast(dict, prompt)["_prompt_embeds"] = (
1276
+ prompt_embeds_tensors,
1277
+ prompt_embeds_placeholder_token_id,
1278
+ )
1279
+ if params.mm_processor_kwargs:
1280
+ cast(dict, prompt)["mm_processor_kwargs"] = params.mm_processor_kwargs
1281
+ elif prompt_embeds_tensors:
1282
+ # Pure mode: no other MM data, mutate prompt to EmbedsPrompt shape.
1283
+ assert prompt_embeds_placeholder_token_id is not None
1284
+ self._apply_prompt_embeds_to_prompt(
1285
+ prompt,
1286
+ prompt_embeds_tensors,
1287
+ prompt_embeds_placeholder_token_id,
1288
+ )
1289
+
1290
+ if mm_data is not None:
1291
+ prompt["multi_modal_data"] = mm_data
1292
+ if mm_uuids is not None:
1293
+ prompt["multi_modal_uuids"] = mm_uuids
1294
+
1295
+ return conversation, prompt
1296
+
1297
+ async def render_messages_async(
1298
+ self,
1299
+ messages: list[ChatCompletionMessageParam],
1300
+ params: ChatParams,
1301
+ ) -> tuple[list[ConversationMessage], DictPrompt]:
1302
+ model_config = self.model_config
1303
+ tokenizer = self.get_tokenizer()
1304
+
1305
+ prompt_embeds_placeholder_token_id: int | None = None
1306
+ if model_config.enable_prompt_embeds:
1307
+ prompt_embeds_placeholder_token_id = (
1308
+ _ensure_prompt_embeds_placeholder_token(tokenizer)
1309
+ )
1310
+
1311
+ messages = _glm5_next_tool_media_order(messages, model_config)
1312
+ conversation, mm_data, mm_uuids = await parse_chat_messages_async(
1313
+ messages,
1314
+ model_config,
1315
+ content_format=resolve_chat_template_content_format(
1316
+ chat_template=params.chat_template,
1317
+ tools=params.chat_template_kwargs.get("tools"),
1318
+ given_format=params.chat_template_content_format,
1319
+ tokenizer=tokenizer,
1320
+ model_config=model_config,
1321
+ ),
1322
+ media_io_kwargs=params.media_io_kwargs,
1323
+ mm_processor_kwargs=params.mm_processor_kwargs,
1324
+ )
1325
+
1326
+ prompt_embeds_tensors: list[torch.Tensor] | None = None
1327
+ if mm_data is not None and "prompt_embeds" in mm_data:
1328
+ prompt_embeds_tensors = list(
1329
+ cast(Sequence[torch.Tensor], mm_data["prompt_embeds"])
1330
+ )
1331
+ mm_data = {k: v for k, v in mm_data.items() if k != "prompt_embeds"}
1332
+ if not mm_data:
1333
+ mm_data = None
1334
+
1335
+ chat_template_kwargs = params.get_apply_chat_template_kwargs()
1336
+ if prompt_embeds_tensors:
1337
+ visibility_check_kwargs = chat_template_kwargs.copy()
1338
+ visibility_check_kwargs["tokenize"] = False
1339
+ rendered = await self._render_with_timeout(
1340
+ self._apply_chat_template_async(
1341
+ model_config,
1342
+ tokenizer,
1343
+ conversation,
1344
+ **visibility_check_kwargs,
1345
+ )
1346
+ )
1347
+ assert isinstance(rendered, str)
1348
+ prompt_embeds_tensors, conversation = _filter_prompt_embeds_by_template(
1349
+ conversation,
1350
+ prompt_embeds_tensors,
1351
+ rendered,
1352
+ )
1353
+
1354
+ if prompt_embeds_tensors:
1355
+ # prompt_embeds post-processing requires prompt_token_ids.
1356
+ if chat_template_kwargs.get("tokenize") is False:
1357
+ logger.warning_once(_TOKENIZE_OVERRIDE_WARNING)
1358
+ chat_template_kwargs["tokenize"] = True
1359
+
1360
+ prompt_raw = await self._render_with_timeout(
1361
+ self._apply_chat_template_async(
1362
+ model_config,
1363
+ tokenizer,
1364
+ conversation,
1365
+ **chat_template_kwargs,
1366
+ )
1367
+ )
1368
+
1369
+ # NOTE: use_unified_vision_chunk is currently specific to Kimi-K2.5
1370
+ # model which uses unified vision chunks for both images and videos.
1371
+ if (
1372
+ self.use_unified_vision_chunk
1373
+ and mm_uuids is not None
1374
+ and mm_data is not None
1375
+ ):
1376
+ mm_uuids = rebuild_mm_uuids_from_mm_data(mm_uuids, mm_data)
1377
+
1378
+ # get video placeholder, replace it with runtime video-chunk prompts
1379
+ video_placeholder = getattr(
1380
+ model_config.hf_config, "video_placeholder", None
1381
+ )
1382
+ prompt_raw = cast(
1383
+ list[int],
1384
+ replace_vision_chunk_video_placeholder(
1385
+ prompt_raw,
1386
+ mm_data,
1387
+ video_placeholder,
1388
+ ),
1389
+ )
1390
+
1391
+ prompt = parse_dec_only_prompt(prompt_raw)
1392
+
1393
+ # See `render_messages` for the rationale.
1394
+ if prompt_embeds_tensors and mm_data:
1395
+ assert prompt_embeds_placeholder_token_id is not None
1396
+ cast(dict, prompt)["_prompt_embeds"] = (
1397
+ prompt_embeds_tensors,
1398
+ prompt_embeds_placeholder_token_id,
1399
+ )
1400
+ if params.mm_processor_kwargs:
1401
+ cast(dict, prompt)["mm_processor_kwargs"] = params.mm_processor_kwargs
1402
+ elif prompt_embeds_tensors:
1403
+ assert prompt_embeds_placeholder_token_id is not None
1404
+ self._apply_prompt_embeds_to_prompt(
1405
+ prompt,
1406
+ prompt_embeds_tensors,
1407
+ prompt_embeds_placeholder_token_id,
1408
+ )
1409
+
1410
+ if mm_data is not None:
1411
+ prompt["multi_modal_data"] = mm_data
1412
+ if mm_uuids is not None:
1413
+ prompt["multi_modal_uuids"] = mm_uuids
1414
+
1415
+ return conversation, prompt
1416
+
1417
+ @override
1418
+ def _process_tokens(
1419
+ self,
1420
+ prompt: TokensPrompt,
1421
+ *,
1422
+ skip_mm_cache: bool = False,
1423
+ ) -> TokensInput | MultiModalInput:
1424
+ """Pre-expand `prompt_embeds` sentinels before delegating to the MM
1425
+ processor, then attach `prompt_embeds` modality data to the result.
1426
+
1427
+ Mixed mode only: the `_prompt_embeds` stash is set by
1428
+ `render_messages` when `prompt_embeds` co-exist with other MM data
1429
+ (images, audio, …). We expand each 1-token sentinel to an N-token
1430
+ span *before* calling `super()._process_tokens()` so the MM
1431
+ processor records all placeholder offsets in the final (post-expansion)
1432
+ coordinate space, no offset shifting needed afterwards.
1433
+ """
1434
+ prompt_embeds_info = cast(dict, prompt).pop("_prompt_embeds", None)
1435
+ if prompt_embeds_info is None:
1436
+ return super()._process_tokens(prompt, skip_mm_cache=skip_mm_cache)
1437
+
1438
+ tensors, placeholder_token_id = prompt_embeds_info
1439
+ mm_updates = _build_prompt_embeds_updates(tensors, placeholder_token_id)
1440
+ cast(dict, prompt)["prompt_token_ids"] = _expand_prompt_embeds_placeholders(
1441
+ list(prompt["prompt_token_ids"]), mm_updates
1442
+ )
1443
+ engine_input = super()._process_tokens(prompt, skip_mm_cache=skip_mm_cache)
1444
+ self._apply_prompt_embeds_to_engine_input(
1445
+ cast(MultiModalInput, engine_input),
1446
+ tensors,
1447
+ mm_updates,
1448
+ )
1449
+
1450
+ return engine_input
1451
+
1452
+ @override
1453
+ async def _process_tokens_async(
1454
+ self,
1455
+ prompt: TokensPrompt,
1456
+ *,
1457
+ skip_mm_cache: bool = False,
1458
+ ) -> TokensInput | MultiModalInput:
1459
+ """Async equivalent of `_process_tokens`."""
1460
+ prompt_embeds_info = cast(dict, prompt).pop("_prompt_embeds", None)
1461
+ if prompt_embeds_info is None:
1462
+ return await super()._process_tokens_async(
1463
+ prompt, skip_mm_cache=skip_mm_cache
1464
+ )
1465
+
1466
+ tensors, placeholder_token_id = prompt_embeds_info
1467
+ mm_updates = _build_prompt_embeds_updates(tensors, placeholder_token_id)
1468
+ cast(dict, prompt)["prompt_token_ids"] = _expand_prompt_embeds_placeholders(
1469
+ list(prompt["prompt_token_ids"]), mm_updates
1470
+ )
1471
+ engine_input = await super()._process_tokens_async(
1472
+ prompt, skip_mm_cache=skip_mm_cache
1473
+ )
1474
+ self._apply_prompt_embeds_to_engine_input(
1475
+ cast(MultiModalInput, engine_input),
1476
+ tensors,
1477
+ mm_updates,
1478
+ )
1479
+
1480
+ return engine_input
1481
+
1482
+ @staticmethod
1483
+ def _apply_prompt_embeds_to_prompt(
1484
+ prompt: DictPrompt,
1485
+ prompt_embeds_tensors: list[torch.Tensor],
1486
+ placeholder_token_id: int,
1487
+ ) -> None:
1488
+ """Mutate `prompt` from `TokensPrompt` to `EmbedsPrompt` shape.
1489
+
1490
+ Pure `prompt_embeds` path only (no other MM modalities). Expands
1491
+ each `<prompt_embeds>` sentinel token into an N-token span and builds
1492
+ the full-length `prompt_embeds` tensor + `prompt_is_token_ids` mask
1493
+ that the engine's `enable_prompt_embeds` worker branch consumes.
1494
+ """
1495
+ token_ids = cast(list[int] | None, prompt.get("prompt_token_ids"))
1496
+ if token_ids is None:
1497
+ raise RuntimeError(_MISSING_PROMPT_TOKEN_IDS_ERROR)
1498
+
1499
+ embeds_orig_positions: list[int] = [
1500
+ i for i, tok in enumerate(token_ids) if tok == placeholder_token_id
1501
+ ]
1502
+ if len(embeds_orig_positions) != len(prompt_embeds_tensors):
1503
+ raise ValueError(
1504
+ f"Expected {len(prompt_embeds_tensors)} prompt_embeds "
1505
+ f"placeholder tokens in the rendered prompt, found "
1506
+ f"{len(embeds_orig_positions)}."
1507
+ )
1508
+
1509
+ mm_updates = _build_prompt_embeds_updates(
1510
+ prompt_embeds_tensors, placeholder_token_id
1511
+ )
1512
+ expanded = _expand_prompt_embeds_placeholders(token_ids, mm_updates)
1513
+ positions = _build_prompt_embeds_positions(
1514
+ expanded, len(prompt_embeds_tensors), mm_updates
1515
+ )
1516
+
1517
+ embeds_prompt = cast(EmbedsPrompt, prompt)
1518
+ embeds_prompt["prompt_token_ids"] = expanded
1519
+ full_embeds, is_token_ids_mask = _build_mixed_prompt_embeds(
1520
+ expanded, prompt_embeds_tensors, positions
1521
+ )
1522
+ embeds_prompt["prompt_embeds"] = full_embeds
1523
+ embeds_prompt["prompt_is_token_ids"] = is_token_ids_mask
1524
+
1525
+ def _apply_prompt_embeds_to_engine_input(
1526
+ self,
1527
+ engine_input: MultiModalInput,
1528
+ prompt_embeds_tensors: list[torch.Tensor],
1529
+ mm_updates: MultiModalPromptUpdates,
1530
+ ) -> None:
1531
+ """Augment `engine_input` in-place with a `prompt_embeds` modality.
1532
+
1533
+ Mixed mode: called after `_process_multimodal` has already run on the
1534
+ pre-expanded token IDs (expansion was done in `_process_tokens` before
1535
+ calling `super()`). Locates the already-expanded `prompt_embeds` spans
1536
+ and adds `prompt_embeds` entries to `mm_kwargs`, `mm_hashes`, and
1537
+ `mm_placeholders`.
1538
+ """
1539
+ # token_ids already contain the pre-expanded N-token spans.
1540
+ token_ids = list(engine_input["prompt_token_ids"])
1541
+
1542
+ positions = _build_prompt_embeds_positions(
1543
+ token_ids, len(prompt_embeds_tensors), mm_updates
1544
+ )
1545
+
1546
+ pe_kwargs_items: list[MultiModalKwargsItem] = []
1547
+ pe_hashes: list[str] = []
1548
+ pe_placeholders: list[PlaceholderRange] = []
1549
+ mm_config = self.model_config.get_multimodal_config()
1550
+ for tensor, (start, length) in zip(
1551
+ prompt_embeds_tensors, positions, strict=True
1552
+ ):
1553
+ pe_kwargs_items.append(
1554
+ MultiModalKwargsItem(
1555
+ {
1556
+ "embedding": MultiModalFieldElem(
1557
+ data=tensor,
1558
+ field=MultiModalSharedField(batch_size=1),
1559
+ )
1560
+ }
1561
+ )
1562
+ )
1563
+ pe_hashes.append(
1564
+ MultiModalHasher.hash_kwargs(
1565
+ mm_config.mm_hasher_algorithm, prompt_embeds=tensor
1566
+ )
1567
+ )
1568
+ # `is_embed=None` matches the existing image_embeds-style
1569
+ # "no encoder, just splice the tensor directly" semantics.
1570
+ pe_placeholders.append(
1571
+ PlaceholderRange(offset=start, length=length, is_embed=None)
1572
+ )
1573
+
1574
+ cast(
1575
+ MultiModalKwargsItems[MultiModalKwargsItem | None],
1576
+ engine_input["mm_kwargs"],
1577
+ )["prompt_embeds"] = pe_kwargs_items
1578
+ engine_input["mm_hashes"] = {
1579
+ **engine_input["mm_hashes"],
1580
+ "prompt_embeds": pe_hashes,
1581
+ }
1582
+ cast(dict, engine_input["mm_placeholders"])["prompt_embeds"] = pe_placeholders