Skip to content

Python Qwen vision: literal <|image_pad|> in ordinary text is mistaken for an image slot #511

Closed as not planned

Description

@jlave-dev

Summary

In the Python Qwen vision preprocessing path, a literal <|image_pad|> in ordinary conversation text is counted as a real image placeholder. A conversation containing an image can therefore fail after a coding tool returns source code quoting that token, even though the structured image inputs are valid.

Observed error: The rendered prompt must contain exactly one image marker for each image (HTTP 400 in the deployed server).

This report is scoped to Python. I read CONTRIBUTING.md and #286: I am not requesting a Python merge or claiming the native Zig engine is affected. Please assess whether the text/media separation issue is relevant to the native implementation.

Versions and verification boundary

  • Reproduced using the unmodified upstream qwen_processing.py from v0.6.0 (c4646171139ee8a3c38103eaa1699dad226ec12b).
  • Also reproduced using the unmodified file from python-0.6 at ed78d6fc204d89d90b045bf033d6551e7714f3a1.
  • CPU reproduction environment: Linux ARM64, Python 3.12.3, NumPy 2.1.0.
  • The original deployment uses a customized Python 0.6.0 CUDA build. To isolate it, the tests above loaded the upstream processor source directly in a separate network-disabled container using existing dependencies. This is not a claim that the entire deployment was replaced with a stock installation.
  • No prefix-cache code, GPU work, image decoding, model weights, or private inputs are required by the reproducer.
  • Separately, the deployed checkpoint's actual tokenizer/chat template preserved the literal token: one structured image produced one marker with ordinary text, but two markers when ordinary tool text quoted <|image_pad|>. That template check used dummy image objects and stopped before image decoding.

Minimal CPU-only reproduction

Run the following as python3 repro.py in a Python TensorFold checkout/environment with its ordinary dependencies. Everything below is synthetic; no checkpoint or image is needed.

from tensorfold.vision.qwen_processing import QwenImageProcessor


class Tokenizer:
    def convert_ids_to_tokens(self, token_id):
        return "<|image_pad|>"

    def convert_tokens_to_ids(self, token):
        return 1


class NoImage:
    def to_pil(self):
        raise RuntimeError("CONTROL: reached image decoding; stopped intentionally")


config = {
    "image_token_id": 1,
    "vision_config": {
        "patch_size": 14,
        "spatial_merge_size": 2,
        "temporal_patch_size": 2,
    },
}
frontend = QwenImageProcessor(config, object(), Tokenizer())
image_slot = "<|vision_start|><|image_pad|><|vision_end|>"
for name, tool_text in [
    ("ordinary text", "source code without a reserved token"),
    ("literal token", 'example = "<|image_pad|>"'),
    ("escaped token", 'example = "<|image\\_pad|>"'),
]:
    rendered = image_slot + "\nTool result: " + tool_text
    try:
        frontend.prepare(rendered, [NoImage()])
    except (ValueError, RuntimeError) as error:
        print(f"{name}: {type(error).__name__}: {error}")
        if name == "literal token":
            assert isinstance(error, ValueError)
            assert str(error) == "The rendered prompt must contain exactly one image marker for each image"
        else:
            assert isinstance(error, RuntimeError)
    else:
        raise AssertionError("The test must stop before any image is decoded")

Actual output on both upstream source versions:

ordinary text: RuntimeError: CONTROL: reached image decoding; stopped intentionally
literal token: ValueError: The rendered prompt must contain exactly one image marker for each image
escaped token: RuntimeError: CONTROL: reached image decoding; stopped intentionally

The intentional RuntimeError demonstrates that the controls pass marker validation without decoding an image. The literal-token case fails before that point. Three expected outcomes passed on each of two upstream source versions. These are preprocessing controls, not inference/exactness benchmarks or a full suite run.

Expected versus actual

Expected: A quoted token in plain text/source code is not interpreted as another media attachment; valid structured image inputs remain usable alongside that text.

Actual: The rendered string contains one genuine image placeholder plus one quoted occurrence; global string counting reports two images when only one was supplied. Retrying with unchanged conversation history fails again.

Likely cause and fix direction

QwenImageProcessor.prepare uses:

if rendered_prompt.count(self.image_token) != len(images):
    raise ValueError("The rendered prompt must contain exactly one image marker for each image")

Ordinary text is preserved during media splitting and template rendering, so this count has no provenance information. Later expansion also splits the entire rendered string on marker tokens; removing the validation alone would not fix the collision.

Possible fixes: preserve genuine media-slot provenance through rendering/expansion, or consistently escape reserved vision tokens in plain text before rendering while preserving structured media parts. Regression coverage should include string and multipart text, source-code/tool output, and quoted video markers. Video collisions are a suggested test, not something verified in this report.

Not tested / privacy

No stock full-server HTTP replay, native Zig reproduction, GPU/model qualification, performance measurement, or full regression suite was run. The startup itself was healthy; failure occurred during request preparation. Private conversation contents, images, paths, hostnames, addresses, credentials, and session identifiers are deliberately omitted; the synthetic fixture above isolates the problem.

Activity

  1. Bizuayeu commented on Oct 8, 2026

    @Bizuayeu
    Contributor

    For the port, a data point from GLM: its Python processor (vision/glm_processing.py) had the same count check. We rewrote it in our fork after MiaAI-Lab's patch 0080: a marker outside the real <|begin_of_image|><|image|><|end_of_image|> sequence is kept as text, by putting a zero-width space after its <|. A conversation that quotes <|image|> beside a real picture now answers 200 and reads the picture, on GLM-5.3-Flash at TP=2 and TP=3. A conversation that quotes the whole begin/image/end sequence is still counted as an image, so the question of separating text from media stays open there too.

  2. ashhart commented on Oct 10, 2026

    @ashhart
    Owner

    Thank you, @jlave-dev, for the CPU-only reproducer and for keeping the claim to the Python path, and thanks to @Bizuayeu for the GLM data point. The miscount is real: the Python Qwen frontend counts image slots in the rendered text, so a tool result that quotes <|image_pad|> looks like a second image. The Python engine is frozen at 0.6.6, so it will not change there. The native server in 1.0.x accepts text only and refuses image parts, so it has no slots to miscount. When native image input lands (#565), this is one of its requirements: images are counted from the request's structured parts, never from text a tool returned. Please reopen if a native build with images shows the same failure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions