vllm - ✅(Solved) Fix [Bug]: Gemma4-31B-it deployed on vLLM cannot process images in tool message [1 pull requests, 1 comments, 2 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
vllm-project/vllm#41452Fetched 2026-05-02 05:28:04
View on GitHub
Comments
1
Participants
2
Timeline
5
Reactions
0
Timeline (top)
subscribed ×2commented ×1cross-referenced ×1labeled ×1

Error Message

import os import sys from openai import OpenAI

API_BASE = <your_server_url> API_KEY = <your_api_key> MODEL = "Gemma4-31B-it"

1x1 transparent PNG — small but valid; exercises the multimodal pipeline

with no external file dependency.

TINY_PNG_B64 = ( "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAA" "jCB0C8AAAAASUVORK5CYII=" ) IMAGE_DATA_URL = f"data:image/png;base64,{TINY_PNG_B64}"

client = OpenAI(base_url=API_BASE, api_key=API_KEY)

def case_A_user_multimodal() -> None: """Image in a user message — works.""" print("=" * 70) print("Case A: image in USER message (expected: 200 OK)") print("=" * 70) resp = client.chat.completions.create( model=MODEL, messages=[ {"role": "user", "content": [ {"type": "text", "text": "Describe this image briefly."}, {"type": "image_url", "image_url": {"url": IMAGE_DATA_URL}}, ]}, ], max_tokens=64, ) print("OK ->", resp.choices[0].message.content)

def case_B_tool_multimodal() -> None: """Same image in a tool message — server returns 500.""" print("=" * 70) print("Case B: image in TOOL message (expected: 200 OK; actual: 500)") print("=" * 70) resp = client.chat.completions.create( model=MODEL, messages=[ {"role": "user", "content": "Download https://example.com/x.png and describe it."}, {"role": "assistant", "content": "", "tool_calls": [ {"id": "call_1", "type": "function", "function": {"name": "download_image", "arguments": '{"url": "https://example.com/x.png"}'}}, ]}, {"role": "tool", "tool_call_id": "call_1", "content": [ {"type": "text", "text": "Image downloaded successfully."}, {"type": "image_url", "image_url": {"url": IMAGE_DATA_URL}}, ]}, ], max_tokens=64, ) print("OK ->", resp.choices[0].message.content)

if name == "main": try: case_A_user_multimodal() except Exception as e: print("Case A FAILED unexpectedly:", e, file=sys.stderr)

print()

try:
    case_B_tool_multimodal()
except Exception as e:
    print("Case B FAILED (this is the bug):", e, file=sys.stderr)

Fix Action

Fix / Workaround

============================== CPU Info

Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 46 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 128 On-line CPU(s) list: 0-127 Vendor ID: GenuineIntel BIOS Vendor ID: Intel(R) Corporation Model name: Intel(R) Xeon(R) Platinum 8358P CPU @ 2.60GHz BIOS Model name: Intel(R) Xeon(R) Platinum 8358P CPU @ 2.60GHz CPU @ 2.6GHz BIOS CPU family: 179 CPU family: 6 Model: 106 Thread(s) per core: 2 Core(s) per socket: 32 Socket(s): 2 Stepping: 6 Frequency boost: enabled CPU(s) scaling MHz: 43% CPU max MHz: 3400.0000 CPU min MHz: 800.0000 BogoMIPS: 5200.00 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid md_clear pconfig flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 3 MiB (64 instances) L1i cache: 2 MiB (64 instances) L2 cache: 80 MiB (64 instances) L3 cache: 96 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-31,64-95 NUMA node1 CPU(s): 32-63,96-127 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable Vulnerability Retbleed: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

PR fix notes

PR #41459: fix(frontend): Add multimodal placeholders to Gemma4 tool message template

Description (problem / solution / changelog)

Purpose

The following <ins>Gemma4 tool-calling multimodal</ins> use case was fixed in this PR:

→ A TLDR of the issue: When a role: "tool" message contains multimodal content parts, for example, [{"type": "text", ...}, {"type": "image"}], the Gemma4 chat template's tool message content-parts loop only extracts type == "text" parts and drops image/audio/video entries without any warnings.
Upon RCA, it turns out the upstream chat_template.jinja shipped by Google on HF has the same bug across all four Gemma4 IT variants. So firstly, raised companion HF Hub PRs to fix the source of truth 🤗

<ins>Companion PRs:</ins>
gemma-4-31B-it Hub PR
gemma-4-26B-A4B-it Hub PR
gemma-4-E4B-it Hub PR
gemma-4-31B-it Hub PR

Secondly, we can fix it within the scope of vLLM's example template for Gemma 4 without dependency on upstream. Added regression tests to make sure the functionality is fixed.

The vLLM PR and Hub PRs together fix #41452 :)

cc: @hmellor

Current Output:

<img alt="4" src="https://github.com/user-attachments/assets/563fe06a-9bf8-4911-8ca7-b03070e5c814" /><br>

Output After Fix:

<img alt="image" src="https://github.com/user-attachments/assets/27557463-7cad-4514-b118-a2aa63d71901" />

Repro

→ Launch the server as follows, and run the repro given in the issue!

vllm serve google/gemma-4-E2B-it 
--port 8199 
--chat-template examples/tool_chat_template_gemma4.jinja 
--enable-auto-tool-choice 
--tool-call-parser gemma4

Test Plan

The following tests were added to prevent regressions: TestGemma4ChatTemplate::test_tool_response_with_multimodal_content and TestGemma4ChatTemplate::test_tool_response_with_all_modalities.

Verified that this change does not cause any breakages in Transformers (tests use dummy chat template) or vLLM.

SuiteResult
vLLM template tests (16)16 passed
vLLM multimodal processing (1)1 passed
vLLM tool/reasoning parsers (77)77 passed
Transformers Gemma4 processing (33)30 passed, 3 skipped

vLLM Test Result

<img alt="image" src="https://github.com/user-attachments/assets/5cdda1bd-5d23-4007-8b39-45733a93bfa1" />

Before submitting

  • This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
  • Was this discussed/approved via a Github issue?
  • The purpose of the PR, such as "Fix some issue (link existing issues this PR will resolve)".
  • The test plan, such as providing test command.
  • The test results, such as pasting the results comparison before and after, or e2e results

Changed files

  • examples/tool_chat_template_gemma4.jinja (modified, +9/-0)
  • tests/renderers/test_gemma4_chat_template.py (modified, +69/-0)

Code Example

Collecting environment information...
==============================
        System Info
==============================
OS                           : Ubuntu 24.04.3 LTS (x86_64)
GCC version                  : (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0
Clang version                : Could not collect
CMake version                : Could not collect
Libc version                 : glibc-2.39

==============================
       PyTorch Info
==============================
PyTorch version              : 2.11.0+cu130
Is debug build               : False
CUDA used to build PyTorch   : 13.0
ROCM used to build PyTorch   : N/A
XPU used to build PyTorch    : N/A

==============================
      Python Environment
==============================
Python version               : 3.12.3 (main, Mar 23 2026, 19:04:32) [GCC 13.3.0] (64-bit runtime)
Python platform              : Linux-5.4.0-173-generic-x86_64-with-glibc2.39
    
==============================
       CUDA / GPU Info
==============================
Is CUDA available            : True
CUDA runtime version         : 13.0.88
CUDA_MODULE_LOADING set to   : 
GPU models and configuration : 
GPU 0: NVIDIA A100-SXM4-80GB
GPU 1: NVIDIA A100-SXM4-80GB
GPU 2: NVIDIA A100-SXM4-80GB
GPU 3: NVIDIA A100-SXM4-80GB
GPU 4: NVIDIA A100-SXM4-80GB
GPU 5: NVIDIA A100-SXM4-80GB
GPU 6: NVIDIA A100-SXM4-80GB
GPU 7: NVIDIA A100-SXM4-80GB

Nvidia driver version        : 570.172.08
cuDNN version                : Could not collect
HIP runtime version          : N/A
MIOpen runtime version       : N/A
Is XNNPACK available         : True

==============================
          CPU Info
==============================
Architecture:                       x86_64
CPU op-mode(s):                     32-bit, 64-bit
Address sizes:                      46 bits physical, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             128
On-line CPU(s) list:                0-127
Vendor ID:                          GenuineIntel
BIOS Vendor ID:                     Intel(R) Corporation
Model name:                         Intel(R) Xeon(R) Platinum 8358P CPU @ 2.60GHz
BIOS Model name:                    Intel(R) Xeon(R) Platinum 8358P CPU @ 2.60GHz  CPU @ 2.6GHz
BIOS CPU family:                    179
CPU family:                         6
Model:                              106
Thread(s) per core:                 2
Core(s) per socket:                 32
Socket(s):                          2
Stepping:                           6
Frequency boost:                    enabled
CPU(s) scaling MHz:                 43%
CPU max MHz:                        3400.0000
CPU min MHz:                        800.0000
BogoMIPS:                           5200.00
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid md_clear pconfig flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          3 MiB (64 instances)
L1i cache:                          2 MiB (64 instances)
L2 cache:                           80 MiB (64 instances)
L3 cache:                           96 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0-31,64-95
NUMA node1 CPU(s):                  32-63,96-127
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:             Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

==============================
Versions of relevant libraries
==============================
[pip3] flashinfer-python==0.6.8.post1
[pip3] numpy==2.2.6
[pip3] nvidia-cublas==13.1.0.3
[pip3] nvidia-cuda-cupti==13.0.85
[pip3] nvidia-cuda-nvrtc==13.0.88
[pip3] nvidia-cuda-runtime==13.0.96
[pip3] nvidia-cudnn-cu13==9.19.0.56
[pip3] nvidia-cudnn-frontend==1.18.0
[pip3] nvidia-cufft==12.0.0.61
[pip3] nvidia-cufile==1.15.1.6
[pip3] nvidia-curand==10.4.0.35
[pip3] nvidia-cusolver==12.0.4.66
[pip3] nvidia-cusparse==12.6.3.3
[pip3] nvidia-cusparselt-cu13==0.8.0
[pip3] nvidia-cutlass-dsl==4.4.2
[pip3] nvidia-cutlass-dsl-libs-base==4.4.2
[pip3] nvidia-ml-py==13.595.45
[pip3] nvidia-nccl-cu13==2.28.9
[pip3] nvidia-nvjitlink==13.0.88
[pip3] nvidia-nvshmem-cu13==3.4.5
[pip3] nvidia-nvtx==13.0.85
[pip3] pyzmq==27.1.0
[pip3] torch==2.11.0+cu130
[pip3] torch_c_dlpack_ext==0.1.5
[pip3] torchaudio==2.11.0+cu130
[pip3] torchvision==0.26.0+cu130
[pip3] transformers==5.6.2
[pip3] triton==3.6.0
[conda] Could not collect

==============================
         vLLM Info
==============================
ROCM Version                 : Could not collect
vLLM Version                 : 0.20.0
vLLM Build Flags:
  CUDA Archs: 7.5 8.0 8.6 8.9 9.0 10.0 12.0+PTX; ROCm: Disabled; XPU: Disabled
GPU Topology:
        GPU0    GPU1    GPU2    GPU3    GPU4    GPU5    GPU6    GPU7    NIC0    NIC1    NIC2    NIC3    NIC4    NIC5    NIC6    NIC7    NIC8    CPU Affinity    NUMA Affinity   GPU NUMA ID
GPU0     X      NV12    NV12    NV12    NV12    NV12    NV12    NV12    SYS     SYS     NODE    PXB     SYS     SYS     SYS     SYS     NODE    0-31,64-95      0               N/A
GPU1    NV12     X      NV12    NV12    NV12    NV12    NV12    NV12    SYS     SYS     NODE    PXB     SYS     SYS     SYS     SYS     NODE    0-31,64-95      0               N/A
GPU2    NV12    NV12     X      NV12    NV12    NV12    NV12    NV12    SYS     SYS     PXB     NODE    SYS     SYS     SYS     SYS     NODE    0-31,64-95      0               N/A
GPU3    NV12    NV12    NV12     X      NV12    NV12    NV12    NV12    SYS     SYS     PXB     NODE    SYS     SYS     SYS     SYS     NODE    0-31,64-95      0               N/A
GPU4    NV12    NV12    NV12    NV12     X      NV12    NV12    NV12    NODE    PXB     SYS     SYS     NODE    NODE    NODE    NODE    SYS     32-63,96-127    1               N/A
GPU5    NV12    NV12    NV12    NV12    NV12     X      NV12    NV12    NODE    PXB     SYS     SYS     NODE    NODE    NODE    NODE    SYS     32-63,96-127    1               N/A
GPU6    NV12    NV12    NV12    NV12    NV12    NV12     X      NV12    PXB     NODE    SYS     SYS     NODE    NODE    NODE    NODE    SYS     32-63,96-127    1               N/A
GPU7    NV12    NV12    NV12    NV12    NV12    NV12    NV12     X      PXB     NODE    SYS     SYS     NODE    NODE    NODE    NODE    SYS     32-63,96-127    1               N/A
NIC0    SYS     SYS     SYS     SYS     NODE    NODE    PXB     PXB      X      NODE    SYS     SYS     NODE    NODE    NODE    NODE    SYS
NIC1    SYS     SYS     SYS     SYS     PXB     PXB     NODE    NODE    NODE     X      SYS     SYS     NODE    NODE    NODE    NODE    SYS
NIC2    NODE    NODE    PXB     PXB     SYS     SYS     SYS     SYS     SYS     SYS      X      NODE    SYS     SYS     SYS     SYS     NODE
NIC3    PXB     PXB     NODE    NODE    SYS     SYS     SYS     SYS     SYS     SYS     NODE     X      SYS     SYS     SYS     SYS     NODE
NIC4    SYS     SYS     SYS     SYS     NODE    NODE    NODE    NODE    NODE    NODE    SYS     SYS      X      PIX     PHB     PHB     SYS
NIC5    SYS     SYS     SYS     SYS     NODE    NODE    NODE    NODE    NODE    NODE    SYS     SYS     PIX      X      PHB     PHB     SYS
NIC6    SYS     SYS     SYS     SYS     NODE    NODE    NODE    NODE    NODE    NODE    SYS     SYS     PHB     PHB      X      PIX     SYS
NIC7    SYS     SYS     SYS     SYS     NODE    NODE    NODE    NODE    NODE    NODE    SYS     SYS     PHB     PHB     PIX      X      SYS
NIC8    NODE    NODE    NODE    NODE    SYS     SYS     SYS     SYS     SYS     SYS     NODE    NODE    SYS     SYS     SYS     SYS      X 

Legend:

  X    = Self
  SYS  = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)
  NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node
  PHB  = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)
  PXB  = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)
  PIX  = Connection traversing at most a single PCIe bridge
  NV#  = Connection traversing a bonded set of # NVLinks

NIC Legend:

  NIC0: mlx5_cx6_0
  NIC1: mlx5_cx6_1
  NIC2: mlx5_cx6_2
  NIC3: mlx5_cx6_3
  NIC4: mlx5_cx4lx_0
  NIC5: mlx5_cx4lx_1
  NIC6: mlx5_cx4lx_2
  NIC7: mlx5_cx4lx_3
  NIC8: mlx5_cx4lx_4

==============================
     Environment Variables
==============================
NVIDIA_VISIBLE_DEVICES=GPU-ef7992f0-d2d2-b2ba-d9aa-13d7830bc191,GPU-fc1d6e4e-17e0-aad0-aa32-dbf2b8b52c68,GPU-ad0d22e3-e8fb-3212-1608-aebe404a86d5,GPU-b585aeb9-7a34-ffb5-dc63-f90d1e7884d6,GPU-5563e915-67e8-e4b4-68da-7e3e88ae6a86,GPU-fcc72bf3-adfe-e599-3da0-129f7c7d0894,GPU-9128ea07-a489-d45a-93fd-da1cdf5937c2,GPU-730848c4-28b3-ba31-ba2c-216169b00011
NCCL_IB_TC=168
NVIDIA_REQUIRE_CUDA=cuda>=13.0 brand=unknown,driver>=535,driver<536 brand=grid,driver>=535,driver<536 brand=tesla,driver>=535,driver<536 brand=nvidia,driver>=535,driver<536 brand=quadro,driver>=535,driver<536 brand=quadrortx,driver>=535,driver<536 brand=nvidiartx,driver>=535,driver<536 brand=vapps,driver>=535,driver<536 brand=vpc,driver>=535,driver<536 brand=vcs,driver>=535,driver<536 brand=vws,driver>=535,driver<536 brand=cloudgaming,driver>=535,driver<536 brand=unknown,driver>=550,driver<551 brand=grid,driver>=550,driver<551 brand=tesla,driver>=550,driver<551 brand=nvidia,driver>=550,driver<551 brand=quadro,driver>=550,driver<551 brand=quadrortx,driver>=550,driver<551 brand=nvidiartx,driver>=550,driver<551 brand=vapps,driver>=550,driver<551 brand=vpc,driver>=550,driver<551 brand=vcs,driver>=550,driver<551 brand=vws,driver>=550,driver<551 brand=cloudgaming,driver>=550,driver<551 brand=unknown,driver>=565,driver<566 brand=grid,driver>=565,driver<566 brand=tesla,driver>=565,driver<566 brand=nvidia,driver>=565,driver<566 brand=quadro,driver>=565,driver<566 brand=quadrortx,driver>=565,driver<566 brand=nvidiartx,driver>=565,driver<566 brand=vapps,driver>=565,driver<566 brand=vpc,driver>=565,driver<566 brand=vcs,driver>=565,driver<566 brand=vws,driver>=565,driver<566 brand=cloudgaming,driver>=565,driver<566 brand=unknown,driver>=570,driver<571 brand=grid,driver>=570,driver<571 brand=tesla,driver>=570,driver<571 brand=nvidia,driver>=570,driver<571 brand=quadro,driver>=570,driver<571 brand=quadrortx,driver>=570,driver<571 brand=nvidiartx,driver>=570,driver<571 brand=vapps,driver>=570,driver<571 brand=vpc,driver>=570,driver<571 brand=vcs,driver>=570,driver<571 brand=vws,driver>=570,driver<571 brand=cloudgaming,driver>=570,driver<571 brand=unknown,driver>=575,driver<576 brand=grid,driver>=575,driver<576 brand=tesla,driver>=575,driver<576 brand=nvidia,driver>=575,driver<576 brand=quadro,driver>=575,driver<576 brand=quadrortx,driver>=575,driver<576 brand=nvidiartx,driver>=575,driver<576 brand=vapps,driver>=575,driver<576 brand=vpc,driver>=575,driver<576 brand=vcs,driver>=575,driver<576 brand=vws,driver>=575,driver<576 brand=cloudgaming,driver>=575,driver<576
TORCH_CUDA_ARCH_LIST=7.5 8.0 8.6 8.9 9.0 10.0 12.0+PTX
NCCL_SOCKET_IFNAME=bondYW
NCCL_NET_GDR_LEVEL=3
NVIDIA_DRIVER_CAPABILITIES=compute,utility
NCCL_DEBUG=INFO
NCCL_IB_HCA=mlx5_cx6_0,mlx5_cx6_1,mlx5_cx6_2,mlx5_cx6_3
VLLM_USAGE_SOURCE=production-docker-image
NCCL_IB_GID_INDEX=3
CUDA_VERSION=13.0.2
VLLM_ENABLE_CUDA_COMPATIBILITY=0
NCCL_IB_TIMEOUT=22
LD_LIBRARY_PATH=/usr/local/nvidia/lib64:/usr/local/cuda/lib64:/usr/local/nvidia/lib:/usr/local/nvidia/lib64:/usr/local/cuda/lib64
PYTORCH_NVML_BASED_CUDA_CHECK=1
TORCHINDUCTOR_COMPILE_THREADS=1
TORCHINDUCTOR_CACHE_DIR=/tmp/torchinductor_root

---

nohup vllm serve ./$model_name \
    --served-model-name "Gemma4-31B-it" \
    --api-key <your_api_key> \
    --host 0.0.0.0 \
    --port "${SERVICE_PORT}" \
    --max-model-len 262144 \
    --max-num-seqs 128 \
    --tensor-parallel-size 8 \
    --gpu-memory-utilization 0.90 \
    --stream-interval 10 \
    --enable-chunked-prefill \
    --max-num-batched-tokens 8192 \
    --async-scheduling \
    --enable-auto-tool-choice \
    --tool-call-parser gemma4 \
    --reasoning-parser gemma4 \
    > "$log_file" 2>&1 &

---

import os
import sys
from openai import OpenAI

API_BASE = <your_server_url>
API_KEY  = <your_api_key>
MODEL    = "Gemma4-31B-it"

# 1x1 transparent PNG — small but valid; exercises the multimodal pipeline
# with no external file dependency.
TINY_PNG_B64 = (
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAA"
    "jCB0C8AAAAASUVORK5CYII="
)
IMAGE_DATA_URL = f"data:image/png;base64,{TINY_PNG_B64}"

client = OpenAI(base_url=API_BASE, api_key=API_KEY)


def case_A_user_multimodal() -> None:
    """Image in a user message — works."""
    print("=" * 70)
    print("Case A: image in USER message  (expected: 200 OK)")
    print("=" * 70)
    resp = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "user", "content": [
                {"type": "text", "text": "Describe this image briefly."},
                {"type": "image_url", "image_url": {"url": IMAGE_DATA_URL}},
            ]},
        ],
        max_tokens=64,
    )
    print("OK ->", resp.choices[0].message.content)


def case_B_tool_multimodal() -> None:
    """Same image in a tool message — server returns 500."""
    print("=" * 70)
    print("Case B: image in TOOL message  (expected: 200 OK; actual: 500)")
    print("=" * 70)
    resp = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "user",
             "content": "Download https://example.com/x.png and describe it."},
            {"role": "assistant", "content": "", "tool_calls": [
                {"id": "call_1", "type": "function",
                 "function": {"name": "download_image",
                              "arguments": '{"url": "https://example.com/x.png"}'}},
            ]},
            {"role": "tool", "tool_call_id": "call_1", "content": [
                {"type": "text", "text": "Image downloaded successfully."},
                {"type": "image_url", "image_url": {"url": IMAGE_DATA_URL}},
            ]},
        ],
        max_tokens=64,
    )
    print("OK ->", resp.choices[0].message.content)


if __name__ == "__main__":
    try:
        case_A_user_multimodal()
    except Exception as e:
        print("Case A FAILED unexpectedly:", e, file=sys.stderr)

    print()

    try:
        case_B_tool_multimodal()
    except Exception as e:
        print("Case B FAILED (this is the bug):", e, file=sys.stderr)

---

======================================================================
Case A: image in USER message  (expected: 200 OK)
======================================================================
OK -> This is a solid black image.

======================================================================
Case B: image in TOOL message  (expected: 200 OK; actual: 500)
======================================================================
Case B FAILED (this is the bug): Error code: 500 - {'error': {'message': "Failed to apply prompt replacement for mm_items['image'][0]", 'type': 'InternalServerError', 'param': None, 'code': 500}}

---

(APIServer pid=1001884) INFO:     10.200.99.229:12273 - "POST /tokenize HTTP/1.1" 500 Internal Server Error
(APIServer pid=1001884) ERROR:    Exception in ASGI application
(APIServer pid=1001884) Traceback (most recent call last):
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/uvicorn/protocols/http/httptools_impl.py", line 421, in run_asgi
(APIServer pid=1001884)     result = await app(  # type: ignore[func-returns-value]
(APIServer pid=1001884)              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/uvicorn/middleware/proxy_headers.py", line 56, in __call__
(APIServer pid=1001884)     return await self.app(scope, receive, send)
(APIServer pid=1001884)            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/fastapi/applications.py", line 1159, in __call__
(APIServer pid=1001884)     await super().__call__(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/applications.py", line 107, in __call__
(APIServer pid=1001884)     await self.middleware_stack(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/middleware/errors.py", line 186, in __call__
(APIServer pid=1001884)     raise exc
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/middleware/errors.py", line 164, in __call__
(APIServer pid=1001884)     await self.app(scope, receive, _send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/middleware/cors.py", line 87, in __call__
(APIServer pid=1001884)     await self.app(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/prometheus_fastapi_instrumentator/middleware.py", line 177, in __call__
(APIServer pid=1001884)     raise exc
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/prometheus_fastapi_instrumentator/middleware.py", line 175, in __call__
(APIServer pid=1001884)     await self.app(scope, receive, send_wrapper)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/middleware/exceptions.py", line 63, in __call__
(APIServer pid=1001884)     await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/_exception_handler.py", line 53, in wrapped_app
(APIServer pid=1001884)     raise exc
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/_exception_handler.py", line 42, in wrapped_app
(APIServer pid=1001884)     await app(scope, receive, sender)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__
(APIServer pid=1001884)     await self.app(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/routing.py", line 716, in __call__
(APIServer pid=1001884)     await self.middleware_stack(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/routing.py", line 736, in app
(APIServer pid=1001884)     await route.handle(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/routing.py", line 290, in handle
(APIServer pid=1001884)     await self.app(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/fastapi/routing.py", line 134, in app
(APIServer pid=1001884)     await wrap_app_handling_exceptions(app, request)(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/_exception_handler.py", line 53, in wrapped_app
(APIServer pid=1001884)     raise exc
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/_exception_handler.py", line 42, in wrapped_app
(APIServer pid=1001884)     await app(scope, receive, sender)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/fastapi/routing.py", line 120, in app
(APIServer pid=1001884)     response = await f(request)
(APIServer pid=1001884)                ^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/fastapi/routing.py", line 674, in app
(APIServer pid=1001884)     raw_response = await run_endpoint_function(
(APIServer pid=1001884)                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/fastapi/routing.py", line 328, in run_endpoint_function
(APIServer pid=1001884)     return await dependant.call(**values)
(APIServer pid=1001884)            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/entrypoints/utils.py", line 95, in wrapper
(APIServer pid=1001884)     return handler_task.result()
(APIServer pid=1001884)            ^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/entrypoints/serve/tokenize/api_router.py", line 52, in tokenize
(APIServer pid=1001884)     generator = await handler.create_tokenize(request, raw_request)
(APIServer pid=1001884)                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/entrypoints/serve/tokenize/serving.py", line 82, in create_tokenize
(APIServer pid=1001884)     _, engine_inputs = await self.openai_serving_render.preprocess_chat(
(APIServer pid=1001884)                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/entrypoints/serve/render/serving.py", line 557, in preprocess_chat
(APIServer pid=1001884)     (conversation,), (engine_input,) = await renderer.render_chat_async(
(APIServer pid=1001884)                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/renderers/base.py", line 1034, in render_chat_async
(APIServer pid=1001884)     eng_prompts = await asyncio.gather(
(APIServer pid=1001884)                   ^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/renderers/base.py", line 910, in process_for_engine_async
(APIServer pid=1001884)     engine_input = await self._process_singleton_async(
(APIServer pid=1001884)                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/renderers/base.py", line 822, in _process_singleton_async
(APIServer pid=1001884)     return await self._process_tokens_async(prompt, skip_mm_cache=skip_mm_cache)  # type: ignore[arg-type]
(APIServer pid=1001884)            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/renderers/base.py", line 784, in _process_tokens_async
(APIServer pid=1001884)     engine_input = await self._process_multimodal_async(
(APIServer pid=1001884)                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/lib/python3.12/concurrent/futures/thread.py", line 58, in run
(APIServer pid=1001884)     result = self.fn(*self.args, **self.kwargs)
(APIServer pid=1001884)              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/renderers/base.py", line 709, in _process_multimodal
(APIServer pid=1001884)     mm_inputs = mm_processor.apply(mm_processor_inputs, mm_timing_ctx)
(APIServer pid=1001884)                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/multimodal/processing/processor.py", line 1689, in apply
(APIServer pid=1001884)     prompt_ids, mm_placeholders = self._maybe_apply_prompt_updates(
(APIServer pid=1001884)                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/multimodal/processing/processor.py", line 1655, in _maybe_apply_prompt_updates
(APIServer pid=1001884)     prompt_ids, mm_placeholders = self._apply_prompt_updates(
(APIServer pid=1001884)                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/multimodal/processing/processor.py", line 1565, in _apply_prompt_updates
(APIServer pid=1001884)     assert update_idx is not None, (
(APIServer pid=1001884)            ^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884) AssertionError: Failed to apply prompt replacement for mm_items['image'][0]

---

from __future__ import annotations

import os
import sys
from typing import Any

import torch
from transformers import AutoModelForImageTextToText, AutoProcessor

MODEL_PATH = os.environ.get(
    "GEMMA4_MODEL_PATH",
    "/home/<user_name>/Models/Gemma4-31B-it",
)

# 1x1 transparent PNG -- small but valid. Same bytes are used by the vLLM
# MRE so the two reports are directly comparable.
TINY_PNG_B64 = (
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAA"
    "jCB0C8AAAAASUVORK5CYII="
)
IMAGE_DATA_URL = f"data:image/png;base64,{TINY_PNG_B64}"


# NOTE: this processor's apply_chat_template iterates `content` looking
# for dict items with a "type" key, so plain-string content crashes with
# TypeError. We pass content as a list of parts everywhere.
MESSAGES_CASE_A = [
    {"role": "user", "content": [
        {"type": "text", "text": "Describe this image briefly."},
        {"type": "image_url", "image_url": {"url": IMAGE_DATA_URL}},
    ]},
]

MESSAGES_CASE_B = [
    {"role": "user", "content": [
        {"type": "text",
         "text": "Download https://example.com/x.png and describe it."},
    ]},
    {"role": "assistant",
     "content": [{"type": "text", "text": ""}],
     "tool_calls": [
        {"id": "call_1", "type": "function",
         "function": {"name": "download_image",
                      "arguments": '{"url": "https://example.com/x.png"}'}},
    ]},
    {"role": "tool", "tool_call_id": "call_1", "content": [
        {"type": "text", "text": "Image downloaded successfully."},
        {"type": "image_url", "image_url": {"url": IMAGE_DATA_URL}},
    ]},
]


def chat(
    processor: Any,
    model: Any,
    messages: list[dict[str, Any]],
    *,
    max_new_tokens: int = 1024,
    do_sample: bool = False,
) -> str:
    inputs = processor.apply_chat_template(
        messages,
        add_generation_prompt=True,
        tokenize=True,
        return_dict=True,
        return_tensors="pt",
    ).to(model.device)
    prompt_len = inputs["input_ids"].shape[-1]
    with torch.inference_mode():
        out = model.generate(
            **inputs,
            max_new_tokens=max_new_tokens,
            do_sample=do_sample,
        )
    return processor.batch_decode(
        out[:, prompt_len:],
        skip_special_tokens=True,
    )[0]


def run_case(label: str, processor, model, messages) -> None:
    print("=" * 70)
    print(label)
    print("=" * 70)
    try:
        out = chat(processor, model, messages)
        print("OK ->", out)
    except Exception as e:  # noqa: BLE001
        print("FAILED:", type(e).__name__, str(e)[:500], file=sys.stderr)


if __name__ == "__main__":
    processor = AutoProcessor.from_pretrained(MODEL_PATH)
    model = AutoModelForImageTextToText.from_pretrained(
        MODEL_PATH,
        dtype=torch.bfloat16,
        device_map="auto",
    )
    model.eval()

    run_case("Case A: image in USER message", processor, model, MESSAGES_CASE_A)
    print()
    run_case("Case B: image in TOOL message", processor, model, MESSAGES_CASE_B)

---

Loading weights: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1188/1188 [00:09<00:00, 125.00it/s]
======================================================================
Case A: image in USER message
======================================================================
[transformers] The channel dimension is ambiguous. Got image shape torch.Size([3, 1, 1]). Assuming channels are the first dimension. Use the [input_data_format](https://huggingface.co/docs/transformers/main/internal/image_processing_utils#transformers.image_transforms.rescale.input_data_format) parameter to assign the channel dimension.
[transformers] The following generation flags are not valid and may be ignored: ['top_p', 'top_k']. Set `TRANSFORMERS_VERBOSITY=info` for more details.
OK -> This is a solid black image.

======================================================================
Case B: image in TOOL message
======================================================================
[transformers] The channel dimension is ambiguous. Got image shape torch.Size([3, 1, 1]). Assuming channels are the first dimension. Use the [input_data_format](https://huggingface.co/docs/transformers/main/internal/image_processing_utils#transformers.image_transforms.rescale.input_data_format) parameter to assign the channel dimension.
OK -> thought
The image is a solid black square.
RAW_BUFFERClick to expand / collapse

Your current environment

<details> <summary>The output of <code>python collect_env.py</code></summary>
Collecting environment information...
==============================
        System Info
==============================
OS                           : Ubuntu 24.04.3 LTS (x86_64)
GCC version                  : (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0
Clang version                : Could not collect
CMake version                : Could not collect
Libc version                 : glibc-2.39

==============================
       PyTorch Info
==============================
PyTorch version              : 2.11.0+cu130
Is debug build               : False
CUDA used to build PyTorch   : 13.0
ROCM used to build PyTorch   : N/A
XPU used to build PyTorch    : N/A

==============================
      Python Environment
==============================
Python version               : 3.12.3 (main, Mar 23 2026, 19:04:32) [GCC 13.3.0] (64-bit runtime)
Python platform              : Linux-5.4.0-173-generic-x86_64-with-glibc2.39
    
==============================
       CUDA / GPU Info
==============================
Is CUDA available            : True
CUDA runtime version         : 13.0.88
CUDA_MODULE_LOADING set to   : 
GPU models and configuration : 
GPU 0: NVIDIA A100-SXM4-80GB
GPU 1: NVIDIA A100-SXM4-80GB
GPU 2: NVIDIA A100-SXM4-80GB
GPU 3: NVIDIA A100-SXM4-80GB
GPU 4: NVIDIA A100-SXM4-80GB
GPU 5: NVIDIA A100-SXM4-80GB
GPU 6: NVIDIA A100-SXM4-80GB
GPU 7: NVIDIA A100-SXM4-80GB

Nvidia driver version        : 570.172.08
cuDNN version                : Could not collect
HIP runtime version          : N/A
MIOpen runtime version       : N/A
Is XNNPACK available         : True

==============================
          CPU Info
==============================
Architecture:                       x86_64
CPU op-mode(s):                     32-bit, 64-bit
Address sizes:                      46 bits physical, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             128
On-line CPU(s) list:                0-127
Vendor ID:                          GenuineIntel
BIOS Vendor ID:                     Intel(R) Corporation
Model name:                         Intel(R) Xeon(R) Platinum 8358P CPU @ 2.60GHz
BIOS Model name:                    Intel(R) Xeon(R) Platinum 8358P CPU @ 2.60GHz  CPU @ 2.6GHz
BIOS CPU family:                    179
CPU family:                         6
Model:                              106
Thread(s) per core:                 2
Core(s) per socket:                 32
Socket(s):                          2
Stepping:                           6
Frequency boost:                    enabled
CPU(s) scaling MHz:                 43%
CPU max MHz:                        3400.0000
CPU min MHz:                        800.0000
BogoMIPS:                           5200.00
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid md_clear pconfig flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          3 MiB (64 instances)
L1i cache:                          2 MiB (64 instances)
L2 cache:                           80 MiB (64 instances)
L3 cache:                           96 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0-31,64-95
NUMA node1 CPU(s):                  32-63,96-127
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:             Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

==============================
Versions of relevant libraries
==============================
[pip3] flashinfer-python==0.6.8.post1
[pip3] numpy==2.2.6
[pip3] nvidia-cublas==13.1.0.3
[pip3] nvidia-cuda-cupti==13.0.85
[pip3] nvidia-cuda-nvrtc==13.0.88
[pip3] nvidia-cuda-runtime==13.0.96
[pip3] nvidia-cudnn-cu13==9.19.0.56
[pip3] nvidia-cudnn-frontend==1.18.0
[pip3] nvidia-cufft==12.0.0.61
[pip3] nvidia-cufile==1.15.1.6
[pip3] nvidia-curand==10.4.0.35
[pip3] nvidia-cusolver==12.0.4.66
[pip3] nvidia-cusparse==12.6.3.3
[pip3] nvidia-cusparselt-cu13==0.8.0
[pip3] nvidia-cutlass-dsl==4.4.2
[pip3] nvidia-cutlass-dsl-libs-base==4.4.2
[pip3] nvidia-ml-py==13.595.45
[pip3] nvidia-nccl-cu13==2.28.9
[pip3] nvidia-nvjitlink==13.0.88
[pip3] nvidia-nvshmem-cu13==3.4.5
[pip3] nvidia-nvtx==13.0.85
[pip3] pyzmq==27.1.0
[pip3] torch==2.11.0+cu130
[pip3] torch_c_dlpack_ext==0.1.5
[pip3] torchaudio==2.11.0+cu130
[pip3] torchvision==0.26.0+cu130
[pip3] transformers==5.6.2
[pip3] triton==3.6.0
[conda] Could not collect

==============================
         vLLM Info
==============================
ROCM Version                 : Could not collect
vLLM Version                 : 0.20.0
vLLM Build Flags:
  CUDA Archs: 7.5 8.0 8.6 8.9 9.0 10.0 12.0+PTX; ROCm: Disabled; XPU: Disabled
GPU Topology:
        GPU0    GPU1    GPU2    GPU3    GPU4    GPU5    GPU6    GPU7    NIC0    NIC1    NIC2    NIC3    NIC4    NIC5    NIC6    NIC7    NIC8    CPU Affinity    NUMA Affinity   GPU NUMA ID
GPU0     X      NV12    NV12    NV12    NV12    NV12    NV12    NV12    SYS     SYS     NODE    PXB     SYS     SYS     SYS     SYS     NODE    0-31,64-95      0               N/A
GPU1    NV12     X      NV12    NV12    NV12    NV12    NV12    NV12    SYS     SYS     NODE    PXB     SYS     SYS     SYS     SYS     NODE    0-31,64-95      0               N/A
GPU2    NV12    NV12     X      NV12    NV12    NV12    NV12    NV12    SYS     SYS     PXB     NODE    SYS     SYS     SYS     SYS     NODE    0-31,64-95      0               N/A
GPU3    NV12    NV12    NV12     X      NV12    NV12    NV12    NV12    SYS     SYS     PXB     NODE    SYS     SYS     SYS     SYS     NODE    0-31,64-95      0               N/A
GPU4    NV12    NV12    NV12    NV12     X      NV12    NV12    NV12    NODE    PXB     SYS     SYS     NODE    NODE    NODE    NODE    SYS     32-63,96-127    1               N/A
GPU5    NV12    NV12    NV12    NV12    NV12     X      NV12    NV12    NODE    PXB     SYS     SYS     NODE    NODE    NODE    NODE    SYS     32-63,96-127    1               N/A
GPU6    NV12    NV12    NV12    NV12    NV12    NV12     X      NV12    PXB     NODE    SYS     SYS     NODE    NODE    NODE    NODE    SYS     32-63,96-127    1               N/A
GPU7    NV12    NV12    NV12    NV12    NV12    NV12    NV12     X      PXB     NODE    SYS     SYS     NODE    NODE    NODE    NODE    SYS     32-63,96-127    1               N/A
NIC0    SYS     SYS     SYS     SYS     NODE    NODE    PXB     PXB      X      NODE    SYS     SYS     NODE    NODE    NODE    NODE    SYS
NIC1    SYS     SYS     SYS     SYS     PXB     PXB     NODE    NODE    NODE     X      SYS     SYS     NODE    NODE    NODE    NODE    SYS
NIC2    NODE    NODE    PXB     PXB     SYS     SYS     SYS     SYS     SYS     SYS      X      NODE    SYS     SYS     SYS     SYS     NODE
NIC3    PXB     PXB     NODE    NODE    SYS     SYS     SYS     SYS     SYS     SYS     NODE     X      SYS     SYS     SYS     SYS     NODE
NIC4    SYS     SYS     SYS     SYS     NODE    NODE    NODE    NODE    NODE    NODE    SYS     SYS      X      PIX     PHB     PHB     SYS
NIC5    SYS     SYS     SYS     SYS     NODE    NODE    NODE    NODE    NODE    NODE    SYS     SYS     PIX      X      PHB     PHB     SYS
NIC6    SYS     SYS     SYS     SYS     NODE    NODE    NODE    NODE    NODE    NODE    SYS     SYS     PHB     PHB      X      PIX     SYS
NIC7    SYS     SYS     SYS     SYS     NODE    NODE    NODE    NODE    NODE    NODE    SYS     SYS     PHB     PHB     PIX      X      SYS
NIC8    NODE    NODE    NODE    NODE    SYS     SYS     SYS     SYS     SYS     SYS     NODE    NODE    SYS     SYS     SYS     SYS      X 

Legend:

  X    = Self
  SYS  = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)
  NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node
  PHB  = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)
  PXB  = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)
  PIX  = Connection traversing at most a single PCIe bridge
  NV#  = Connection traversing a bonded set of # NVLinks

NIC Legend:

  NIC0: mlx5_cx6_0
  NIC1: mlx5_cx6_1
  NIC2: mlx5_cx6_2
  NIC3: mlx5_cx6_3
  NIC4: mlx5_cx4lx_0
  NIC5: mlx5_cx4lx_1
  NIC6: mlx5_cx4lx_2
  NIC7: mlx5_cx4lx_3
  NIC8: mlx5_cx4lx_4

==============================
     Environment Variables
==============================
NVIDIA_VISIBLE_DEVICES=GPU-ef7992f0-d2d2-b2ba-d9aa-13d7830bc191,GPU-fc1d6e4e-17e0-aad0-aa32-dbf2b8b52c68,GPU-ad0d22e3-e8fb-3212-1608-aebe404a86d5,GPU-b585aeb9-7a34-ffb5-dc63-f90d1e7884d6,GPU-5563e915-67e8-e4b4-68da-7e3e88ae6a86,GPU-fcc72bf3-adfe-e599-3da0-129f7c7d0894,GPU-9128ea07-a489-d45a-93fd-da1cdf5937c2,GPU-730848c4-28b3-ba31-ba2c-216169b00011
NCCL_IB_TC=168
NVIDIA_REQUIRE_CUDA=cuda>=13.0 brand=unknown,driver>=535,driver<536 brand=grid,driver>=535,driver<536 brand=tesla,driver>=535,driver<536 brand=nvidia,driver>=535,driver<536 brand=quadro,driver>=535,driver<536 brand=quadrortx,driver>=535,driver<536 brand=nvidiartx,driver>=535,driver<536 brand=vapps,driver>=535,driver<536 brand=vpc,driver>=535,driver<536 brand=vcs,driver>=535,driver<536 brand=vws,driver>=535,driver<536 brand=cloudgaming,driver>=535,driver<536 brand=unknown,driver>=550,driver<551 brand=grid,driver>=550,driver<551 brand=tesla,driver>=550,driver<551 brand=nvidia,driver>=550,driver<551 brand=quadro,driver>=550,driver<551 brand=quadrortx,driver>=550,driver<551 brand=nvidiartx,driver>=550,driver<551 brand=vapps,driver>=550,driver<551 brand=vpc,driver>=550,driver<551 brand=vcs,driver>=550,driver<551 brand=vws,driver>=550,driver<551 brand=cloudgaming,driver>=550,driver<551 brand=unknown,driver>=565,driver<566 brand=grid,driver>=565,driver<566 brand=tesla,driver>=565,driver<566 brand=nvidia,driver>=565,driver<566 brand=quadro,driver>=565,driver<566 brand=quadrortx,driver>=565,driver<566 brand=nvidiartx,driver>=565,driver<566 brand=vapps,driver>=565,driver<566 brand=vpc,driver>=565,driver<566 brand=vcs,driver>=565,driver<566 brand=vws,driver>=565,driver<566 brand=cloudgaming,driver>=565,driver<566 brand=unknown,driver>=570,driver<571 brand=grid,driver>=570,driver<571 brand=tesla,driver>=570,driver<571 brand=nvidia,driver>=570,driver<571 brand=quadro,driver>=570,driver<571 brand=quadrortx,driver>=570,driver<571 brand=nvidiartx,driver>=570,driver<571 brand=vapps,driver>=570,driver<571 brand=vpc,driver>=570,driver<571 brand=vcs,driver>=570,driver<571 brand=vws,driver>=570,driver<571 brand=cloudgaming,driver>=570,driver<571 brand=unknown,driver>=575,driver<576 brand=grid,driver>=575,driver<576 brand=tesla,driver>=575,driver<576 brand=nvidia,driver>=575,driver<576 brand=quadro,driver>=575,driver<576 brand=quadrortx,driver>=575,driver<576 brand=nvidiartx,driver>=575,driver<576 brand=vapps,driver>=575,driver<576 brand=vpc,driver>=575,driver<576 brand=vcs,driver>=575,driver<576 brand=vws,driver>=575,driver<576 brand=cloudgaming,driver>=575,driver<576
TORCH_CUDA_ARCH_LIST=7.5 8.0 8.6 8.9 9.0 10.0 12.0+PTX
NCCL_SOCKET_IFNAME=bondYW
NCCL_NET_GDR_LEVEL=3
NVIDIA_DRIVER_CAPABILITIES=compute,utility
NCCL_DEBUG=INFO
NCCL_IB_HCA=mlx5_cx6_0,mlx5_cx6_1,mlx5_cx6_2,mlx5_cx6_3
VLLM_USAGE_SOURCE=production-docker-image
NCCL_IB_GID_INDEX=3
CUDA_VERSION=13.0.2
VLLM_ENABLE_CUDA_COMPATIBILITY=0
NCCL_IB_TIMEOUT=22
LD_LIBRARY_PATH=/usr/local/nvidia/lib64:/usr/local/cuda/lib64:/usr/local/nvidia/lib:/usr/local/nvidia/lib64:/usr/local/cuda/lib64
PYTORCH_NVML_BASED_CUDA_CHECK=1
TORCHINDUCTOR_COMPILE_THREADS=1
TORCHINDUCTOR_CACHE_DIR=/tmp/torchinductor_root
</details>

🐛 Describe the bug

An Internal Server Error (500) occurs in Gemma4-31B-it hosted on vLLM-0.20.0 when the tool-calling output includes image data. The specific error message is: 500 - {'error': {'message': "Failed to apply prompt replacement for mm_items['image'][0]", 'type': 'InternalServerError', 'param': None, 'code': 500}}

However, when the user input message contains image data, the server works without problem.

Script to launch the vLLM server:

nohup vllm serve ./$model_name \
    --served-model-name "Gemma4-31B-it" \
    --api-key <your_api_key> \
    --host 0.0.0.0 \
    --port "${SERVICE_PORT}" \
    --max-model-len 262144 \
    --max-num-seqs 128 \
    --tensor-parallel-size 8 \
    --gpu-memory-utilization 0.90 \
    --stream-interval 10 \
    --enable-chunked-prefill \
    --max-num-batched-tokens 8192 \
    --async-scheduling \
    --enable-auto-tool-choice \
    --tool-call-parser gemma4 \
    --reasoning-parser gemma4 \
    > "$log_file" 2>&1 &

A minimal script to demonstrate the bug:

import os
import sys
from openai import OpenAI

API_BASE = <your_server_url>
API_KEY  = <your_api_key>
MODEL    = "Gemma4-31B-it"

# 1x1 transparent PNG — small but valid; exercises the multimodal pipeline
# with no external file dependency.
TINY_PNG_B64 = (
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAA"
    "jCB0C8AAAAASUVORK5CYII="
)
IMAGE_DATA_URL = f"data:image/png;base64,{TINY_PNG_B64}"

client = OpenAI(base_url=API_BASE, api_key=API_KEY)


def case_A_user_multimodal() -> None:
    """Image in a user message — works."""
    print("=" * 70)
    print("Case A: image in USER message  (expected: 200 OK)")
    print("=" * 70)
    resp = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "user", "content": [
                {"type": "text", "text": "Describe this image briefly."},
                {"type": "image_url", "image_url": {"url": IMAGE_DATA_URL}},
            ]},
        ],
        max_tokens=64,
    )
    print("OK ->", resp.choices[0].message.content)


def case_B_tool_multimodal() -> None:
    """Same image in a tool message — server returns 500."""
    print("=" * 70)
    print("Case B: image in TOOL message  (expected: 200 OK; actual: 500)")
    print("=" * 70)
    resp = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "user",
             "content": "Download https://example.com/x.png and describe it."},
            {"role": "assistant", "content": "", "tool_calls": [
                {"id": "call_1", "type": "function",
                 "function": {"name": "download_image",
                              "arguments": '{"url": "https://example.com/x.png"}'}},
            ]},
            {"role": "tool", "tool_call_id": "call_1", "content": [
                {"type": "text", "text": "Image downloaded successfully."},
                {"type": "image_url", "image_url": {"url": IMAGE_DATA_URL}},
            ]},
        ],
        max_tokens=64,
    )
    print("OK ->", resp.choices[0].message.content)


if __name__ == "__main__":
    try:
        case_A_user_multimodal()
    except Exception as e:
        print("Case A FAILED unexpectedly:", e, file=sys.stderr)

    print()

    try:
        case_B_tool_multimodal()
    except Exception as e:
        print("Case B FAILED (this is the bug):", e, file=sys.stderr)

Output of the above script:

======================================================================
Case A: image in USER message  (expected: 200 OK)
======================================================================
OK -> This is a solid black image.

======================================================================
Case B: image in TOOL message  (expected: 200 OK; actual: 500)
======================================================================
Case B FAILED (this is the bug): Error code: 500 - {'error': {'message': "Failed to apply prompt replacement for mm_items['image'][0]", 'type': 'InternalServerError', 'param': None, 'code': 500}}

The following error traceback can be found in the server log:

(APIServer pid=1001884) INFO:     10.200.99.229:12273 - "POST /tokenize HTTP/1.1" 500 Internal Server Error
(APIServer pid=1001884) ERROR:    Exception in ASGI application
(APIServer pid=1001884) Traceback (most recent call last):
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/uvicorn/protocols/http/httptools_impl.py", line 421, in run_asgi
(APIServer pid=1001884)     result = await app(  # type: ignore[func-returns-value]
(APIServer pid=1001884)              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/uvicorn/middleware/proxy_headers.py", line 56, in __call__
(APIServer pid=1001884)     return await self.app(scope, receive, send)
(APIServer pid=1001884)            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/fastapi/applications.py", line 1159, in __call__
(APIServer pid=1001884)     await super().__call__(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/applications.py", line 107, in __call__
(APIServer pid=1001884)     await self.middleware_stack(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/middleware/errors.py", line 186, in __call__
(APIServer pid=1001884)     raise exc
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/middleware/errors.py", line 164, in __call__
(APIServer pid=1001884)     await self.app(scope, receive, _send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/middleware/cors.py", line 87, in __call__
(APIServer pid=1001884)     await self.app(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/prometheus_fastapi_instrumentator/middleware.py", line 177, in __call__
(APIServer pid=1001884)     raise exc
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/prometheus_fastapi_instrumentator/middleware.py", line 175, in __call__
(APIServer pid=1001884)     await self.app(scope, receive, send_wrapper)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/middleware/exceptions.py", line 63, in __call__
(APIServer pid=1001884)     await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/_exception_handler.py", line 53, in wrapped_app
(APIServer pid=1001884)     raise exc
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/_exception_handler.py", line 42, in wrapped_app
(APIServer pid=1001884)     await app(scope, receive, sender)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__
(APIServer pid=1001884)     await self.app(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/routing.py", line 716, in __call__
(APIServer pid=1001884)     await self.middleware_stack(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/routing.py", line 736, in app
(APIServer pid=1001884)     await route.handle(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/routing.py", line 290, in handle
(APIServer pid=1001884)     await self.app(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/fastapi/routing.py", line 134, in app
(APIServer pid=1001884)     await wrap_app_handling_exceptions(app, request)(scope, receive, send)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/_exception_handler.py", line 53, in wrapped_app
(APIServer pid=1001884)     raise exc
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/starlette/_exception_handler.py", line 42, in wrapped_app
(APIServer pid=1001884)     await app(scope, receive, sender)
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/fastapi/routing.py", line 120, in app
(APIServer pid=1001884)     response = await f(request)
(APIServer pid=1001884)                ^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/fastapi/routing.py", line 674, in app
(APIServer pid=1001884)     raw_response = await run_endpoint_function(
(APIServer pid=1001884)                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/fastapi/routing.py", line 328, in run_endpoint_function
(APIServer pid=1001884)     return await dependant.call(**values)
(APIServer pid=1001884)            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/entrypoints/utils.py", line 95, in wrapper
(APIServer pid=1001884)     return handler_task.result()
(APIServer pid=1001884)            ^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/entrypoints/serve/tokenize/api_router.py", line 52, in tokenize
(APIServer pid=1001884)     generator = await handler.create_tokenize(request, raw_request)
(APIServer pid=1001884)                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/entrypoints/serve/tokenize/serving.py", line 82, in create_tokenize
(APIServer pid=1001884)     _, engine_inputs = await self.openai_serving_render.preprocess_chat(
(APIServer pid=1001884)                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/entrypoints/serve/render/serving.py", line 557, in preprocess_chat
(APIServer pid=1001884)     (conversation,), (engine_input,) = await renderer.render_chat_async(
(APIServer pid=1001884)                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/renderers/base.py", line 1034, in render_chat_async
(APIServer pid=1001884)     eng_prompts = await asyncio.gather(
(APIServer pid=1001884)                   ^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/renderers/base.py", line 910, in process_for_engine_async
(APIServer pid=1001884)     engine_input = await self._process_singleton_async(
(APIServer pid=1001884)                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/renderers/base.py", line 822, in _process_singleton_async
(APIServer pid=1001884)     return await self._process_tokens_async(prompt, skip_mm_cache=skip_mm_cache)  # type: ignore[arg-type]
(APIServer pid=1001884)            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/renderers/base.py", line 784, in _process_tokens_async
(APIServer pid=1001884)     engine_input = await self._process_multimodal_async(
(APIServer pid=1001884)                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/lib/python3.12/concurrent/futures/thread.py", line 58, in run
(APIServer pid=1001884)     result = self.fn(*self.args, **self.kwargs)
(APIServer pid=1001884)              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/renderers/base.py", line 709, in _process_multimodal
(APIServer pid=1001884)     mm_inputs = mm_processor.apply(mm_processor_inputs, mm_timing_ctx)
(APIServer pid=1001884)                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/multimodal/processing/processor.py", line 1689, in apply
(APIServer pid=1001884)     prompt_ids, mm_placeholders = self._maybe_apply_prompt_updates(
(APIServer pid=1001884)                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/multimodal/processing/processor.py", line 1655, in _maybe_apply_prompt_updates
(APIServer pid=1001884)     prompt_ids, mm_placeholders = self._apply_prompt_updates(
(APIServer pid=1001884)                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884)   File "/usr/local/lib/python3.12/dist-packages/vllm/multimodal/processing/processor.py", line 1565, in _apply_prompt_updates
(APIServer pid=1001884)     assert update_idx is not None, (
(APIServer pid=1001884)            ^^^^^^^^^^^^^^^^^^^^^^
(APIServer pid=1001884) AssertionError: Failed to apply prompt replacement for mm_items['image'][0]

Comparison with model loaded by transformers

Script to load the model and send the inputs:

from __future__ import annotations

import os
import sys
from typing import Any

import torch
from transformers import AutoModelForImageTextToText, AutoProcessor

MODEL_PATH = os.environ.get(
    "GEMMA4_MODEL_PATH",
    "/home/<user_name>/Models/Gemma4-31B-it",
)

# 1x1 transparent PNG -- small but valid. Same bytes are used by the vLLM
# MRE so the two reports are directly comparable.
TINY_PNG_B64 = (
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAA"
    "jCB0C8AAAAASUVORK5CYII="
)
IMAGE_DATA_URL = f"data:image/png;base64,{TINY_PNG_B64}"


# NOTE: this processor's apply_chat_template iterates `content` looking
# for dict items with a "type" key, so plain-string content crashes with
# TypeError. We pass content as a list of parts everywhere.
MESSAGES_CASE_A = [
    {"role": "user", "content": [
        {"type": "text", "text": "Describe this image briefly."},
        {"type": "image_url", "image_url": {"url": IMAGE_DATA_URL}},
    ]},
]

MESSAGES_CASE_B = [
    {"role": "user", "content": [
        {"type": "text",
         "text": "Download https://example.com/x.png and describe it."},
    ]},
    {"role": "assistant",
     "content": [{"type": "text", "text": ""}],
     "tool_calls": [
        {"id": "call_1", "type": "function",
         "function": {"name": "download_image",
                      "arguments": '{"url": "https://example.com/x.png"}'}},
    ]},
    {"role": "tool", "tool_call_id": "call_1", "content": [
        {"type": "text", "text": "Image downloaded successfully."},
        {"type": "image_url", "image_url": {"url": IMAGE_DATA_URL}},
    ]},
]


def chat(
    processor: Any,
    model: Any,
    messages: list[dict[str, Any]],
    *,
    max_new_tokens: int = 1024,
    do_sample: bool = False,
) -> str:
    inputs = processor.apply_chat_template(
        messages,
        add_generation_prompt=True,
        tokenize=True,
        return_dict=True,
        return_tensors="pt",
    ).to(model.device)
    prompt_len = inputs["input_ids"].shape[-1]
    with torch.inference_mode():
        out = model.generate(
            **inputs,
            max_new_tokens=max_new_tokens,
            do_sample=do_sample,
        )
    return processor.batch_decode(
        out[:, prompt_len:],
        skip_special_tokens=True,
    )[0]


def run_case(label: str, processor, model, messages) -> None:
    print("=" * 70)
    print(label)
    print("=" * 70)
    try:
        out = chat(processor, model, messages)
        print("OK ->", out)
    except Exception as e:  # noqa: BLE001
        print("FAILED:", type(e).__name__, str(e)[:500], file=sys.stderr)


if __name__ == "__main__":
    processor = AutoProcessor.from_pretrained(MODEL_PATH)
    model = AutoModelForImageTextToText.from_pretrained(
        MODEL_PATH,
        dtype=torch.bfloat16,
        device_map="auto",
    )
    model.eval()

    run_case("Case A: image in USER message", processor, model, MESSAGES_CASE_A)
    print()
    run_case("Case B: image in TOOL message", processor, model, MESSAGES_CASE_B)

Outputs of the above script:

Loading weights: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1188/1188 [00:09<00:00, 125.00it/s]
======================================================================
Case A: image in USER message
======================================================================
[transformers] The channel dimension is ambiguous. Got image shape torch.Size([3, 1, 1]). Assuming channels are the first dimension. Use the [input_data_format](https://huggingface.co/docs/transformers/main/internal/image_processing_utils#transformers.image_transforms.rescale.input_data_format) parameter to assign the channel dimension.
[transformers] The following generation flags are not valid and may be ignored: ['top_p', 'top_k']. Set `TRANSFORMERS_VERBOSITY=info` for more details.
OK -> This is a solid black image.

======================================================================
Case B: image in TOOL message
======================================================================
[transformers] The channel dimension is ambiguous. Got image shape torch.Size([3, 1, 1]). Assuming channels are the first dimension. Use the [input_data_format](https://huggingface.co/docs/transformers/main/internal/image_processing_utils#transformers.image_transforms.rescale.input_data_format) parameter to assign the channel dimension.
OK -> thought
The image is a solid black square.

Before submitting a new issue...

  • Make sure you already searched for relevant issues, and asked the chatbot living at the bottom right corner of the documentation page, which can answer lots of frequently asked questions.

extent analysis

TL;DR

The issue is likely due to a bug in the vllm library when handling multimodal inputs, specifically when an image is included in a tool message, and can be fixed by updating the vllm library or applying a workaround to handle image data correctly.

Guidance

  1. Check the vllm library version: Ensure you are using the latest version of the vllm library, as the issue might have been fixed in a recent update.
  2. Verify image handling: Confirm that the image data is being handled correctly in the vllm library, specifically when included in a tool message.
  3. Apply a workaround: If the issue persists, consider applying a workaround, such as preprocessing the image data or modifying the vllm library code to handle image data correctly.
  4. Test with a different library: Compare the results with a different library, such as transformers, to isolate the issue and determine if it's specific to vllm.

Example

No code example is provided, as the issue is likely related to the vllm library and its handling of multimodal inputs.

Notes

The issue might be specific to the vllm library and its interaction with the transformers library. Further investigation is needed to determine the root cause and develop a fix.

Recommendation

Apply a workaround to handle image data correctly, such as preprocessing the image data or modifying the vllm library code, until an official fix is available.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING